text
stringlengths
8
6.88M
/*********************************************************************** * created: Fri Sep 19 2014 * author: Martin Preisler *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include <boost/test/unit_test.hpp> #include "PerformanceTest.h" #include "CEGUI/PropertySet.h" #include <sstream> static const CEGUI::String PROPERTY_NAME("ExplicitlyAddedTestProperty"); class PropertySetStringPerformanceTest : public PerformanceTest { public: PropertySetStringPerformanceTest(const CEGUI::String& test_name, CEGUI::PropertySet& set): PerformanceTest(test_name), d_propertySet(set) {} virtual void doTest() { for (unsigned int i = 0; i < 1000000; ++i) { d_propertySet.setProperty(PROPERTY_NAME, "{ { 1, 0 }, {0.5, 100} }"); } } CEGUI::PropertySet& d_propertySet; }; class PropertySetTypedPerformanceTest : public PerformanceTest { public: PropertySetTypedPerformanceTest(const CEGUI::String& test_name, CEGUI::PropertySet& set): PerformanceTest(test_name), d_propertySet(set) {} virtual void doTest() { for (unsigned int i = 0; i < 1000000; ++i) { d_propertySet.setProperty<CEGUI::UVector2>(PROPERTY_NAME, CEGUI::UVector2(CEGUI::UDim(1, 0), CEGUI::UDim(0.5, 100))); } } CEGUI::PropertySet& d_propertySet; }; class TestingPropertySet : public CEGUI::PropertySet { public: TestingPropertySet() { const CEGUI::String propertyOrigin("abc"); CEGUI_DEFINE_PROPERTY(TestingPropertySet, CEGUI::UVector2, PROPERTY_NAME, "Doc", &TestingPropertySet::setTestingProperty, &TestingPropertySet::getTestingProperty, CEGUI::UVector2() ); } void setTestingProperty(const CEGUI::UVector2& v) { d_testingProperty = v; } const CEGUI::UVector2& getTestingProperty() const { return d_testingProperty; } private: CEGUI::UVector2 d_testingProperty; }; BOOST_AUTO_TEST_SUITE(PropertySetPerformance) BOOST_AUTO_TEST_CASE(StringSetTest) { TestingPropertySet set; PropertySetStringPerformanceTest test("PropertySet String set test", set); test.execute(); } BOOST_AUTO_TEST_CASE(TypedSetTest) { TestingPropertySet set; PropertySetTypedPerformanceTest test("PropertySet typed set test", set); test.execute(); } BOOST_AUTO_TEST_SUITE_END()
#ifdef FASTCG_VULKAN #include <FastCG/Graphics/Vulkan/VulkanTexture.h> #include <FastCG/Graphics/Vulkan/VulkanGraphicsSystem.h> #include <FastCG/Graphics/Vulkan/VulkanExceptions.h> #include <cstring> namespace FastCG { VulkanTexture::VulkanTexture(const Args &rArgs) : BaseTexture(rArgs), mImage(rArgs.image) { if (mImage == VK_NULL_HANDLE) { CreateImage(); } #if _DEBUG VulkanGraphicsSystem::GetInstance()->SetObjectName(GetName().c_str(), VK_OBJECT_TYPE_IMAGE, (uint64_t)mImage); #endif CreateDefaultImageView(); if ((GetUsage() & TextureUsageFlagBit::SAMPLED) != 0) { CreateDefaultSampler(); } TransitionToRestingLayout(); } VulkanTexture::~VulkanTexture() { DestroyDefaultSampler(); DestroyDefaultImageView(); if (OwnsImage()) { DestroyImage(); } } void VulkanTexture::CreateImage() { VkImageCreateInfo imageCreateInfo; imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.pNext = nullptr; imageCreateInfo.flags = 0; imageCreateInfo.imageType = GetVkImageType(GetType()); imageCreateInfo.format = GetVulkanFormat(); imageCreateInfo.extent = {GetWidth(), GetHeight(), 1}; // 3D texture not supported yet imageCreateInfo.mipLevels = 1; // mipped texture not supported yet imageCreateInfo.arrayLayers = 1; // array texture not supported yet imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; // multisampled texture not supported yet const auto *pFormatProperties = VulkanGraphicsSystem::GetInstance()->GetFormatProperties(imageCreateInfo.format); assert(pFormatProperties != nullptr); bool usesMappableMemory = false; if ((pFormatProperties->optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0) { imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; } else if ((pFormatProperties->linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0) { imageCreateInfo.tiling = VK_IMAGE_TILING_LINEAR; // linearly tiled images should use mappable memory at the moment usesMappableMemory = true; } else { FASTCG_THROW_EXCEPTION(Exception, "Vulkan: No tiling features found for format %s", GetVkFormatString(imageCreateInfo.format)); } imageCreateInfo.usage = GetVkImageUsageFlags(GetUsage(), GetFormat()); imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocationCreateInfo; if (usesMappableMemory) { allocationCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; } else { allocationCreateInfo.flags = 0; } allocationCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; allocationCreateInfo.requiredFlags = 0; allocationCreateInfo.preferredFlags = 0; allocationCreateInfo.memoryTypeBits = 0; allocationCreateInfo.pool = VK_NULL_HANDLE; allocationCreateInfo.pUserData = nullptr; allocationCreateInfo.priority = 0; FASTCG_CHECK_VK_RESULT(vmaCreateImage(VulkanGraphicsSystem::GetInstance()->GetAllocator(), &imageCreateInfo, &allocationCreateInfo, &mImage, &mAllocation, &mAllocationInfo)); if (GetData() != nullptr) { VulkanGraphicsSystem::GetInstance()->GetImmediateGraphicsContext()->Copy(this, GetDataSize(), GetData()); } } void VulkanTexture::DestroyImage() { if (mImage != VK_NULL_HANDLE) { vmaDestroyImage(VulkanGraphicsSystem::GetInstance()->GetAllocator(), mImage, mAllocation); mImage = VK_NULL_HANDLE; mAllocation = VK_NULL_HANDLE; } } void VulkanTexture::TransitionToRestingLayout() { VulkanGraphicsSystem::GetInstance()->GetImmediateGraphicsContext()->AddTextureMemoryBarrier(this, GetRestingLayout(), 0, VK_ACCESS_MEMORY_READ_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); } void VulkanTexture::CreateDefaultImageView() { switch (GetType()) { case TextureType::TEXTURE_2D: VkImageViewCreateInfo imageViewCreateInfo; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.pNext = nullptr; imageViewCreateInfo.flags = 0; imageViewCreateInfo.image = mImage; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.format = GetVulkanFormat(); imageViewCreateInfo.components = VkComponentMapping{VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}; if (IsDepthFormat(GetFormat())) { // TODO: support stencil imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; } else { imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; } imageViewCreateInfo.subresourceRange.baseMipLevel = 0; imageViewCreateInfo.subresourceRange.levelCount = 1; // mipped texture not supported yet imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; imageViewCreateInfo.subresourceRange.layerCount = 1; // array texture not supported yet FASTCG_CHECK_VK_RESULT(vkCreateImageView(VulkanGraphicsSystem::GetInstance()->GetDevice(), &imageViewCreateInfo, VulkanGraphicsSystem::GetInstance()->GetAllocationCallbacks(), &mDefaultImageView)); break; default: FASTCG_THROW_EXCEPTION(Exception, "Vulkan: Can't create image view for texture type %s", GetTextureTypeString(GetType())); break; } #if _DEBUG VulkanGraphicsSystem::GetInstance()->SetObjectName((GetName() + " View").c_str(), VK_OBJECT_TYPE_IMAGE_VIEW, (uint64_t)mDefaultImageView); #endif } void VulkanTexture::CreateDefaultSampler() { VkSamplerCreateInfo samplerCreateInfo; samplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerCreateInfo.pNext = nullptr; samplerCreateInfo.flags = 0; samplerCreateInfo.magFilter = samplerCreateInfo.minFilter = GetVkFilter(GetFilter()); samplerCreateInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; samplerCreateInfo.addressModeU = samplerCreateInfo.addressModeV = samplerCreateInfo.addressModeW = GetVkAddressMode(GetWrapMode()); samplerCreateInfo.mipLodBias = 0; samplerCreateInfo.anisotropyEnable = VK_FALSE; samplerCreateInfo.maxAnisotropy = 0; samplerCreateInfo.compareEnable = VK_FALSE; samplerCreateInfo.compareOp = VK_COMPARE_OP_NEVER; samplerCreateInfo.minLod = 0; samplerCreateInfo.maxLod = VK_LOD_CLAMP_NONE; samplerCreateInfo.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; samplerCreateInfo.unnormalizedCoordinates = VK_FALSE; FASTCG_CHECK_VK_RESULT(vkCreateSampler(VulkanGraphicsSystem::GetInstance()->GetDevice(), &samplerCreateInfo, VulkanGraphicsSystem::GetInstance()->GetAllocationCallbacks(), &mDefaultSampler)); #if _DEBUG VulkanGraphicsSystem::GetInstance()->SetObjectName((GetName() + " Sampler").c_str(), VK_OBJECT_TYPE_SAMPLER, (uint64_t)mDefaultSampler); #endif } void VulkanTexture::DestroyDefaultImageView() { if (mDefaultImageView != VK_NULL_HANDLE) { vkDestroyImageView(VulkanGraphicsSystem::GetInstance()->GetDevice(), mDefaultImageView, VulkanGraphicsSystem::GetInstance()->GetAllocationCallbacks()); mDefaultImageView = VK_NULL_HANDLE; } } void VulkanTexture::DestroyDefaultSampler() { if (mDefaultSampler != VK_NULL_HANDLE) { vkDestroySampler(VulkanGraphicsSystem::GetInstance()->GetDevice(), mDefaultSampler, VulkanGraphicsSystem::GetInstance()->GetAllocationCallbacks()); mDefaultSampler = VK_NULL_HANDLE; } } } #endif
/** * Copyright 2019 Eliza Wszola (eliza.wszola@inf.ethz.ch) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PIECE_POOL_H #define PIECE_POOL_H #include "algebra.h" class PiecePool { private: SparsePiece* stack; uint64_t capacity; public: //allocate as many pieces as possible and add them to the stack void allocate(uint64_t available_size, bool hbw); void deallocate(bool hbw); SparsePiece* pop(); void push(SparsePiece* ptr); uint64_t get_capacity(); //how many pieces can I afford? uint64_t get_pieces(); //how many pieces left? }; #endif
#include "core.h" #include "configvar.h" ConfigVar::ConfigVar() : m_Type( EVT_None ) , m_String( NULL ) // Initialize this for the whole union; it's a pointer so it's bigger than the rest on x64 , m_Hash( (unsigned int)0 ) #if PARANOID_HASH_CHECK , m_Name( "" ) #endif { }
//题目:给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 //思路:先排序,按照从大到小排列,最大乘积就是 nums[0]*nums[1]*nums[2] #include<stdio.h> int main() { int nums[10] = {1,2,3,4,5,6,7,8,9,10}; int numsize = sizeof(nums)/sizeof(nums[0]); int i,j,t,max; for( i = 0;i < numsize-1;i++) for( j = 0;j < (numsize-1-i);j++) if(nums[j]<nums[j+1]){ t = nums[j]; nums[j] = nums[j+1]; nums[j+1] = t; } max = nums[0]*nums[1]*nums[2]; printf("最大乘积 = %d",max); }
// Driver to test class tree #include<iostream> #include"binarytree.h" #include"rbtree.h" int main() { RBTree<int> rbtree; int val; for(int i = 0; i < 10; i++) { std::cin>>val; rbtree.insertNode(val); } //tree.preOrderTraversal(); rbtree.inOrderTraversal(); //tree.postOrderTraversal(); return 0; }
#include <SoftwareSerial.h> // 매크로 상수, 자주 쓰는거 지정 // TX를 2번에 RX를 3번에 연결했다(실제회로). 아두이노에는 반대로 기입해야 한다. #define rxPin 2 #define txPin 3 //swSerial(rxPin, txPin) SoftwareSerial swSerial(rxPin, txPin); // (2,3) char data; void setup() { Serial.begin(9600); swSerial.begin(9600); Serial.println("ready..."); } void loop() { // 시리얼 버퍼를 비우는 작업 Serial.flush(); Serial.println("command : "); // 사용자가 데이터를 입력할 때까지 대기 - 버퍼에 값이 들어올때까지 대기 while(!Serial.available()); // +++++ HC-06에 명령어를 전송 +++++ while(Serial.available()) // 데이터 있냐 없냐에 따라서 True, False를 반환 { data = Serial.read(); // 키보드로 입력하는 블루투스 명령어를 읽어서 if(data == -1) { break; } swSerial.print(data); // 블루투스에 명령어를 전달 Serial.print(data); delay(1); } Serial.println(); // HC-06 (블루투스 모듈) 이 명령어를 받아서 처리할 시간 delay(1000); Serial.println("return : "); // +++++ HC-06으로부터 전송된 데이터를 화면에 출력 +++++ while(swSerial.available()) // 데이터 있냐 없냐에 따라서 True, False를 반환 { data = swSerial.read(); // 키보드로 입력하는 블루투스 명령어를 읽어서 if(data == -1) { break; } Serial.print(data); // 블루투스에 명령어를 전달 delay(1); } Serial.print("\n\n\n"); }
#ifndef _MAZO_ #define _MAZO_ 0 #include <string> #include <vector> #include "cartas.h" vector<Carta> crearmazo(){ vector<Carta> vectorM; for (int i = 0; i<5;i++){ vectorM.push_back(CartaMilagro()); //5 cartas de MILAGRO } for (int i = 0; i<4;i++){ vectorM.push_back(CartaTraicion()); //5 cartas de TRAICION } for (int i = 0; i<7;i++){ vectorM.push_back(CartaAnarquia()); //5 cartas de ANARQUIA } for (int i = 0; i<4;i++){ vectorM.push_back(CartaUnion()); //5 cartas de UNION } for (int i = 0; i<4;i++){ vectorM.push_back(CartaNuevoDios()); //5 cartas de NUEVO DIOS } for (int i = 0; i<6;i++){ vectorM.push_back(CartaRetorno()); //5 cartas de RETORNO } for (int i = 0; i<10;i++){ vectorM.push_back(CartaMuerte()); //5 cartas de MUERTE } return vectorM; } #endif
//***************************************************** // VMA209 Push button and LED test // written by Patrick De Coninck / Velleman NV. // VMA209 contains 3 Push buttons, they are connected to the Arduino Analog inputs A1, A2, A3 // in this example we will switch ON LED1 when pushing Push button 3 - please feel free to choose different buttons or LEDS //**************************************************** int ledpin=13; //Define integer ledpin with a value of 13 int inpin=A3; //Define integer inpin = analog line A3 int val; // define variable VAL void setup() { pinMode(ledpin,OUTPUT);//Declare ledpin (which has a value of 13) as OUTPUT pinMode(inpin,INPUT);//Declare inpin (which is analog input A3) as INPUT } void loop() { val=digitalRead(inpin);//Read the value of Analog line 13 (push button) if(val==LOW) //If this value is LOW: { digitalWrite(ledpin,LOW);} // then ledpin (the led on digital line 13) is also LOW (off) else { digitalWrite(ledpin,HIGH);} // in the other case (ledpin is not low) switch ON the LED on D13 }
#include "producto.h" Producto::Producto(string nombre_p,float costo_p,int id_p) { this->id_producto = id_p; this->nombre_producto = nombre_p; this->costo_producto = costo_p; } float Producto::getCostoProducto(){ if(costo_producto>100){ costo_producto = costo_producto - (costo_producto*0.1); }else if(costo_producto>200){ costo_producto = costo_producto - (costo_producto*0.2); }else if(costo_producto>300){ costo_producto = costo_producto - (costo_producto*0.3); } return costo_producto; } string Producto::getNombreProducto(){ return nombre_producto; } int Producto::getIdProducto(){ return id_producto; } Producto::~Producto() { }
/* * Copyright (c) 2013-2015 BlackBerry Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "service.hpp" #include <bb/Application> #include <bb/platform/Notification> #include <bb/platform/NotificationDefaultApplicationSettings> #include <bb/system/InvokeManager> #include <bb/system/InvokeTimerRequest> #include <bb/system/InvokeReply> #include <QSettings> #include <QTimer> using namespace bb::platform; using namespace bb::system; Service::Service() : QObject(), m_notify(new Notification(this)), m_invokeManager(new InvokeManager(this)), m_ppsWatch(new PpsWatch("/pps/system/development/devmode", this)) { m_invokeManager->connect(m_invokeManager, SIGNAL(invoked(const bb::system::InvokeRequest&)), this, SLOT(handleInvoke(const bb::system::InvokeRequest&))); NotificationDefaultApplicationSettings settings; settings.setPreview(NotificationPriorityPolicy::Allow); settings.apply(); connect(m_ppsWatch, SIGNAL(ppsFileReady(const QVariantMap&)), this, SLOT(onPpsFileReady(const QVariantMap&))); } void Service::checkTokenExpiracy() { bb::PpsObject ppsObject("/pps/system/development/devmode"); if (ppsObject.open( bb::PpsOpenMode::Subscribe )) { bool readOk; QByteArray data = ppsObject.read(&readOk); if(!readOk) { return; } bool decodeOk; const QVariantMap map = bb::PpsObject::decode(data, &decodeOk); if(!decodeOk) { return; } const QVariantMap ppsFile = map["@devmode"].toMap(); if (ppsFile.isEmpty()) { return; } this->onPpsFileReady(ppsFile); } } void Service::handleInvoke(const bb::system::InvokeRequest & request) { qDebug() << "handleInvoke" << request.action(); if (request.action().compare("bb.action.system.TIMER_FIRED") == 0) { this->triggerNotification(); } else { this->checkTokenExpiracy(); } } void Service::invalidTokenExpiration() { qDebug() << "Invalid date"; Notification::clearEffectsForAll(); Notification::deleteAllFromInbox(); m_notify->setTitle("The token expiration could not be retrieved."); m_notify->setBody("You may not have any token installed, please update your token in Momentics. This app will continue running (headless) until you update your token."); bb::system::InvokeRequest request; request.setTarget("com.CellNinja.TokenExpiration"); request.setAction("bb.action.START"); m_notify->setInvokeRequest(request); m_notify->notify(); } void Service::onFinished() { qDebug() << "onFinished()" << m_invokeReply->errorCode() << m_invokeReply->error(); if ((m_invokeReply->errorCode() == 0) || (m_invokeReply->error() == bb::system::InvokeReplyError::None)) { bb::Application::instance()->quit(); } else { qDebug() << "There was an error, check back in an hour, when things will have cool down ;)"; QTimer::singleShot((1000 * 60 * 60), this, SLOT(checkTokenExpiracy())); } } void Service::onPpsFileReady(const QVariantMap& map) { qDebug() << "onPpsFileReady():" << map; QString dateTime = map["debug_token_expiration"].toString(); int start = dateTime.lastIndexOf(":") + 2; int length = dateTime.lastIndexOf(" ") - start; const QDateTime expirationDateTime = QDateTime::fromString(dateTime.remove(start, length)); if (!expirationDateTime.isValid()) { this->invalidTokenExpiration(); } QSettings settings; settings.setValue("expirationDateTime", expirationDateTime); this->setTimerTrigger(expirationDateTime); } void Service::triggerNotification() { Notification::clearEffectsForAll(); Notification::deleteAllFromInbox(); QSettings settings; QDateTime dateTime = settings.value("expirationDateTime", QDateTime::currentDateTime().addDays(2)).toDateTime(); if (QDateTime::currentDateTime().msecsTo(dateTime) < 0) { m_notify->setTitle("Your Debug Token is expired."); m_notify->setBody("Expiration: " + dateTime.toString() + "\n\nThis app will continue running (headless) until you update your token."); bb::system::InvokeRequest request; request.setTarget("com.CellNinja.TokenExpiration"); request.setAction("bb.action.START"); m_notify->setInvokeRequest(request); } else { m_notify->setTitle("Your Debug Token is about to expire."); m_notify->setBody("Expiration: " + dateTime.toString()); } m_notify->notify(); } void Service::setTimerTrigger(const QDateTime& expirationDateTime) { int daysToExpiration = QDateTime::currentDateTime().daysTo(expirationDateTime); if (daysToExpiration <= 0) { this->triggerNotification(); // Keep running headless to get notified when token is updated return; } int daysBefore = (daysToExpiration > 2) ? 2 : 1; QDateTime notificationDateTime = expirationDateTime.addDays(-daysBefore); qDebug() << "Timer trigger set to" << notificationDateTime.toString("yyyy/MM/dd hh:mm"); // Set the timer trigger for 2 days before expiration InvokeDateTime trigdatetime(notificationDateTime.date(), notificationDateTime.time(), ""); qDebug() << trigdatetime.date() << trigdatetime.time(); // Create the timer request InvokeTimerRequest timer_request("debugTokenTrigger", trigdatetime, "com.CellNinja.TokenExpirationService"); m_invokeManager->deregisterTimer("debugTokenTrigger"); m_invokeReply = m_invokeManager->registerTimer(timer_request); connect(m_invokeReply, SIGNAL(finished()), this, SLOT(onFinished())); }
/***************************************************************************************************** * 剑指offer第33题 * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 * * Input: 一维数组 * Output: 数组中所有数字组成的最小的数 * * Note: (考虑到新建比较规则,并且涉及到大数问题,可能会有数据溢出,考虑字符串) * key:自定义一个比较大小的函数,比较两个字符串s1, s2大小的时候,先将它们拼接起来,比较s1+s2,和s2+s1那个大, 如果s1+s2大,那说明s2应该放前面,所以按这个规则,s2就应该排在s1前面。 * author: lcxanhui@163.com * time: 2019.5.15 ******************************************************************************************************/ #include<iostream> #include<vector> #include<string> #include<sstream> #include <algorithm> using namespace std; //如果题目要求得出最大的数字,可以将比较器转换成从大到小排序即可 //其中,数字转化为字符串的使用方法,参考别人的代码 static bool compare(const string &st1, const string &st2) { string s1 = st1 + st2; string s2 = st2 + st1; return s1 < s2; //降序排列,改为大于就是升序排列!! } string PrintMinNumber(vector<int> numbers) { string res; if (numbers.size() <= 0) return res; vector<string> vec; for (int i = 0; i < numbers.size(); i++) { stringstream ss; //使用输入输出流,头文件要包含#include<sstream> ss << numbers[i]; //读入数字给流处理 string s = ss.str(); //转换成字符串 vec.push_back(s); //将字符串s压入vec中 } //排序,传入比较器,从小到大排序 // compare作为比较器供sort函数调用,因为不是单纯的比较两个数值的大小而是 //比较两个数分别前后串起来数值的大小,所以要重写比较器 sort(vec.begin(), vec.end(), compare); for (int i = 0; i < vec.size(); i++) res.append(vec[i]); //拼接字符串,这就是最小的数字 return res; } int main(void) { vector<int> numbers{ 3,321,22,43 }; string result = PrintMinNumber(numbers); cout << result; return 0; }
#include "competitive.h" USESTD; /* * Used to solve APSP. O(V^3). * It can also be used for checking transitive closures: * initially, AdjMat[i][j] contains 1 (true) if vertex i is directly connected to vertex j, * 0 (false) otherwise. Perform this operation: AdjMat[i][j] |= (AdjMat[i][k] & AdjMat[k][j]). * We can check if any two vertices i and j are directly or indirectly connected by checking AdjMat[i][j]. */ void apsp_warshall(int (&adjMat)[100][100], int (&parent)[100][100], int V) { LOOP(i,0,V) LOOP(j,0,V) parent[i][j] = i; for (int k = 0; k < V; k++) // remember that loop order is k->i->j for (int i = 0; i < V; i++) for (int j = 0; j < V; j++) if (adjMat[i][k] + adjMat[k][j] < adjMat[i][j]) { adjMat[i][j] = adjMat[i][k] + adjMat[k][j]; parent[i][j] = parent[k][j]; // update the parent matrix } } int main() { // precondition: AdjMat[i][j] contains the weight of edge (i, j) // or INF (1B) if there is no such edge // AdjMat is a 32-bit signed integer array int INF = 1000000000; int adjMat[100][100]; int parent[100][100]; int V = 6; LOOP(i,0,100) LOOP(j,0,100) adjMat[i][j] = INF; adjMat[0][1] = 3; adjMat[1][0] = 3; adjMat[1][2] = 4; adjMat[2][1] = 4; adjMat[1][3] = 2; adjMat[3][1] = 2; adjMat[1][4] = 1; adjMat[4][1] = 1; adjMat[3][4] = 5; adjMat[4][3] = 5; apsp_warshall(adjMat, parent, V); int source = 3; int dest = 0; cout << "Cost: " << adjMat[source][dest] << endl; cout << "Path: "; while (parent[source][dest] != source) { cout << dest << " "; dest = parent[source][dest]; } cout << dest << " " << source << endl; }
#include <bits/stdc++.h> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } struct DSU{ vector<ll> e; DSU(ll N){ e = vector<ll>(N, -1); }; ll get(ll x){ print(e); return e[x] < 0 ? x : e[x] = get(e[x]); }; ll size(ll x){ return -e[get(x)]; }; bool unite(ll a, ll b){ ll x = get(a); ll y = get(b); cout << x << " " << y << endl; if(x == y) return false; if(e[x] > e[y]) swap(x, y); e[x] += e[y]; e[y] = x; return true; }; }; int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); DSU dsu(6); dsu.unite(3, 1); cout << dsu.size(3) << endl; dsu.unite(3, 2); //dsu.unite(3, 4); //dsu.unite(4, 5); print(dsu.e); }
// note that if((bitOper[i] & bitOper[j]) == 0) but not if(bitOper[i] & bitOper[j] == 0) class Solution { public: int maxProduct(vector<string>& words) { if(words.empty()) return 0; int res = 0; int n = words.size(); vector<int> bitOper(n, 0); for(int i = 0; i < n; i++) for(int j = 0; j < words[i].size(); j++) bitOper[i] = bitOper[i] | (1 << (words[i][j] - 'a')); for(int i = 0; i < words.size() - 1; i++) for(int j = i + 1; j < words.size(); j++) if((bitOper[i] & bitOper[j]) == 0) res = max(res, (int)words[i].size() * (int)words[j].size()); return res; } };
//============================================================================ // Name : lab3.cpp // Author : Philippe Gelinas // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <list> #include <chrono> #include "algorithm.h" #include "graph.h" using namespace std; int main() { int z; int choice,start,stop,method; std::chrono::system_clock::time_point start_time,end_time; std::chrono::duration<double> time_count; std::vector<int> x;; CGraph * G = new(CGraph); algorithm Al; std::cout << "\033[2J\033[1;1H"; while(choice !='q' && method!='q' && start !='q' && stop !='q'){ std::cout<<"=====LAB3 Testbench=====\n"; std::cout<<"Veuillez entrer le type de probleme a resoudre\n"; std::cout<<"1. Labyrinthe/TL\n2. Carte routiere\n"; std::cin>>choice; G->createNewGraph(); std::cout<<"Veuillez entrer le noeud de depart\n"; std::cin>>start; std::cout<<"Veuillez entrer le noeud d'arriver\n"; std::cin>>stop; std::cout<<"Veuillez entrer le type d'algorithm\n"; if(choice==1){ std::cout<<"1. Recherche en profondeur\n2. Recherche en largeur\n"; std::cin>>method; switch(method){ case 1: G->resetVisited(); G->resetDistance(); x.resize(G->N); x.clear(); start_time = std::chrono::high_resolution_clock::now(); if(Al.deep_search(G->graph,start,stop,x)){ end_time = std::chrono::high_resolution_clock::now(); std::cout<<"Path found"; G->displayViewedNodes(); G->displayPath(x); std::cout<<"Number of node visited :"<<x.size(); time_count = end_time - start_time; std::cout << "\nElapsed time: " << time_count.count() << "s\n"; } else{ std::cout<<"Path not found"; } break; case 2: G->resetVisited(); G->resetDistance(); x.resize(G->N); x.clear(); start_time = std::chrono::high_resolution_clock::now(); if(Al.wide_search(G,start,stop,x)){ std::cout<<"Path found"; } else{ std::cout<<"Path not found\n"; } end_time = std::chrono::high_resolution_clock::now(); G->displayViewedNodes(); G->displayPath(x); std::cout<<"Number of node visited :"<<x.size(); time_count = end_time - start_time; std::cout << "\nElapsed time: " << time_count.count() << "s\n"; break; default: break; } } else{ std::cout<<"1. Recherche en profondeur\n2. Dijkstra\n3. Floyd-Warshall\n"; std::cin>>method; switch(method){ case 1: G->resetVisited(); x.resize(G->N); x.clear(); start_time = std::chrono::high_resolution_clock::now(); if(Al.deep_search_weight(G->graph,start,stop,x)){ std::cout<<"Path found"; } else{ std::cout<<"Path not found\n"; } end_time = std::chrono::high_resolution_clock::now(); G->displayViewedNodes(); G->displayPath(x); cout<<"Solution cost : "<<G->countSolutionCost(x)<<'\n'; std::cout<<"Number of node visited :"<<x.size(); time_count = end_time - start_time; std::cout << "\nElapsed time: " << time_count.count() << "s\n"; break; case 2: G->resetVisited(); x.resize(G->N); x.clear(); start_time = std::chrono::high_resolution_clock::now(); if(Al.dijkstra_search(G,start,stop,x)){ std::cout<<"Path found"; } else{ std::cout<<"Path not found\n"; } end_time = std::chrono::high_resolution_clock::now(); G->displayViewedNodes(); G->displayPath(x); cout<<"Solution cost : "<<G->countSolutionCost(x)<<'\n'; std::cout<<"Number of node visited :"<<x.size(); time_count = end_time - start_time; std::cout << "\nElapsed time: " << time_count.count() << "s\n"; break; case 3: G->resetVisited(); x.resize(G->N); x.clear(); start_time = std::chrono::high_resolution_clock::now(); if(Al.floyd_warshal_search(G,start,stop,x)){ std::cout<<"Path found"; } else{ std::cout<<"Path not found\n"; } end_time = std::chrono::high_resolution_clock::now(); G->displayViewedNodes(); G->displayPath(x); cout<<"Solution cost : "<<G->countSolutionCost(x)<<'\n'; std::cout<<"Number of node visited :"<<x.size(); time_count = end_time - start_time; std::cout << "\nElapsed time: " << time_count.count() << "s\n"; break; default: break; } } } // x.resize(G->N); // // start_time = std::chrono::high_resolution_clock::now(); // // Al.floyd_warshal_search(G,0,4,x); // // G->displayViewedNodes(); // // G->displayPath(x); // // z = G->countSolutionCost(x); // // cout << "\nTotal cost = " << z; // // end_time = std::chrono::high_resolution_clock::now(); // // time_count = end_time - start_time; // // std::cout << "\nElapsed time: " << time_count.count() << "s\n"; delete G; return 0; }
// // Created by Wesley Moncrief on 4/5/16. // #ifndef RAYTRACING_POINT_H #define RAYTRACING_POINT_H #include <cmath> class Point { public: double x; double y; double z; Point() { x = 0, y = 0, z = 0;} Point(double x, double y, double z) : x(x), y(y), z(z) { } double distance(Point pt) const { return sqrt((pt.x - x) * (pt.x - x) + (pt.y - y) * (pt.y - y) + (pt.z - z) * (pt.z - z)); } }; #endif //RAYTRACING_POINT_H
#pragma once #include "VertexFormats.h" #include "VertexBufferManager.h" class RenderMesh { public: RenderMesh(void); ~RenderMesh(void); template <typename VertexFormat> void AddVertices(vector<VertexFormat> vVertices, D3D11_PRIMITIVE_TOPOLOGY ePrimitiveType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); void AddIndices(vector<unsigned int> vIndices); ////////////////////////////////////////////////////////////////////////// // Accessors const unsigned int GetNumVertices(void) const { return m_unNumVertices; } const unsigned int GetNumIndices(void) const { return m_unNumIndices; } const unsigned int GetNumPrimitives(void) const { return m_unNumPrimitives; } const unsigned int GetStartVertex(void) const { return m_unStartVertex; } const unsigned int GetStartIndex(void) const { return m_unStartIndex; } const D3D11_PRIMITIVE_TOPOLOGY GetPrimitiveType(void) const { return m_ePrimitiveType; } const vector<VERTEX_POSCOLOR> GetVertices(void) const { return m_vVertices; } const vector<unsigned int> GetIndices(void) const { return m_vIndices; } ////////////////////////////////////////////////////////////////////////// // Mutators void SetNumVertices(const unsigned int unNumVertices) { m_unNumVertices = unNumVertices; } void SetNumIndices(const unsigned int unNumIndices) { m_unNumIndices = unNumIndices; } void SetNumPrimitives(const unsigned int unNumPrimitives) { m_unNumPrimitives = unNumPrimitives; } void SetStartVertex(const unsigned int unStartVertex) { m_unStartVertex = unStartVertex; } void SetStartIndex(const unsigned int unStartIndex) { m_unStartIndex = unStartIndex; } void SetPrimitiveType(D3D11_PRIMITIVE_TOPOLOGY ePrimitiveType) { m_ePrimitiveType = ePrimitiveType; } void SetNumVertices(const vector<VERTEX_POSCOLOR> vVertices) { m_vVertices = vVertices; } void SetNumVertices(const vector<unsigned int> vIndices) { m_vIndices = vIndices; } private: // Numbers unsigned int m_unNumVertices; unsigned int m_unNumIndices; unsigned int m_unNumPrimitives; unsigned int m_unStartVertex; unsigned int m_unStartIndex; // Primitive Topology D3D11_PRIMITIVE_TOPOLOGY m_ePrimitiveType; // Arrays vector<VERTEX_POSCOLOR> m_vVertices; vector<unsigned int> m_vIndices; }; template <typename VertexFormat> void RenderMesh::AddVertices(vector<VertexFormat> vVertices, D3D11_PRIMITIVE_TOPOLOGY ePrimitiveType) { m_unNumVertices = (unsigned int)vVertices.size(); m_ePrimitiveType = ePrimitiveType; m_unNumPrimitives = m_unNumVertices / 3; if (m_unNumVertices % 3 != 0) m_unNumPrimitives++; m_unStartVertex = VertexBufferManager::GetInstance()->GetVertexBuffer<VertexFormat>().AddVerts(&vVertices[0], m_unNumVertices); }
#include "math/cloud_math.h" #include "io/io.h" #include <iostream> #include <fstream> #include <vector> #include <string> int main(int argc ,char** argv) { if(argc != 1) { std::cout << " Usage: testmath " << std::endl; } pc::PointCloud pts; pc::ReadASC_xyz(argv[1], pts); pc::PointNormal point = mean(pts); std::cout << point.x << " " << point.y << " " << point.z << '\n'; return 0; }
// // Created by anggo on 6/10/2020. // #ifndef TESTER_HEALTH_H #define TESTER_HEALTH_H #include <SFML/Graphics.hpp> class Health : public sf::Drawable { private: sf::Sprite healthIcon; sf::Texture texture; public: Health(std::string filepath); void draw(sf::RenderTarget& window,sf::RenderStates state)const; void setSize(sf::Vector2f size); void setPosition(sf::Vector2f pos); }; #endif //TESTER_HEALTH_H
#pragma once #include <map> #include <string> #include <vector> #include "Comparators.h" struct World { World(std::string name, int seed) : Name(name), Seed(seed) {} std::string Name; int Seed; }; namespace Worlds { std::string Get_Name(int seed); int Get_Seed(std::string name); void Create_World(std::string name, int seed); void Delete_World(std::string name); void Save_World(); void Load_World(int seed); std::vector<World> Get_Worlds(); void Save_Chunk(std::string world, glm::vec3 chunkPos); std::map<glm::vec3, std::pair<int, int>, VectorComparator> Load_Chunk(std::string world, glm::ivec3 pos); };
/** * Date: 2019-11-08 18:43:18 * LastEditors: Aliver * LastEditTime: 2019-11-08 20:57:00 */ #include <iostream> #include <unistd.h> #include <cstdlib> #include <cstring> using namespace std; int main(int argc, char *argv[]) { int pipeFd[2], childPid; // 建立管道 pipeFd[1]写 pipeFd[0]读 if (pipe(pipeFd) == -1) { perror("create pipe error"); exit(EXIT_FAILURE); } // 创建子进程 childPid = fork(); if (childPid == -1) { perror("fork"); exit(EXIT_FAILURE); } // 子进程读 父进程写 if (childPid == 0) { // 关闭写端 close(pipeFd[1]); char buff[16]{}; // 从pipeFd[0] 读 while (read(pipeFd[0], buff, sizeof(buff) - 1) > 0) cout << "pid:" << getpid() << " read from ppid:" << getppid() << " content : " << buff << endl; close(pipeFd[0]); exit(EXIT_SUCCESS); } else { // 关闭读端 close(pipeFd[0]); const char *str = "hello! world"; write(pipeFd[1], str, strlen(str)); cout << "pid:" << getpid() << " write to childPid:" << childPid << " content : " << str << endl; close(pipeFd[1]); exit(EXIT_SUCCESS); } return 0; }
#include <iostream> #include <stdlib.h> #include <conio.h> #include <windows.h> #include <time.h> using namespace std; int i, j, w = 25, h = 20; int inicio(void); char modo(char c); void game(void); int direcao(void); char tela(char mat['h']['w'], int s); char movimento(char mat['h']['w']); int caudaX[50]{1}, caudaY[50]{1}; int Cauda(int cx, int cy); int main(int argc, char** argv) { inicio(); return 0; } int inicio(void){ system("mode con:cols=25 lines=25"); char select='1', menu1=62, menu2='\0', menu='\0'; while(1){ system("cls"); cout<<"Snake game."<<endl; cout<<menu1<<" Start game"<<endl; cout<<menu2<<" Exit"<<endl; menu=getch(); if(menu==72){ menu1=62; menu2='\0'; select='1'; } if(menu==80){ menu1='\0'; menu2=62; select='0'; } if(menu==13){modo(select);} } } char modo(char c){ switch(c){ case '0': exit(0); break; case '1': game(); break; } } void game(void){ char matriz['h']['w']{'\0'}; system("cls"); for(i=0; i<h; i++){ for(j=0; j<w; j++){ if(i==0||i==h-1){ matriz[i][j]='#'; } if(j==0||j==w-1){ matriz[i][j]='#'; } } } movimento(matriz); } int direcao(void){ int c; if(kbhit()==1){ c=getch(); switch(c){ //Seta pra cima case 72: c=1; break; //Seta pra direita case 77: c=2; break; //Seta pra baixo case 80: c=3; break; //Seta pra esquerda case 75: c=4; break; //ESC pra voltar ao inicio case 27: inicio(); break; } } return c; } char tela(char mat['h']['w'], int s){ system("cls"); for(i=0; i<h; i++){ for(j=0; j<w; j++){ printf("%c",mat[i][j]); } printf("\n"); } printf("Score = %i\n", s-1); } char movimento(char mat['h']['w']){ int x=2, y=2, t1, t2, dir=2, milisec=100, fx, fy, score=1; srand(time(NULL)); while(1){ do{ fx=1+rand()%(h-2); fy=1+rand()%(w-2); }while(mat[fx][fy]=='o'); mat[fx][fy]='@'; do{ if(mat[x][y]!='o'){ mat[x][y]=254; }else{ printf("Game over!"); system("pause>null"); inicio(); } Sleep(milisec); tela(mat, score); mat[caudaX[score]][caudaY[score]]='\0'; caudaX[0]=x; caudaY[0]=y; if(direcao()!=0){ if(direcao()==dir+1||direcao()==dir-1||direcao()==dir+3||direcao()==dir-3){ dir=direcao(); } } switch(dir){ case 1: x--; break; case 2: y++; break; case 3: x++; break; case 4: y--; break; default: dir=2; break; } mat[caudaX[0]][caudaY[0]]='o'; for(i=score+1;i>0;i--){ caudaX[i]=caudaX[i-1]; caudaY[i]=caudaY[i-1]; } if(y==w-1||y==0||x==h-1||x==0){ cout<<"Game over\n"; system("pause>null"); inicio(); } }while(mat[fx][fy]=='@'); score++; Beep(150,200); if(score>5&&score<10){ milisec=80; } if(score==10){ milisec=50; } } }
#include "CIL/transform/resize.h" #include <cfloat> #include <cmath> #include <cstring> #include "CIL/mat/mat.h" #include "CIL/auto_buffer.h" #include "CIL/fast_math.h" #include "CIL/hardware.h" #include "CIL/parallel.h" #include "CIL/saturate_cast.h" #include "CIL/util.h" namespace cil { #include "CIL/transform/resize/interp.lut.h" #include "CIL/transform/resize/common.h" #include "CIL/transform/resize/nearest.h" #include "CIL/transform/resize/linear.h" #include "CIL/transform/resize/cubic.h" #include "CIL/transform/resize/lanczos.h" #include "CIL/transform/resize/area.h" #include "CIL/transform/resize/invoker.h" }
#include "planner.h" #include "nav_msgs/OccupancyGrid.h" Planner::Planner(){ sub_costmap = n.subscribe("/costmap_node/costmap/costmap", 1, &Sensing::costmapCb, &sensor); } void Planner::Astar(){ } void Planner::move(){ // ROS_INFO("Robot moving . . ."); }
#ifndef WINDOWSINPUTLISTENER_H #define WINDOWSINPUTLISTENER_H #include "../Input/InputListener.h" class CWindow; class CWindowsInputListener : public CInputListener { public: CWindowsInputListener( CInput* pInput, CWindow& rWindow ); virtual ~CWindowsInputListener(); virtual void Push( CMessage& rMessage ); private: CWindowsInputListener(); CWindowsInputListener& operator=( const CWindowsInputListener& ); static const u32 ms_kuLeftMouseDownMessageUID = 33928; CWindow& m_rWindow; }; #endif
#include "ComponentHandler.h" ComponentHandler::ComponentHandler() { } ComponentHandler::~ComponentHandler() { } int ComponentHandler::Initialize(GraphicsHandler * graphicsHandler, PhysicsHandler* physicsHandler, AIHandler* aiHandler, AnimationHandler* aHandler) { int result = 1; this->m_graphicsHandler = graphicsHandler; this->m_physicsHandler = physicsHandler; this->m_aiHandler = aiHandler; this->m_aHandler = aHandler; if (graphicsHandler == nullptr || physicsHandler == nullptr || aiHandler == nullptr || aHandler == nullptr) result = 0; return result; } GraphicsComponent * ComponentHandler::GetStaticGraphicsComponent() { GraphicsComponent* graphicsComponent = nullptr; if (this->m_graphicsHandler != nullptr) { graphicsComponent = this->m_graphicsHandler->GetNextAvailableStaticComponent(); } return graphicsComponent; } GraphicsComponent * ComponentHandler::GetDynamicGraphicsComponent() { GraphicsComponent* graphicsComponent = nullptr; if (this->m_graphicsHandler != nullptr) { graphicsComponent = this->m_graphicsHandler->GetNextAvailableDynamicComponent(); } return graphicsComponent; } GraphicsComponent * ComponentHandler::GetPersistentGraphicsComponent() { GraphicsComponent* graphicsComponent = nullptr; if (this->m_graphicsHandler != nullptr) { graphicsComponent = this->m_graphicsHandler->GetNextAvailablePersistentComponent(); } return graphicsComponent; } //GraphicsComponent * ComponentHandler::GetGraphicsComponent() //{ // GraphicsComponent* graphicsComponent = nullptr; // if (this->m_graphicsHandler != nullptr) // { // graphicsComponent = this->m_graphicsHandler->GetNextAvailableComponent(); // } // return graphicsComponent; //} GraphicsAnimationComponent * ComponentHandler::GetGraphicsAnimationComponent() { GraphicsAnimationComponent * graphicsAnimComponent = nullptr; if (this->m_graphicsHandler != nullptr) { graphicsAnimComponent = this->m_graphicsHandler->GetNextAvailableAnimationComponent(); } return graphicsAnimComponent; } PhysicsComponent * ComponentHandler::GetPhysicsComponent() { PhysicsComponent* newComponent = nullptr; DirectX::XMVECTOR tempPos = DirectX::XMVectorSet(0, 8, 60, 0); newComponent = this->m_physicsHandler->CreatePhysicsComponent(tempPos, false); return newComponent; } UIComponent* ComponentHandler::GetUIComponent() { UIComponent* uiComponent = nullptr; if (this->m_graphicsHandler != nullptr) { uiComponent = this->m_graphicsHandler->GetNextAvailableUIComponent(); } return uiComponent; } TextComponent * ComponentHandler::GetTextComponent() { TextComponent* textComponent = nullptr; if (this->m_graphicsHandler != nullptr) { textComponent = this->m_graphicsHandler->GetNextAvailableTextComponent(); } return textComponent; } AIComponent * ComponentHandler::GetAIComponent() { AIComponent* newComp = nullptr; if (this->m_aiHandler != nullptr) { newComp = this->m_aiHandler->GetNextAvailableComponents(); newComp->AC_active = 1; } return newComp; } AnimationComponent * ComponentHandler::GetAnimationComponent() { AnimationComponent* animComp = nullptr; if (this->m_aHandler != nullptr) { animComp = this->m_aHandler->GetNextAvailableComponent(); } return animComp; } void ComponentHandler::UpdateGraphicsComponents() { this->m_graphicsHandler->UpdateComponentList(); } void ComponentHandler::UpdateGraphicsAnimationComponents() { this->m_graphicsHandler->UpdateAnimComponentList(); } void ComponentHandler::UpdateAIComponents() { this->m_aiHandler->UpdateAIComponentList(); } void ComponentHandler::UpdateSoundHandler() { } void ComponentHandler::SetGraphicsComponentListSize(int gCompSize) { this->m_graphicsHandler->SetComponentArraySize(gCompSize); return; } void ComponentHandler::SetGraphicsAnimationComponentListSize(int gCompSize) { this->m_graphicsHandler->SetAnimComponentArraySize(gCompSize); return; } int ComponentHandler::ResizeGraphicsStatic(size_t newCap) { int size = 0; size = this->m_graphicsHandler->ResizeStaticComponents(newCap); return size; } int ComponentHandler::ResizeGraphicsDynamic(size_t newCap) { int size = 0; size = this->m_graphicsHandler->ResizeDynamicComponents(newCap); return size; } int ComponentHandler::ResizeGraphicsPersistent(size_t newCap) { int size = 0; size = this->m_graphicsHandler->ResizePersistentComponents(newCap); return size; } int ComponentHandler::ClearAminationComponents() { this->m_aHandler->ClearAnimationComponents(); this->m_graphicsHandler->ResetAnimationComponents(); return 0; } int ComponentHandler::ClearAIComponents() { this->m_aiHandler->ClearAIComponents(); return 0; } int ComponentHandler::RemoveUIComponentFromPtr(UIComponent * ptr) { return this->m_graphicsHandler->RemoveUIComponentFromPtr(ptr); } int ComponentHandler::RemoveLastUIComponent() { return this->m_graphicsHandler->RemoveLastUIComponent(); } int ComponentHandler::RemoveLastTextComponent() { return this->m_graphicsHandler->RemoveLastTextComponent(); } void ComponentHandler::WaypointTime() { m_aiHandler->WaypointTime(); } PhysicsHandler * ComponentHandler::GetPhysicsHandler() const { return this->m_physicsHandler; } GraphicsHandler * ComponentHandler::GetGraphicsHandler() const { return this->m_graphicsHandler; }
#include "ThirdGift.h" #include "Controller.h" ThirdGift::ThirdGift(sf::Vector2f location, sf::Vector2f size, sf::Vector2f scale, sf::Color color) :Gift(location, size, scale, color) {} ThirdGift::~ThirdGift() {} void ThirdGift::getGift() { auto& control = Controller::getInstance(); control.setPoints(10); }
#include "expressions/expression.hpp" namespace flow { Expression::Expression(Operator op) : m_op(op) { } Operator Expression::getOperator() const { return m_op; } }
#pragma once #include "Piece.h" class King : public Piece { public: King(); King(bool); bool move(char, char); ~King(); };
#include<iostream> #include<set> using namespace std; // 统计set容器的大小以及交换set容器 // empty() //判空 // size() //大小 // swap() //交换 //遍历set void printSet(set<int> &s) { for(set<int>::iterator it=s.begin();it!=s.end();it++) { cout<<*it<<" "; } cout<<endl; } void test01() { // 默认构造 set<int> s1; //插入方式只有insert() s1.insert(1); s1.insert(3); s1.insert(4); s1.insert(2); //所有元素插入时会被自动升序排序 printSet(s1);//1 2 3 4 //判空 if (s1.empty()) { cout<<"s1为空"<<endl; } else { cout<<"s1不为空"<<endl; cout<<"set的大小为:"<<s1.size()<<endl; } set<int> s2; //插入方式只有insert() s2.insert(10); s2 .insert(30); s2 .insert(40); s2 .insert(20); cout<<"交换前"<<endl; printSet(s1); printSet(s2); //swap交换 cout<<"交换后"<<endl; s1.swap(s2); printSet(s1); printSet(s2); } int main() { test01(); return 0; }
#include "stdafx.h" #include "GoCommand.h" #include "Player.h" GoCommand::GoCommand() { directions["north"] = Room::Direction::North; directions["east"] = Room::Direction::East; directions["south"] = Room::Direction::South; directions["west"] = Room::Direction::West; } GoCommand::~GoCommand() { } void GoCommand::Run(list<string>* parameters, Game* game) { Room::Direction d; map<string, Room::Direction>::iterator it = directions.find(*parameters->begin()); if (it != directions.end()) { if (game->getPlayer()->getCurrentRoom()->isTrapped()) { game->getPlayer()->setCurrentHealth(game->getPlayer()->getCurrentHealth() - 20); game->getPlayer()->getCurrentRoom()->setTrapped(false); std::cout << "There was a trap in this room that you didn't disarm. You triggered it and lose 20hp" << std::endl; if (game->getPlayer()->getCurrentHealth() < 0) { std::cout << "Your died... GAME OVER!" << endl; game->finish(); cin.get(); } } d = it->second; game->getPlayer()->MoveDirection(d); } else { cout << "Second part of command is unknown." << endl; } }
#include <iostream> #include <Windows.h> wchar_t *LPCtransferfromstring(const char * title) { size_t size = mbsrtowcs(NULL, &title, 0, NULL); wchar_t * buf = new wchar_t[size + 1](); size = mbsrtowcs(buf, &title, size + 1, NULL); return buf; } std::wstring convert(const std::string& as) { // deal with trivial case of empty string if (as.empty()) return std::wstring(); // determine required length of new string size_t reqLength = ::MultiByteToWideChar(CP_UTF8, 0, as.c_str(), (int)as.length(), 0, 0); // construct new string of required length std::wstring ret(reqLength, L'\0'); // convert old string to new string ::MultiByteToWideChar(CP_UTF8, 0, as.c_str(), (int)as.length(), &ret[0], (int)ret.length()); // return new string ( compiler should optimize this away ) return ret; }
/* path.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 26 Apr 2014 FreeBSD-style copyright and disclaimer apply Path implementation. */ #include "includes.h" #include "types/std/string.h" #include "types/std/vector.h" #include <algorithm> namespace reflect { namespace config { /******************************************************************************/ /* PATH */ /******************************************************************************/ void Path:: parse(const std::string& path, char sep) { size_t i = 0; while (i < path.size()) { size_t j = path.find(sep, i); if (j == std::string::npos) j = path.size(); if (i == j) reflectError("empty path component <%s>", path); items.push_back(path.substr(i, j - i)); i = j + 1; } } std::string Path:: toString(char sep) const { std::string path; for (size_t i = 0; i < items.size(); ++i) { if (i) path += sep; path += items[i]; } return path; } Path:: Path(const std::string& path, char sep) { parse(path, sep); } Path:: Path(const char* path, char sep) { parse(path, sep); } Path:: Path(const Path& prefix, const std::string& path, char sep) : items(prefix.items) { parse(path, sep); } Path:: Path(const Path& prefix, size_t index) : items(prefix.items) { items.emplace_back(std::to_string(index)); } bool Path:: isIndex(size_t index) const { const auto& item = items[index]; for (char c : item) { if (!std::isdigit(c)) return false; } return true; } size_t Path:: index(size_t index) const { const auto& item = items[index]; for (char c : item) { if (!std::isdigit(c)) reflectError("component at <%s> is not an index <%s>", index, item); } return std::stoull(item); } Path Path:: popFront() const { if (items.empty()) reflectError("pop on an empty path"); Path result; result.items.insert(result.items.begin(), items.begin() + 1, items.end()); return std::move(result); } Path Path:: popBack() const { if (items.empty()) reflectError("pop on an empty path"); Path result; result.items.insert(result.items.begin(), items.begin(), items.end() - 1); return std::move(result); } bool Path:: operator<(const Path& other) const { for (size_t i = 0; i < std::min(size(), other.size()); ++i) { int res = items[i].compare(other[i]); if (!res) continue; return res < 0; } return size() < other.size(); } /******************************************************************************/ /* UTILS */ /******************************************************************************/ // We use recursive pathing to ensure that rvalue returns remain valid during // the duration of the access. bool has(Value value, const Path& path, size_t index) { if (index == path.size()) return true; if (value.type()->isPointer()) return has(*value, path, index); if (value.is("list")) { if (!path.isIndex(index)) return false; if (path.index(index) >= value.call<size_t>("size")) return false; return has(value[path.index(index)], path, index + 1); } if (value.is("map")) { if (value.type()->call<const Type*>("keyType") != type<std::string>()) return false; if (!value.call<size_t>("count", path[index])) return false; return has(value[path[index]], path, index + 1); } if (!value.type()->hasField(path[index])) return false; return has(value.get<Value>(path[index]), path, index + 1); } Value get(Value value, const Path& path, size_t index) { if (index == path.size()) return value; if (value.type()->isPointer()) return get(*value, path, index); if (value.is("list")) { if (!value.isConst()) value.call<void>("resize", path.index(index) + 1); return get(value[path.index(index)], path, index + 1); } if (value.is("map")) return get(value[path[index]], path, index + 1); return get(value.get<Value>(path[index]), path, index + 1); } } // namespace config } // namespace reflect
#include <bits/stdc++.h> using namespace std; const int N = 1005; char mat[1010][1010], aux[1010][1010]; map < pair < char, char >, char > change; void rotate(char c, const int &n){ if(c == 'R'){ int a = 0; for (int j=0; j<n; j++){ int b =0; for (int i=n-1; i>=0; i--){ aux[a][b] = change[{c,mat[i][j]}]; b++; } a++; } } else { int a = 0; for (int j=n-1; j>=0; j--){ int b = 0; for (int i=0; i<n; i++){ aux[a][b] = change[{c, mat[i][j]}]; b++; } a++; } } for (int i=0; i<n; i++){ for (int j=0; j<n; j++) mat[i][j] = aux[i][j]; } } int main(){ int n; char str[110]; scanf("%d %s", &n, &str); change[{'L','>'}] = '^'; change[{'L','<'}] = 'v'; change[{'L','^'}] = '<'; change[{'L','v'}] = '>'; change[{'R','>'}] = 'v'; change[{'R','<'}] = '^'; change[{'R','^'}] = '>'; change[{'R','v'}] = '<'; change[{'L','.'}] = '.'; change[{'R','.'}] = '.'; int L = 0, R = 0; for (int i=0; i<strlen(str); i++){ char c = str[i]; if(c == 'L') L++; else R++; } L %= 4; R %= 4; for (int i=0; i<n; i++) scanf("%s", mat[i]); for (int i=0; i<L; i++) rotate('L', n); for (int i=0; i<R; i++) rotate('R', n); for (int i=0; i<n; i++){ for (int j=0; j<n; j++){ printf("%c", mat[i][j]); } puts(""); } }
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "paintlayerstack.h" #include <QDebug> class PaintLayerStackPrivate { public: PaintLayerStack* q; QList<PaintLayer*> m_layers; }; PaintLayerStack::PaintLayerStack(QObject* parent) : PaintLayer(parent) { d = new PaintLayerStackPrivate; d->q = this; } PaintLayerStack::~PaintLayerStack() { delete d; } void PaintLayerStack::addLayer(PaintLayer* layer) { d->m_layers << layer; /// Witold, is this the right thing to do? layer->setParent(this); layer->setWindowSize(this->windowSize()); QObject::connect(layer, SIGNAL(repaintNeeded()), this, SIGNAL(repaintNeeded())); } void PaintLayerStack::paint(QPainter* painter) { for (int i = 0; i < d->m_layers.count(); i++) { bool hold_export_mode = d->m_layers[i]->exportMode(); d->m_layers[i]->setExportMode(this->exportMode()); d->m_layers[i]->paint(painter); d->m_layers[i]->setExportMode(hold_export_mode); } } void PaintLayerStack::mousePressEvent(QMouseEvent* evt) { evt->setAccepted(false); for (int i = d->m_layers.count() - 1; i >= 0; i--) { if (evt->isAccepted()) break; d->m_layers[i]->mousePressEvent(evt); } } void PaintLayerStack::mouseReleaseEvent(QMouseEvent* evt) { evt->setAccepted(false); for (int i = d->m_layers.count() - 1; i >= 0; i--) { if (evt->isAccepted()) break; d->m_layers[i]->mouseReleaseEvent(evt); } } void PaintLayerStack::mouseMoveEvent(QMouseEvent* evt) { evt->setAccepted(false); for (int i = d->m_layers.count() - 1; i >= 0; i--) { if (evt->isAccepted()) break; d->m_layers[i]->mouseMoveEvent(evt); } } void PaintLayerStack::setWindowSize(QSize size) { for (int i = 0; i < d->m_layers.count(); i++) { d->m_layers[i]->setWindowSize(size); } PaintLayer::setWindowSize(size); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QTextStream> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); n_input=46; //constant하나 추가 n_hidden=50; m_netH = new double[n_hidden]; m_netO = new double[45]; delta_k = new double[45]; delta_j = new double[n_hidden]; n_training = 50; nvOutput_Target=new double[45]; learning_rate = 0.1; } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { // QString fileName; // fileName = QFileDialog::getOpenFileName(this,tr("Open History"),"/Users/kirumang/QT_SRC/Lotto/", tr("Text Files (*.txt)")); QFile file("/Users/kirumang/QT_SRC/Lotto/LottoHistory_0216.txt"); QString errorMsg; //ui->DisplayText->setText(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { errorMsg = "Error"; ui->DisplayText->setText(errorMsg); return; } int index =0; QTextStream in(&file); QString line = in.readLine(); QStringList linelist; QString test; historylist = new int*[600]; while (!line.isNull()) { linelist = line.split(QRegExp("\\s+")); historylist[index] = new int[7]; historylist[index][0] = linelist.at(0).toInt(); historylist[index][1] = linelist.at(1).toInt(); historylist[index][2] = linelist.at(2).toInt(); historylist[index][3] = linelist.at(3).toInt(); historylist[index][4] = linelist.at(4).toInt(); historylist[index][5] = linelist.at(5).toInt(); historylist[index][6] = linelist.at(6).toInt(); // test = QString("Number : %1 %2 %3 %4 %5 %6 %7 [%8]").arg(historylist[index][0]).arg(historylist[index][1]).arg(historylist[index][2]).arg(historylist[index][3]).arg(historylist[index][4]).arg(historylist[index][5]).arg(historylist[index][6]).arg(index); index++; // debug(test); line = in.readLine(); } n_history = index-1; nvInputProbability = new double *[index];//index == number of history, n_history = end of array int i; int j; int k; bool choice; double delta_probability = 0.01; double maxprob; double totalprob; double normalize; nvInputProbability[n_history] = new double[45]; test = ""; maxprob=-1.0; totalprob=0.0; for(i=0;i<45;i++) { nvInputProbability[n_history][i]=1.0; choice = false; for(j=0;j<7;j++) { if(historylist[n_history][j] == i+1) { choice=true; nvInputProbability[n_history][i] += delta_probability; } } if(maxprob < nvInputProbability[n_history][i]) { maxprob = nvInputProbability[n_history][i]; } // totalprob=totalprob+nvInputProbability[n_history][i]; /*if(!choice){ nvInputProbability[n_history][i] -= delta_probability/(45.0-7.0); }*/ } //normalize //test=QString("Totalprob:%1").arg(totalprob); for(i=0;i<45;i++) { normalize = nvInputProbability[n_history][i]; nvInputProbability[n_history][i]=normalize/maxprob; test = test+ QString("%1[%2] ").arg(i+1).arg(nvInputProbability[n_history][i]); } debug(test); for(i=n_history-1;i>=0;i--) { nvInputProbability[i] = new double[45]; maxprob=-1.0; totalprob=0.0; for(k=0;k<45;k++) { choice = false; for(j=0;j<7;j++) { if(historylist[i][j] == k+1) //n_history -> 1 까지만 러닝, 0:마지막 { choice=true; nvInputProbability[i][k] = nvInputProbability[i+1][k] + delta_probability; } } if(maxprob < nvInputProbability[i][k]) { maxprob = nvInputProbability[i][k]; } //totalprob=totalprob+nvInputProbability[i][k]; }//normalize for(k=0;k<45;k++) { nvInputProbability[i][k]= nvInputProbability[i][k]/maxprob; } } for(i=0;i<=n_history;i++) { test=QString("%1 : ").arg(i); test = test+ QString("%1[%2] ").arg(1).arg(nvInputProbability[i][0]); debug(test); } } void MainWindow::Addaweek(QString aline) { } void MainWindow::debug(QString text) { ui->textBrowser_debug->append(text); } void MainWindow::on_pushButton_2_clicked() { //MLP생성 nvInput = new double[n_input]; // nvHidden = new double[n_hidden]; nvOutput = new double[45]; srand(time(NULL)*(1)); weight_w = new double *[n_input]; QString test; QString temp; for(int i=0;i<n_input;i++) { weight_w[i]= new double[n_hidden]; for(int j=0;j<n_hidden;j++) weight_w[i][j] = ((double)rand()/RAND_MAX-0.5)*0.5; } weight_v = new double *[n_hidden]; for(int i=0;i<n_hidden;i++) { weight_v[i] = new double[45]; for(int j=0;j<45;j++) weight_v[i][j] = ((double)rand()/RAND_MAX-0.5)*0.5; } } void MainWindow::on_pushButton_3_clicked() { //Learning //Target Input & Ouput Selection QString test; for(int k=0;k<n_training;k++) { for(int i=n_history;i>0;i--) { learning_rate=0.01; setTarget(i,i-1); forward(); backward(); } } long long error_rate = compute_error(); QString moneytext; moneytext= QString("Amount Money : %1").arg(error_rate); debug(moneytext); } long long MainWindow::compute_error() { //전체 학습 데이터에 대한 forward결과 매칭율 (전회 -> 다음회비교) //3개 : 5000 won //4개 : 50000 won //5개 : 1000000 won //6개 : 1000000000 won int rank[45]; int n_match; int ind; int money; ind=0; money=0; for(int i=n_history;i>0;i--) { setTarget(i,i-1); forward(); //Ranking 탐색 : 나보다 큰놈 있음 인덱스 +1 // 0,1,2,3,4,5 가 랭커 for(int j=0;j<45;j++) { rank[j]=0; for(int k=0;k<45;k++) { if(j!=k) { if(nvOutput[j] < nvOutput[k]) rank[j]=rank[j]+1; } } } n_match=0; for(int j=0;j<45;j++) { if(rank[j]==0 || rank[j]==1 || rank[j]==2 || rank[j]==3 || rank[j]==4 || rank[j]==5) { //해당 숫자가 target 있는지 판별 // test= QString("rank %1 : %2").arg(rank[j]).arg(j+1); //debug(test); ind = j+1; for(int k=0;k<6;k++) { if(historylist[i-1][k] == ind) n_match++; } } } money=money+calmoney(n_match,i-1); } return money; } long long MainWindow::calmoney(int n_match, int index) { QString test; if(n_match==3) { test = QString("ForthAward %1").arg(index); debug(test); return 5; }else if(n_match==4) { test = QString("ThirdAward %1").arg(index); debug(test); return 50; }else if(n_match==5) { test = QString("SecondAward %1").arg(index); debug(test); return 1000; }else if(n_match==6) { test = QString("FirstAward %1").arg(index); debug(test); return 1000000; }else { return 0; } } void MainWindow::setTarget(int n_inputhistory, int n_outputhistory) { nvInput[0]=1.0; //Constant value = 1 nvInput[45]=0.0; for(int i=0; i<45;i++) { nvInput[i+1]=nvInputProbability[n_inputhistory][i]; nvOutput_Target[i]=0.0; } //Here_Probability should be imported /* for(int i=0; i<7;i++) { nvInput[historylist[n_inputhistory][i]] = 1.0; }*/ for(int i=0; i<6;i++) nvOutput_Target[historylist[n_outputhistory][i]-1] = 1.0; } void MainWindow::backward() { weight_change=0.0; for(int i=0;i<45;i++) { delta_k[i]=-sigmoidInv(m_netO[i])*(nvOutput_Target[i]-nvOutput[i]); } for(int i=0;i<n_hidden;i++) { double sum=0.0; for(int j=0;j<45;j++) { sum+= weight_v[i][j]*delta_k[j]; } delta_j[i]=sigmoidInv(m_netH[i])*sum; } for(int i=0;i<n_input;i++) { for(int j=0;j<n_hidden;j++) { weight_w[i][j]=weight_w[i][j]-learning_rate*delta_j[j]*nvInput[i]; weight_change+=learning_rate*delta_j[j]*nvInput[i]; } } for(int i=0;i<n_hidden;i++) { for(int j=0;j<45;j++) { weight_v[i][j]=weight_v[i][j]-learning_rate*delta_k[j]*m_netH[i]; } } } void MainWindow::forward() { //1. Forward for(int i=0;i<n_hidden;i++){ double sum = 0.0; for(int j=0;j<n_input;j++){ sum += nvInput[j] * weight_w[j][i]; } m_netH[i]=sum; nvHidden[i]=sigmoid(sum); } for(int i=0;i<45;i++){ double sum = 0.0; for(int j=0;j<n_hidden;j++){ sum += nvHidden[j] * weight_v[j][i]; } m_netO[i]=sum; nvOutput[i] = sigmoid(sum); } } void MainWindow::on_pushButton_4_clicked() { //Prediction by Input (Recent selected Number) nvInput[0]=1.0; //Constant value = 1 // nvInput[45]=0.0; for(int i=0; i<45;i++) { nvInput[i+1]=0.0; } //번호 입력 /* int number; number = ui->spinBox->value();nvInput[number] = 1.0; number = ui->spinBox_2->value();nvInput[number] = 1.0; number = ui->spinBox_3->value();nvInput[number] = 1.0; number = ui->spinBox_4->value();nvInput[number] = 1.0; number = ui->spinBox_5->value();nvInput[number] = 1.0; number = ui->spinBox_6->value();nvInput[number] = 1.0; */ setTarget(0,0); forward(); QString text=""; QString temp; int rank[45]; for(int j=0;j<45;j++) { rank[j]=0; for(int k=0;k<45;k++) { if(j!=k) { if(nvOutput[j] < nvOutput[k]) rank[j]=rank[j]+1; } } } for(int i=0;i<45;i++) { if(rank[i]==0 || rank[i]==1 || rank[i]==2 || rank[i]==3 || rank[i]==4 || rank[i]==5) {temp=QString("%1[%2] \n").arg(i+1).arg(rank[i]).arg(nvOutput[i]); text.append(temp);} } ui->textBrowser->append(text); } void MainWindow::on_pushButton_6_clicked() { n_hidden = 50; n_training = 50000; on_pushButton_2_clicked(); on_pushButton_3_clicked(); //learining on_pushButton_4_clicked(); //prediction n_hidden = 100; n_training = 60000; on_pushButton_2_clicked(); on_pushButton_3_clicked(); //learining on_pushButton_4_clicked(); //prediction n_hidden = 150; n_training = 70000; on_pushButton_2_clicked(); on_pushButton_3_clicked(); //learining on_pushButton_4_clicked(); //prediction n_hidden = 200; n_training = 80000; on_pushButton_2_clicked(); on_pushButton_3_clicked(); //learining on_pushButton_4_clicked(); //prediction n_hidden = 250; n_training = 90000; on_pushButton_2_clicked(); on_pushButton_3_clicked(); //learining on_pushButton_4_clicked(); //prediction }
//CloseForm.cpp #include "CloseForm.h" CloseForm::CloseForm(Form *form) :FindingFormAction(form) { } CloseForm::CloseForm(const CloseForm& source) : FindingFormAction(source) { } CloseForm::~CloseForm() { } CloseForm& CloseForm::operator=(const CloseForm& source) { FindingFormAction::operator=(source); return *this; } #include "FindingForm.h" #include "OtherNoteForm.h" #include "PageForm.h" #include "MemoForm.h" #include "Note.h" #include "Page.h" #include "Memo.h" #include "Line.h" #include "SelectedBuffer.h" void CloseForm::OnFindingFormButtonClicked(WPARAM wParam, LPARAM lParam) { OtherNoteForm *otherNoteForm = static_cast<OtherNoteForm*>(this->form); FindingForm *findingForm = otherNoteForm->GetFindingForm(); if (findingForm->GetLength() > 0) { //강조하기 해제 전에 현재 찾은 문자의 memoForm에 fucous를 주기 위해서 FindIndex findIndex = findingForm->GetIndexes().GetAt(findingForm->GetCurrent()); PageForm *pageForm = otherNoteForm->GetPageForm(findIndex.GetPageIndex()); MemoForm *memoForm = findIndex.GetMemoIndex(); memoForm->SetFocus(); //0924 : 캐럿에 앞서서 선택하기 추가하기 Memo *memo = static_cast<Memo*>(memoForm->GetContents()); Line *line = memo->GetLine(memo->GetRow()); if (memoForm->GetSelectedBuffer()->GetIsSelecting() == false) { memoForm->GetSelectedBuffer()->SetInitialPosition(memo->GetRow(), line->GetColumn() - findingForm->GetKeyLength()); } memoForm->GetSelectedBuffer()->CopyToBuffer(memo->GetRow(), line->GetColumn()); memoForm->GetSelectedBuffer()->SetIsSelecting(true); memoForm->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ERASE); findingForm->EraseFindIndexes(); if (findingForm->GetLength() > 0) { otherNoteForm->GetPageForm(static_cast<Note*>(otherNoteForm->GetContents())->GetCurrent())->OnEraseFindIndexes(); } otherNoteForm->GetPageForm(static_cast<Note*>(otherNoteForm->GetContents())->GetCurrent())->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ERASE); otherNoteForm->GetTabCtrl()->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ERASE); } else { PageForm *pageForm = otherNoteForm->GetPageForm(static_cast<Note*>(otherNoteForm->GetContents())->GetCurrent()); Page *page = static_cast<Page*>(pageForm->GetContents()); if (page->GetCurrent() >= 0 && page->GetLength() > 0) {//메모가 없을 경우 찾으려고 할 떄 MemoForm *memoForm = pageForm->GetMemoForm(static_cast<Page*>(pageForm->GetContents())->GetCurrent()); memoForm->SetFocus(); } } //findingForm에 대한 해제가 필요하다 11/12 if (findingForm != 0) { findingForm->CloseWindow(); otherNoteForm->SetFindingForm(NULL); } }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int R,C,r,c; bool find2D(vector<string> s, vector<string> p){ bool found = false; for(int i=0;i<R-r+1;i++){ for(int j=0;j<C-c+1;j++){ found = true; for(int i1=0;i1<r && found;i1++){ // no need to keep looking further after one mismatch for(int j1=0;j1<c && found;j1++){ //same as above comment, will just waste time if(s[i+i1][j+j1]!=p[i1][j1]){ found = false; } } } if(found){ return true; } } } return false; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t; string temp; cin >> t; while(t-->0){ cin >> R >> C; //** No need to make G vector<vector<int>> vector<string> G; for(int i=0;i<R;i++){ cin >> temp; G.push_back(temp); } cin >> r >> c; vector<string> g; for(int i=0;i<r;i++){ cin >> temp; g.push_back(temp); } if(find2D(G,g)){ cout << "YES" << endl; }else{ cout << "NO" << endl; } } return 0; }
#include <string> #include <mysql++.h> #include <fstream> #include <sys/types.h> #include <unistd.h> #include "tiempo.h" #include "dominio.h" #include "util.h" #include "servicio.h" #include "servicioMultidominio.h" #include "configuracion.h" using namespace std; using namespace mysqlpp; cServicioMultidominio::cServicioMultidominio(cDominio *dom):cServicio(dom) { servicioDB = "MULTIDOMINIO"; } bool cServicioMultidominio::iniciar() { bool resultado = true; cServicio::iniciar(); traerLimite(); traerCantidad(); if ((limite.length() <= 0) || (cantidad.length() <= 0)) resultado = false; return(resultado); } int cServicioMultidominio::agregarFileHttpdConf(const std::string &multi, cDominio &dominio) { //Abrir el archivo para escritura ofstream out("/usr/local/apache/conf/extra/httpd-vhosts.conf", ios::app); if (!out.is_open()) { dominio.loguear("No se pudo abrir el archivo /usr/local/apache/conf/extra/httpd-vhosts.conf"); return(-1); } //Agregar las lineas out << endl << "#################### Multiple Domain: www." << multi << " ####################" << endl << "<VirtualHost " << SERVER_IP << ":80>" << endl << "ServerAdmin info@" << dominio.getDominio() << endl << "DocumentRoot /www/docs/" << dominio.getDominio() << "/public_html" << endl << "ServerName www." << multi << endl << "ServerAlias *." << multi << endl << "RewriteEngine on" << endl << "RewriteRule ^/phcm(.*) http://panel2.powered-hosting.com:81/phcm/" << dominio.getDominio() << " [R,L]" << endl << "RewriteRule ^/webmail(.*) http://panel2.powered-hosting.com:81/phcm/" << dominio.getDominio() << "/webmail [R,L]" << endl << "RewriteRule ^/soporte(.*) http://panel2.powered-hosting.com:81/phcm/" << dominio.getDominio() << "/SoportePD.php [R,L]" << endl << "ErrorLog /www/docs/" << dominio.getDominio() << "/error-log.txt" << endl << "CustomLog /www/docs/" << dominio.getDominio() << "/access-log.txt combined" << endl << "Options ExecCGI Includes Indexes" << endl << "php_admin_value safe_mode 1" << endl << "php_admin_value safe_mode_exec_dir /www/docs/" << dominio.getDominio() << "/" << endl << "</VirtualHost>" << endl << "#####################################################################################" << endl; //Cerrar el archivo out.close(); return(0); } int cServicioMultidominio::agregarFileNamed(const std::string &multi, cDominio &dominio) { std::string archivo; Tiempo tiempo; //Abrir el archivo para escritura archivo = "/var/named/named." + multi; ofstream out(archivo.c_str(), ios::app); if (!out.is_open()) { dominio.loguear(string("No se pudo abrir el archivo " + archivo)); return(-1); } //Agregar al archivo la configuracion out << "$TTL 1H" << endl << ";" << endl << ";zone file for " << multi << endl << ";" << endl << "@\tIN\tSOA\t" << multi << ". root." << multi << ". (" << endl << "\t\t\t" << tiempo.getAnio() << tiempo.getMes() << tiempo.getDia() << "00" << endl << "\t\t\t8H" << endl << "\t\t\t2H" << endl << "\t\t\t1W" << endl << "\t\t\t1D )" << endl << "\t\tNS\tns" << endl << "\t\tTXT\t\"Powered Hosting\"" << endl << "\t\tTXT\t\"v=spf1 ip4:" << SERVER_IP << " ip4:" << SERVER_IP2 << " mx ptr -all\"" << endl << "\t\tMX\t10\tmail." << multi << "." << endl << "\t\tMX\t20\tmail2." << multi << "." << endl << "@\t\tA\t" << SERVER_IP << endl << "www\t\tA\t" << SERVER_IP << endl << "ftp\t\tA\t" << SERVER_IP << endl << "irc\t\tA\t" << SERVER_IP << endl << "pop3\t\tA\t" << SERVER_IP << endl << "stmp\t\tA\t" << SERVER_IP << endl << "mail\t\tA\t" << SERVER_IP << endl << "mail2\t\tA\t" << SERVER_IP2 << endl << "webmail\t\tA\t" << SERVER_IP << endl << "ns\t\tA\t" << SERVER_IP << endl << "*\t\tA\t" << SERVER_IP << endl; //Cerrar el archivo out.close(); return(0); } int cServicioMultidominio::agregarFileNamedConf(const std::string &redir, cDominio &dominio) { //Abrir el archivo para escritura ofstream out("/etc/named.conf", ios::app); if (!out.is_open()) { dominio.loguear("No se pudo abrir el archivo /etc/named.conf"); return(-1); } //Agregar las lineas out << endl << "zone \"" << redir << "\" {" << endl << "\ttype master;" << endl << "\tnotify no;" << endl << "\tfile \"named." << redir << "\";" << endl << "};" << endl; //Cerrar el archivo out.close(); return(0); } int cServicioMultidominio::agregarMultidominio(const std::string &multidominio, cDominio &dominio) { std::string comando; //Obtener permisos de root if (setuid(0) < 0) { dominio.loguear("Error al obtener permisos de root"); return(-1); } //Crear el archivo named.dominio if (agregarFileNamed(multidominio, dominio) < 0) { comando = "Error al crear el archivo named." + dominio.getDominio(); dominio.loguear(comando); return(-1); } //Modificar el archivo named.conf if (agregarFileNamedConf(multidominio, dominio) < 0) { comando = "Error al modificar el archivo named.conf"; dominio.loguear(comando); return(-1); } //Modificar el archivo httpd-vhosts.conf if (agregarFileHttpdConf(multidominio, dominio) < 0) { comando = "Error al modificar el archivo httpd-vhosts.conf"; dominio.loguear(comando); return(-1); } //Actualizar los DNS actualizarDNS(); return(0); } int cServicioMultidominio::agregarMultidominioDB(const std::string &multidominio, cDominio &dominio) { try { Query qry = dominio.con.query(); qry << "INSERT INTO MULTIDOMINIO(MULTIDOMINIO, ID_DOMINIO) VALUES('" << multidominio << "', '" << dominio.getIdDominio() << "')"; qry.execute(); return(0); } catch(BadQuery er) { dominio.loguear(er.error); return(-1); } catch(...) { string error; error = "Error al agregar el multidominio " + multidominio; dominio.loguear(error); return(-2); } } int cServicioMultidominio::quitarFileHttpdConf(const std::string &multi, cDominio &dominio) { std::string archivo, archivo2, comando; archivo = "/usr/local/apache/conf/extra/httpd-vhosts.conf"; archivo2 = "/usr/local/apache/conf/extra/httpd-vhosts.conf.bak"; //Mover el archivo para actualizarlo comando = "mv -f " + archivo + " " + archivo2; system(comando.c_str()); //Abrir el archivo para lectura ifstream in(archivo2.c_str()); if (!in.is_open()) { comando = "mv -f " + archivo2 + " " + archivo; system(comando.c_str()); comando = "No se pudo abrir el archivo " + archivo; dominio.loguear(comando); return(-1); } //Abrir el archivo para escritura ofstream out(archivo.c_str()); if (!out.is_open()) { comando = "mv -f " + archivo2 + " " + archivo; system(comando.c_str()); comando = "No se pudo abrir el archivo " + archivo; dominio.loguear(comando); return(-1); } //Filtrar el archivo char buffer[MINLINE]; std::string linea; std::string buscada, hasta; buscada = "#################### Multiple Domain: www." + multi + " #"; hasta = "</VirtualHost>"; int estado = 1; while(in.getline(buffer, MINLINE)) { linea = buffer; if (estado == 1) { if (linea.find(buscada) != string::npos) estado = 2; else out << linea << endl; } else if (estado == 2) { if (linea.find(hasta) != string::npos) { in.getline(buffer, MINLINE); in.getline(buffer, MINLINE); estado = 1; } } } //Cerrar los archivos in.close(); out.close(); return(0); } int cServicioMultidominio::quitarFileNamed(const std::string &multi, cDominio &dominio) { std::string archivo, comando; //Eliminar el archivo archivo = "/var/named/named." + multi; if (unlink(archivo.c_str()) < 0) { comando = "Error al eliminar el archivo " + archivo; dominio.loguear(comando); return(-1); } return(0); } int cServicioMultidominio::quitarFileNamedConf(const std::string &multi, cDominio &dominio) { //Mover el archivo para actualizarlo system("mv -f /etc/named.conf /etc/named.conf.bak"); //Abrir el archivo para lectura ifstream in("/etc/named.conf.bak"); if (!in.is_open()) { system("mv -f /etc/named.conf.bak /etc/named.conf"); dominio.loguear("No se pudo abrir el archivo /etc/named.conf"); return(-1); } //Abrir el archivo para escritura ofstream out("/etc/named.conf"); if (!out.is_open()) { system("mv -f /etc/named.conf.bak /etc/named.conf"); dominio.loguear("No se pudo abrir el archivo /etc/named.conf"); return(-1); } //Filtrar el archivo char buffer[MINLINE]; std::string linea; std::string buscada, hasta; buscada = "zone \"" + multi + "\" {"; hasta = "};"; int estado = 1; while(in.getline(buffer, MINLINE)) { linea = buffer; if (estado == 1) { if (linea.find(buscada) != string::npos) estado = 2; else out << linea << endl; } else if (estado == 2) { if (linea.find(hasta) != string::npos) { in.getline(buffer, MINLINE); estado = 1; } } } //Cerrar los archivos in.close(); out.close(); return(0); } int cServicioMultidominio::quitarMultidominio(const std::string &multidominio, cDominio &dominio) { std::string comando; //Obtener permisos de root if (setuid(0) < 0) { dominio.loguear("Error al obtener permisos de root"); return(-1); } //Eliminar el archivo named.dominio if (quitarFileNamed(multidominio, dominio) < 0) { comando = "Error al eliminar el archivo named." + dominio.getDominio(); dominio.loguear(comando); return(-1); } //Modificar el archivo named.conf if (quitarFileNamedConf(multidominio, dominio) < 0) { comando = "Error al modificar el archivo named.conf"; dominio.loguear(comando); return(-1); } //Modificar el archivo httpd-vhosts.conf if (quitarFileHttpdConf(multidominio, dominio) < 0) { comando = "Error al modificar el archivo httpd-vhosts.conf"; dominio.loguear(comando); return(-1); } //Actualizar los DNS actualizarDNS(); return(0); } int cServicioMultidominio::quitarMultidominioDB(const std::string &multidominio, cDominio &dominio) { try { Query qry = dominio.con.query(); qry << "DELETE FROM MULTIDOMINIO WHERE MULTIDOMINIO = '" << multidominio << "' AND ID_DOMINIO = '" << dominio.getIdDominio() << "'"; qry.execute(); return(0); } catch(BadQuery er) { dominio.loguear(er.error); return(-1); } catch(...) { string error; error = "Error al quitar el multidominio " + multidominio; dominio.loguear(error); return(-2); } } std::string cServicioMultidominio::traerCantidad() { try { Query qry = dominio->con.query(); qry << "SELECT COUNT(*) FROM MULTIDOMINIO WHERE ID_DOMINIO = '" << dominio->getIdDominio() << "'"; Result res = qry.store(); Row row; Result::iterator i; if (res.size() > 0) { i = res.begin(); row = *i; cantidad = std::string(row[0]); } return(cantidad); } catch(BadQuery er) { dominio->loguear(er.error); return(cantidad); } catch(...) { string error; error = "Error al recuperar la cantidad del servicio"; dominio->loguear(error); return(cantidad); } } int cServicioMultidominio::verificarExisteMultidominioDB(const std::string &multidominio, cDominio &dominio) { int resultado = 0; try { Query qry = dominio.con.query(); qry << "SELECT COUNT(*) FROM MULTIDOMINIO WHERE MULTIDOMINIO = '" << multidominio << "'"; Result res = qry.store(); Row row; Result::iterator i; if (res.size() > 0) { i = res.begin(); row = *i; resultado = row[0]; } return(resultado); } catch(BadQuery er) { dominio.loguear(er.error); return(resultado); } catch(...) { string error; error = "Error al verificar si existe el multidominio " + multidominio; dominio.loguear(error); return(resultado); } } int cServicioMultidominio::verificarExisteMultidominioDB(const std::string &multidominio, cDominio &dominio, std::string) { int resultado = 0; try { Query qry = dominio.con.query(); qry << "SELECT COUNT(*) FROM MULTIDOMINIO WHERE MULTIDOMINIO = '" << multidominio << "' AND ID_DOMINIO = '" << dominio.getIdDominio() << "'"; Result res = qry.store(); Row row; Result::iterator i; if (res.size() > 0) { i = res.begin(); row = *i; resultado = row[0]; } return(resultado); } catch(BadQuery er) { dominio.loguear(er.error); return(resultado); } catch(...) { string error; error = "Error al verificar si existe el multidominio " + multidominio; dominio.loguear(error); return(resultado); } }
// EraseFindIndexVisitor.h #ifndef _ERASEFINDINDEXVISITOR_H #define _ERASEFINDINDEXVISITOR_H #include "Visitor.h" #include <afxwin.h> class EraseFindIndexVisitor : public Visitor { public: EraseFindIndexVisitor(CDC *dc); EraseFindIndexVisitor(const EraseFindIndexVisitor& source); virtual ~EraseFindIndexVisitor(); EraseFindIndexVisitor& operator=(const EraseFindIndexVisitor& source); virtual void Visit(Note *note); virtual void Visit(Page *page); virtual void Visit(Memo *memo); virtual void Visit(Line *line); virtual void Visit(Character *character); virtual void Visit(SingleCharacter *singleCharacter); virtual void Visit(DoubleCharacter *doubleCharacter); private: CDC *dc; }; #endif // _ERASEFINDINDEXVISITOR_H
/** * 3D NDT-UKF Node. */ #include <ros/ros.h> #include <angles/angles.h> #include <tf/transform_listener.h> #include <boost/foreach.hpp> #include <sensor_msgs/LaserScan.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/approximate_time.h> #include <nav_msgs/Odometry.h> #include <nav_msgs/OccupancyGrid.h> #include <visualization_msgs/MarkerArray.h> #include <tf/transform_broadcaster.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <geometry_msgs/Pose.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/filters/voxel_grid.h> #include <velodyne_pointcloud/rawdata.h> #include <velodyne_pointcloud/point_types.h> #include <pcl_ros/impl/transforms.hpp> #include "tf/message_filter.h" #include <tf/transform_broadcaster.h> #include <tf_conversions/tf_eigen.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <sensor_msgs/PointCloud2.h> #include <ndt_generic/utils.h> #include <ndt_generic/eigen_utils.h> #include <ndt_mcl/3d_ndt_ukf.h> #include <ndt_map/ndt_map.h> #include <ndt_rviz/ndt_rviz.h> #include <ndt_generic/pcl_utils.h> inline void normalizeEulerAngles(Eigen::Vector3d &euler) { if (fabs(euler[0]) > M_PI/2) { euler[0] += M_PI; euler[1] += M_PI; euler[2] += M_PI; euler[0] = angles::normalize_angle(euler[0]); euler[1] = angles::normalize_angle(euler[1]); euler[2] = angles::normalize_angle(euler[2]); } } std::string affine3dToString(const Eigen::Affine3d &T) { std::ostringstream stream; stream << std::setprecision(std::numeric_limits<double>::digits10); Eigen::Vector3d rot = T.rotation().eulerAngles(0,1,2); normalizeEulerAngles(rot); stream << T.translation().transpose() << " " << rot.transpose(); return stream.str(); } class NDTUKF3DNode { private: ros::NodeHandle nh_; NDTUKF3D *ndtukf; boost::mutex ukf_m,message_m; message_filters::Subscriber<sensor_msgs::PointCloud2> *points2_sub_; message_filters::Subscriber<nav_msgs::Odometry> *odom_sub_; ros::Subscriber scan_sub_; ros::Subscriber scan2_sub_; ros::Subscriber gt_sub; ///Laser sensor offset Eigen::Affine3d sensorPoseT; //<<Sensor offset with respect to odometry frame ros::Duration sensorTimeOffset_; Eigen::Affine3d sensorPoseT2; //<<Sensor offset with respect to odometry frame ros::Duration sensorTimeOffset2_; Eigen::Affine3d Told,Todo,Todo_old,Tcum; //<<old and current odometry transformations Eigen::Affine3d initPoseT; //<<Sensor offset with respect to odometry frame pcl::PointCloud<pcl::PointXYZ> scan2_cloud_; ros::Time scan2_t0_; bool use_dual_scan; bool hasSensorPose, hasInitialPose; bool isFirstLoad; bool forceSIR, do_visualize; bool saveMap; ///< indicates if we want to save the map in a regular intervals std::string mapName; ///<name and the path to the map std::string output_map_name; double resolution; double subsample_level; int pcounter; ros::Publisher ukf_pub; ///< The output of UKF is published with this! ros::Publisher marker_pub_; ros::Publisher markerarray_pub_; ros::Publisher pointcloud_pub_; ros::Publisher pointcloud2_pub_; std::string tf_base_link, tf_sensor_link, tf_gt_link, points_topic, odometry_topic, odometry_frame, scan_topic, scan2_topic; ros::Timer heartbeat_slow_visualization_; ros::Timer heartbeat_fast_visualization_; bool do_pub_ndt_markers_; bool do_pub_sigmapoints_markers_; std::ofstream gt_file_; std::ofstream gt2d_file_; std::ofstream est_file_; std::ofstream est2d_file_; std::string gt_topic; bool use_initial_pose_from_gt; boost::shared_ptr<velodyne_rawdata::RawData> data_; boost::shared_ptr<velodyne_rawdata::RawData> data2_; tf::TransformListener tf_listener; int skip_nb_rings_; int skip_start_; double voxel_filter_size_; int cloud_min_size_; bool draw_ml_lines; public: NDTUKF3DNode(ros::NodeHandle param_nh) : data_(new velodyne_rawdata::RawData()), data2_(new velodyne_rawdata::RawData()) { ////////////////////////////////////////////////////////// // Setup the data parser for the raw packets ////////////////////////////////////////////////////////// { data_->setup(param_nh); // To get the calibration file double max_range, min_range, view_direction, view_width; param_nh.param<double>("max_range", max_range, 130.); param_nh.param<double>("min_range", min_range, 2.); param_nh.param<double>("view_direction", view_direction, 0.); param_nh.param<double>("view_width", view_width, 6.3); data_->setParameters(min_range, max_range, view_direction, view_width); param_nh.param<int>("skip_nb_rings", skip_nb_rings_, 0); param_nh.param<int>("skip_start", skip_start_, 0); param_nh.param<double>("voxel_filter_size", voxel_filter_size_, -1.); param_nh.param<int>("cloud_min_size", cloud_min_size_, 2000); // minimum amount of points (to avoid some problems with lost packages...). } // Need to have a separate configuration file for the second scanner... std::string calibration2; param_nh.param<std::string>("calibration2", calibration2, std::string("")); { if (calibration2 != std::string("")) { ros::NodeHandle nh_tmp("scan2"); nh_tmp.setParam("calibration", calibration2); data2_->setup(nh_tmp); double max_range, min_range, view_direction, view_width; param_nh.param<double>("max_range2", max_range, 130.); param_nh.param<double>("min_range2", min_range, 2.); param_nh.param<double>("view_direction2", view_direction, 0.); param_nh.param<double>("view_width2", view_width, 6.3); data2_->setParameters(min_range, max_range, view_direction, view_width); } } ////////////////////////////////////////////////////////// /// Prepare Pose offsets ////////////////////////////////////////////////////////// bool use_sensor_pose, use_initial_pose; double pose_init_x,pose_init_y,pose_init_z, pose_init_r,pose_init_p,pose_init_t; double sensor_pose_x,sensor_pose_y,sensor_pose_z, sensor_pose_r,sensor_pose_p,sensor_pose_t; param_nh.param<bool>("set_sensor_pose", use_sensor_pose, true); param_nh.param<bool>("set_initial_pose", use_initial_pose, false); param_nh.param<bool>("set_initial_pose_from_gt", use_initial_pose_from_gt, false); if(use_initial_pose) { ///initial pose of the vehicle with respect to the map param_nh.param("pose_init_x",pose_init_x,0.); param_nh.param("pose_init_y",pose_init_y,0.); param_nh.param("pose_init_z",pose_init_z,0.); param_nh.param("pose_init_r",pose_init_r,0.); param_nh.param("pose_init_p",pose_init_p,0.); param_nh.param("pose_init_t",pose_init_t,0.); initPoseT = Eigen::Translation<double,3>(pose_init_x,pose_init_y,pose_init_z)* Eigen::AngleAxis<double>(pose_init_r,Eigen::Vector3d::UnitX()) * Eigen::AngleAxis<double>(pose_init_p,Eigen::Vector3d::UnitY()) * Eigen::AngleAxis<double>(pose_init_t,Eigen::Vector3d::UnitZ()) ; hasInitialPose=true; } else { hasInitialPose=false; } if(use_sensor_pose) { ///pose of the sensor with respect to the vehicle odometry frame param_nh.param("sensor_pose_x",sensor_pose_x,0.); param_nh.param("sensor_pose_y",sensor_pose_y,0.); param_nh.param("sensor_pose_z",sensor_pose_z,0.); param_nh.param("sensor_pose_r",sensor_pose_r,0.); param_nh.param("sensor_pose_p",sensor_pose_p,0.); param_nh.param("sensor_pose_t",sensor_pose_t,0.); hasSensorPose = true; sensorPoseT = Eigen::Translation<double,3>(sensor_pose_x,sensor_pose_y,sensor_pose_z)* Eigen::AngleAxis<double>(sensor_pose_r,Eigen::Vector3d::UnitX()) * Eigen::AngleAxis<double>(sensor_pose_p,Eigen::Vector3d::UnitY()) * Eigen::AngleAxis<double>(sensor_pose_t,Eigen::Vector3d::UnitZ()) ; param_nh.param("sensor_pose2_x",sensor_pose_x,0.); param_nh.param("sensor_pose2_y",sensor_pose_y,0.); param_nh.param("sensor_pose2_z",sensor_pose_z,0.); param_nh.param("sensor_pose2_r",sensor_pose_r,0.); param_nh.param("sensor_pose2_p",sensor_pose_p,0.); param_nh.param("sensor_pose2_t",sensor_pose_t,0.); sensorPoseT2 = Eigen::Translation<double,3>(sensor_pose_x,sensor_pose_y,sensor_pose_z)* Eigen::AngleAxis<double>(sensor_pose_r,Eigen::Vector3d::UnitX()) * Eigen::AngleAxis<double>(sensor_pose_p,Eigen::Vector3d::UnitY()) * Eigen::AngleAxis<double>(sensor_pose_t,Eigen::Vector3d::UnitZ()) ; } else { hasSensorPose = false; } double sensor_time_offset; param_nh.param("sensor_time_offset", sensor_time_offset, 0.); sensorTimeOffset_ = ros::Duration(sensor_time_offset); param_nh.param("sensor_time_offset2", sensor_time_offset, 0.); sensorTimeOffset2_ = ros::Duration(sensor_time_offset); ////////////////////////////////////////////////////////// /// Prepare the map ////////////////////////////////////////////////////////// param_nh.param<std::string>("map_file_name", mapName, std::string("basement.ndmap")); param_nh.param<bool>("save_output_map", saveMap, true); param_nh.param<std::string>("output_map_file_name", output_map_name, std::string("ndt_mapper_output.ndmap")); param_nh.param<double>("map_resolution", resolution , 0.2); param_nh.param<double>("subsample_level", subsample_level , 1); fprintf(stderr,"USING RESOLUTION %lf\n",resolution); perception_oru::NDTMap ndmap(new perception_oru::LazyGrid(resolution)); ndmap.loadFromJFF(mapName.c_str()); ROS_INFO_STREAM("Loaded map: " << mapName << " containing " << ndmap.getAllCells().size() << " cells"); ////////////////////////////////////////////////////////// /// Prepare UKF object ////////////////////////////////////////////////////////// ndtukf = new NDTUKF3D(resolution,ndmap); UKF3D::Params ukf_params; param_nh.getParam("motion_model", ndtukf->motion_model); param_nh.getParam("motion_model_offset", ndtukf->motion_model_offset); param_nh.param<double>("resolution_sensor", ndtukf->resolution_sensor, resolution); param_nh.param<double>("ukf_range_var", ukf_params.range_var, 1.); param_nh.param<double>("ukf_alpha", ukf_params.alpha, 0.1); param_nh.param<double>("ukf_beta", ukf_params.beta, 2.); param_nh.param<double>("ukf_kappa", ukf_params.kappa, 3.); param_nh.param<double>("ukf_min_pos_var", ukf_params.min_pos_var, 0.01); param_nh.param<double>("ukf_min_rot_var", ukf_params.min_rot_var, 0.01); param_nh.param<double>("ukf_range_filter_max_dist", ukf_params.range_filter_max_dist, 1.); param_nh.param<int>("ukf_nb_ranges_in_update", ukf_params.nb_ranges_in_update, 100); ndtukf->setParamsUKF(ukf_params); ukf_pub = nh_.advertise<nav_msgs::Odometry>("ndt_ukf",10); ////////////////////////////////////////////////////////// /// Prepare the callbacks and message filters ////////////////////////////////////////////////////////// //the name of the TF link associated to the base frame / odometry frame param_nh.param<std::string>("tf_base_link", tf_base_link, std::string("/base_link")); //the name of the tf link associated to the 3d laser scanner param_nh.param<std::string>("tf_laser_link", tf_sensor_link, std::string("/velodyne_link")); param_nh.param<std::string>("tf_gt_link", tf_gt_link, std::string("")); ///topic to wait for packet data param_nh.param<std::string>("scan_topic", scan_topic, ""); param_nh.param<std::string>("scan2_topic", scan2_topic, ""); use_dual_scan = false; if (scan2_topic != std::string("")) { use_dual_scan = true; if (calibration2 == std::string("")) { ROS_ERROR("no calibration2 parameter given for the scan2 scanner!!!"); } } ///topic to wait for point clouds param_nh.param<std::string>("points_topic",points_topic,"points"); ///topic to wait for odometry messages param_nh.param<std::string>("odometry_topic",odometry_topic,"odometry"); param_nh.param<std::string>("odometry_frame", odometry_frame, "/world"); // If a scan_topic is provided, force to use it if (scan_topic != std::string("")) { ROS_INFO_STREAM("A scan topic is specified [will use that along with tf] : " << scan_topic); scan_sub_ = nh_.subscribe<velodyne_msgs::VelodyneScan>(scan_topic,10,&NDTUKF3DNode::scan_callback, this); if (scan2_topic != std::string("")) { scan2_sub_ = nh_.subscribe<velodyne_msgs::VelodyneScan>(scan2_topic,10,&NDTUKF3DNode::scan2_callback, this); ROS_INFO_STREAM("A scan2 topic is specified [will use that along with tf] : " << scan_topic); } } else { ROS_ERROR_STREAM("No scan_topic specified... quitting."); exit(-1); } isFirstLoad=true; pcounter =0; ////////////////////////////////////////////////////////// /// Visualization ////////////////////////////////////////////////////////// param_nh.param<bool>("do_visualize", do_visualize, true); param_nh.param<bool>("do_pub_ndt_markers", do_pub_ndt_markers_, true); param_nh.param<bool>("do_pub_sigmapoints_markers", do_pub_sigmapoints_markers_, true); param_nh.param<bool>("draw_ml_lines", draw_ml_lines, true); marker_pub_ = nh_.advertise<visualization_msgs::Marker>("visualization_marker", 3); markerarray_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 10); pointcloud_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("interppoints", 15); pointcloud2_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("ml_points", 15); heartbeat_slow_visualization_ = nh_.createTimer(ros::Duration(1.0),&NDTUKF3DNode::publish_visualization_slow,this); heartbeat_fast_visualization_ = nh_.createTimer(ros::Duration(0.1),&NDTUKF3DNode::publish_visualization_fast,this); ////////////////////////////////////////////////////////// /// Evaluation ////////////////////////////////////////////////////////// std::string gt_filename, gt2d_filename, est_filename, est2d_filename; param_nh.param<std::string>("gt_topic",gt_topic,""); param_nh.param<std::string>("output_gt_file", gt_filename, "loc_gt_pose.txt"); param_nh.param<std::string>("output_gt2d_file", gt2d_filename, "loc_gt2d_pose.txt"); param_nh.param<std::string>("output_est_file", est_filename, "loc_est_pose.txt"); param_nh.param<std::string>("output_est2d_file", est2d_filename, "loc_est2d_pose.txt"); if (gt_filename != std::string("")) { gt_file_.open(gt_filename.c_str()); if (tf_gt_link == std::string("")) { ROS_WARN("tf_gt_link not set - will not log any gt data"); } } if (gt2d_filename != std::string("")) { gt2d_file_.open(gt2d_filename.c_str()); if (tf_gt_link == std::string("")) { ROS_WARN("tf_gt_link not set - will not log any gt data"); } } if (est_filename != std::string("")) { est_file_.open(est_filename.c_str()); } if (est2d_filename != std::string("")) { est2d_file_.open(est2d_filename.c_str()); } if (!gt_file_.is_open() || !gt2d_file_.is_open() || !est_file_.is_open() || !est2d_file_.is_open()) { ROS_ERROR_STREAM("Failed to open : " << est_file_.rdbuf() << " | " << est2d_file_.rdbuf() << " | " << gt_file_.rdbuf() << " | " << gt2d_file_.rdbuf()); } if (gt_topic != std::string("")) { ROS_INFO_STREAM("Subscribing to : " << gt_topic); gt_sub = nh_.subscribe<nav_msgs::Odometry>(gt_topic,10,&NDTUKF3DNode::gt_callback, this); } } ~NDTUKF3DNode() { if (gt_file_.is_open()) gt_file_.close(); if (gt2d_file_.is_open()) gt2d_file_.close(); if (est_file_.is_open()) est_file_.close(); if (est2d_file_.is_open()) est2d_file_.close(); delete points2_sub_; delete odom_sub_; delete ndtukf; } void publish_visualization_fast(const ros::TimerEvent &event) { if (do_pub_sigmapoints_markers_) { ukf_m.lock(); std::vector<Eigen::Affine3d> sigmas = ndtukf->getSigmasAsAffine3d(); for (int i = 0; i < sigmas.size(); i++) { markerarray_pub_.publish(ndt_visualisation::getMarkerFrameAffine3d(sigmas[i], "sigmapoints" + ndt_generic::toString(i), 1., 0.1)); std::cout << "sigmas[i] : " << ndt_generic::affine3dToStringRPY(sigmas[i]) << std::endl; } ukf_m.unlock(); } } void publish_visualization_slow(const ros::TimerEvent &event) { if (do_pub_ndt_markers_) { // visualization_msgs::Marker markers_ndt; // ndt_visualisation::markerNDTCells2(*(graph->getLastFeatureFuser()->map), // graph->getT(), 1, "nd_global_map_last", markers_ndt); // marker_pub_.publish(markers_ndt); ukf_m.lock(); marker_pub_.publish(ndt_visualisation::markerNDTCells(ndtukf->map, 1, "nd_map")); ukf_m.unlock(); } } void initialize() { //if not, check if initial robot pose has been set if(!hasInitialPose) { //can't do anything, wait for pose message... ROS_INFO("waiting for initial pose"); return; } //initialize filter Eigen::Vector3d tr = initPoseT.translation(); Eigen::Vector3d rot = initPoseT.rotation().eulerAngles(0,1,2); Todo_old=Todo; Tcum = initPoseT; //ndtukf->initializeFilter(initPoseT, 50, 50, 10, 100.0*M_PI/180.0, 100.0*M_PI/180.0 ,100.0*M_PI/180.0); // ndtukf->initializeFilter(initPoseT, 0.5, 0.5, 0.5, 2.0*M_PI/180.0, 2.0*M_PI/180.0 ,2.0*M_PI/180.0); // ndtukf->initializeFilter(initPoseT, 2, 2, 2, 5.0*M_PI/180.0, 5.0*M_PI/180.0 ,5.0*M_PI/180.0); ndtukf->initializeFilter(initPoseT, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01); isFirstLoad = false; } // Simply to get an easier interface to tf. bool getTransformationForTime(const ros::Time &t0, const std::string &frame_id, tf::Transform &T) { bool success = false; try { success = tf_listener.waitForTransform(odometry_frame, frame_id, t0, ros::Duration(2.0)); } catch (tf::TransformException &ex) { ROS_WARN_THROTTLE(100, "%s", ex.what()); return false; } if (!success) { return false; } tf::StampedTransform Ts; tf_listener.lookupTransform (odometry_frame, frame_id, t0, Ts); T = Ts; return true; } // Simply to get an easier interface to tf. bool getRelativeTransformationForTime(const ros::Time &t0,const ros::Time &t1, const std::string &frame_id,tf::Transform &T) { bool success = false; try { success = tf_listener.waitForTransform(frame_id, t0, frame_id, t1, odometry_frame, ros::Duration(2.0)); } catch (tf::TransformException &ex) { ROS_WARN_THROTTLE(100, "%s", ex.what()); return false; } if (!success) { return false; } tf::StampedTransform Ts; tf_listener.lookupTransform (frame_id, t0, frame_id, t1, odometry_frame, Ts); T = Ts; return true; } bool getTransformationAffine3d(const ros::Time &t0, const std::string &frame_id, Eigen::Affine3d &T) { tf::Transform tf_T; if (!getTransformationForTime(t0, frame_id, tf_T)) { ROS_ERROR_STREAM("Failed to get from /tf : " << frame_id); return false; } tf::transformTFToEigen(tf_T, T); return true; } // Access the scans directly. This to better handle the time offsets / perform interpolation. Anyway it is useful to have better access to the points. void scan_callback(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg) { ukf_m.lock(); // Get the time stamp from the header, the pose at this time will be seen as the origin. ros::Time t0; // Corresponding time stamp which relates the scan to the odometry tf frame. t0 = scanMsg->header.stamp + sensorTimeOffset_; // If we are using the dual scan setup then we need to have the timestamp of the previous one in order to get syncronized pointclouds if (use_dual_scan) { if (scan2_cloud_.empty()) { ukf_m.unlock(); return; } t0 = scan2_t0_ - sensorTimeOffset2_ + sensorTimeOffset_; } // Get the current odometry position (need to check the incremental odometry meassure since last call). { tf::Transform T; if (!getTransformationForTime(t0, tf_base_link, T)) { ROS_INFO_STREAM("Waiting for : " << tf_base_link); ukf_m.unlock(); return; } tf::transformTFToEigen(T, Todo); } //check if we have done iterations if(isFirstLoad) { initialize(); ukf_m.unlock(); return; } Eigen::Affine3d Tm; Tm = Todo_old.inverse()*Todo; if(Tm.translation().norm()<0.01 && fabs(Tm.rotation().eulerAngles(0,1,2)[2])<(0.5*M_PI/180.0)) { ROS_INFO_STREAM("Not enough distance / rot traversed : " << Tm.translation().norm() << " / " << fabs(Tm.rotation().eulerAngles(0,1,2)[2])); ukf_m.unlock(); return; } // We're interessted in getting the pointcloud in the vehicle frame (that is to transform it using the sensor pose offset). pcl::PointCloud<pcl::PointXYZ> cloud, cloud2; velodyne_rawdata::VPointCloud pnts,conv_points; tf::Transform T_sensorpose; tf::transformEigenToTF(sensorPoseT, T_sensorpose); for (size_t next = 0; next < scanMsg->packets.size(); ++next) { data_->unpack(scanMsg->packets[next], pnts); // Get the transformation of this scan packet (the vehicle pose) ros::Time t1 = scanMsg->packets[next].stamp + sensorTimeOffset_; // Get the relative pose... tf::Transform T; if (!getRelativeTransformationForTime(t0, t1, tf_base_link, T)) { continue; } tf::Transform Tcloud = T * T_sensorpose; pcl_ros::transformPointCloud(pnts,conv_points,Tcloud); for (size_t i = 0; i < conv_points.size(); i++) { if (skip_nb_rings_ == 0) { cloud.push_back(pcl::PointXYZ(conv_points.points[i].x, conv_points.points[i].y, conv_points.points[i].z)); } else if (conv_points.points[i].ring % (skip_nb_rings_+1) == skip_start_ % (skip_nb_rings_+1)) { cloud.push_back(pcl::PointXYZ(conv_points.points[i].x, conv_points.points[i].y, conv_points.points[i].z)); } else { } } pnts.clear(); conv_points.clear(); } if (voxel_filter_size_ > 0) { // Create the filtering object pcl::PointCloud<pcl::PointXYZ>::Ptr cloud2(new pcl::PointCloud<pcl::PointXYZ>()); *cloud2 = cloud; pcl::VoxelGrid<pcl::PointXYZ> sor; sor.setInputCloud (cloud2); sor.setLeafSize (voxel_filter_size_, voxel_filter_size_, voxel_filter_size_); pcl::PointCloud<pcl::PointXYZ> cloud_filtered; sor.filter (cloud); // pcl::PointCloud<PointType>::Ptr laserCloudCornerStack(new pcl::PointCloud<PointType>()); // pcl::VoxelGrid<PointType> downSizeFilterCorner; // downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2); // downSizeFilterCorner.setInputCloud(laserCloudCornerStack2); // downSizeFilterCorner.filter(*laserCloudCornerStack); } // Check size of the cloud if (cloud.size() < cloud_min_size_) { ukf_m.unlock(); return; } if (use_dual_scan) { cloud += scan2_cloud_; scan2_cloud_.clear(); } // Tcum = Tcum*Tm; Todo_old=Todo; //update filter -> + add parameter to subsample ndt map in filter step ndtukf->updateAndPredict/*Eff*/(Tm, cloud/*, subsample_level*/, sensorPoseT); //ndtukf->predict(Tm); { sensor_msgs::PointCloud2 pcloud; pcl::toROSMsg(ndtukf->getFilterRaw(), pcloud); pcloud.header.stamp = t0; pcloud.header.frame_id = "interppoints"; pointcloud_pub_.publish(pcloud); } { sensor_msgs::PointCloud2 pcloud; pcl::toROSMsg(ndtukf->getFilterPred(),pcloud); pcloud.header.stamp = t0; pcloud.header.frame_id = "interppoints"; pointcloud2_pub_.publish(pcloud); if (draw_ml_lines) { marker_pub_.publish(ndt_visualisation::getMarkerLineListFromTwoPointClouds(ndtukf->getFilterRaw(), ndtukf->getFilterPred(), 0, "ml_lines", "interppoints", 0.05)); } } //publish pose sendROSOdoMessage(ndtukf->getMean(),t0); ukf_m.unlock(); } // Simply store the point cloud, all the updates are from the scan_callback() void scan2_callback(const velodyne_msgs::VelodyneScan::ConstPtr &scanMsg) { ukf_m.lock(); // Get the time stamp from the header, the pose at this time will be seen as the origin. ros::Time t0; t0 = scanMsg->header.stamp + sensorTimeOffset2_; scan2_t0_ = t0; // Get the current odometry position (need to check the incremental odometry meassure since last call). { tf::Transform T; if (!getTransformationForTime(t0, tf_base_link, T)) { ROS_INFO_STREAM("Waiting for : " << tf_base_link); ukf_m.unlock(); return; } tf::transformTFToEigen(T, Todo); } //check if we have done iterations if(isFirstLoad) { initialize(); ukf_m.unlock(); return; } Eigen::Affine3d Tm; Tm = Todo_old.inverse()*Todo; if(Tm.translation().norm()<0.01 && fabs(Tm.rotation().eulerAngles(0,1,2)[2])<(0.5*M_PI/180.0)) { ukf_m.unlock(); return; } // We're interessted in getting the pointcloud in the vehicle frame (that is to transform it using the sensor pose offset). pcl::PointCloud<pcl::PointXYZ> cloud; velodyne_rawdata::VPointCloud pnts,conv_points; tf::Transform T_sensorpose; tf::transformEigenToTF(sensorPoseT2, T_sensorpose); for (size_t next = 0; next < scanMsg->packets.size(); ++next) { data2_->unpack(scanMsg->packets[next], pnts); // Get the transformation of this scan packet (the vehicle pose) ros::Time t1 = scanMsg->packets[next].stamp + sensorTimeOffset_; // Get the relative pose... tf::Transform T; if (!getRelativeTransformationForTime(t0, t1, tf_base_link, T)) { continue; } tf::Transform Tcloud = T * T_sensorpose; pcl_ros::transformPointCloud(pnts,conv_points,Tcloud); for (size_t i = 0; i < conv_points.size(); i++) { cloud.push_back(pcl::PointXYZ(conv_points.points[i].x, conv_points.points[i].y, conv_points.points[i].z)); } pnts.clear(); conv_points.clear(); } // Check size of the cloud if (cloud.size() < 3000) { ukf_m.unlock(); return; } scan2_cloud_ = cloud; ukf_m.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // bool sendROSOdoMessage(Eigen::Affine3d mean,ros::Time ts){ nav_msgs::Odometry O; static int seq = 0; O.header.stamp = ts; O.header.seq = seq; O.header.frame_id = odometry_frame; O.child_frame_id = "/ukf_pose"; O.pose.pose.position.x = mean.translation()[0]; O.pose.pose.position.y = mean.translation()[1]; O.pose.pose.position.z = mean.translation()[2]; Eigen::Quaterniond q (mean.rotation()); tf::Quaternion qtf; tf::quaternionEigenToTF (q, qtf); O.pose.pose.orientation.x = q.x(); O.pose.pose.orientation.y = q.y(); O.pose.pose.orientation.z = q.z(); O.pose.pose.orientation.w = q.w(); seq++; ukf_pub.publish(O); static tf::TransformBroadcaster br; tf::Transform transform; transform.setOrigin( tf::Vector3(mean.translation()[0],mean.translation()[1], mean.translation()[2]) ); transform.setRotation( qtf ); br.sendTransform(tf::StampedTransform(transform, ts, "world", "ukf_pose")); if (est_file_.is_open()) { est_file_ << ts << " " << perception_oru::transformToEvalString(mean); } if (est2d_file_.is_open()) { est2d_file_ << ts << " " << perception_oru::transformToEval2dString(mean); } if (gt_file_.is_open() && tf_gt_link != std::string("")) { Eigen::Affine3d T_gt; if (getTransformationAffine3d(ts, tf_gt_link, T_gt)) { gt_file_ << ts << " " << perception_oru::transformToEvalString(T_gt); } if (gt2d_file_.is_open()) { gt2d_file_ << ts << " " << perception_oru::transformToEval2dString(T_gt); } } return true; } // Callback void gt_callback(const nav_msgs::Odometry::ConstPtr& msg_in) { Eigen::Quaterniond qd; Eigen::Affine3d gt_pose; qd.x() = msg_in->pose.pose.orientation.x; qd.y() = msg_in->pose.pose.orientation.y; qd.z() = msg_in->pose.pose.orientation.z; qd.w() = msg_in->pose.pose.orientation.w; gt_pose = Eigen::Translation3d (msg_in->pose.pose.position.x, msg_in->pose.pose.position.y,msg_in->pose.pose.position.z) * qd; // Query the pose from the /tf instead (see abouve in sendOdoMessage). // if (gt_file_.is_open()) { // gt_file_ << msg_in->header.stamp << " " << lslgeneric::transformToEvalString(gt_pose); // } // m.lock(); if(use_initial_pose_from_gt && !hasInitialPose) { hasInitialPose = true; ROS_INFO("Set initial pose from GT track"); initPoseT = gt_pose; } // m.unlock(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// }; int main(int argc, char **argv){ ros::init(argc, argv, "NDT-UKF"); ros::NodeHandle paramHandle ("~"); NDTUKF3DNode ukfnode(paramHandle); ros::spin(); return 0; }
#define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include <thread> #include "AppData.h" AppData app; int main(int argv, char *args[]) { if (app.Setup() < 0) return -1; app.Run(); app.Shutdown(); return 0; }
/*********************************************************************** created: Sun Jun 18th 2006 author: Andrzej Krzysztof Haczewski (aka guyver6) purpose: This codec provide FreeImage based image loading *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodecModules/FreeImage/ImageCodec.h" #include "CEGUI/Logger.h" #include "CEGUI/Sizef.h" #include "CEGUI/DataContainer.h" #include "CEGUI/Texture.h" #include <FreeImage.h> namespace { void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) { CEGUI::Logger::getSingleton().logEvent( CEGUI::String("FreeImage error (") + FreeImage_GetFormatFromFIF(fif) + "): " + message, CEGUI::LoggingLevel::Error); } } // Start of CEGUI namespace section namespace CEGUI { FreeImageImageCodec::FreeImageImageCodec() : ImageCodec("FreeImageCodec - FreeImage based image codec") { FreeImage_Initialise(true); FreeImage_SetOutputMessage(&FreeImageErrorHandler); // Getting extensions for (int i = 0; i < FreeImage_GetFIFCount(); ++i) { String exts(FreeImage_GetFIFExtensionList((FREE_IMAGE_FORMAT)i)); // Replace commas with spaces for (size_t i = 0; i < exts.length(); ++i) if (exts[i] == ',') exts[i] = ' '; // Add space after existing extensions if (!d_supportedFormat.empty()) d_supportedFormat += ' '; d_supportedFormat += exts; } } FreeImageImageCodec::~FreeImageImageCodec() { FreeImage_DeInitialise(); } Texture* FreeImageImageCodec::load(const RawDataContainer& data, Texture* result) { int len = (int)data.getSize(); FIMEMORY *mem = 0; FIBITMAP *img = 0; Texture *retval = 0; try { mem = FreeImage_OpenMemory(static_cast<BYTE*>(const_cast<std::uint8_t*>(data.getDataPtr())), len); if (mem == 0) throw MemoryException("Unable to open memory stream, FreeImage_OpenMemory failed"); FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem, len); if (fif == FIF_UNKNOWN) // it may be that it's TARGA or MNG { fif = FIF_TARGA; img = FreeImage_LoadFromMemory(fif, mem, 0); if (img == 0) { fif = FIF_MNG; img = FreeImage_LoadFromMemory(fif, mem, 0); } } else img = FreeImage_LoadFromMemory(fif, mem, 0); if (img == 0) throw GenericException("Unable to load image, FreeImage_LoadFromMemory failed"); FIBITMAP *newImg = FreeImage_ConvertTo32Bits(img); if (newImg == 0) throw GenericException("Unable to convert image, FreeImage_ConvertTo32Bits failed"); FreeImage_Unload(img); img = newImg; newImg = 0; // FreeImage pixel format for little-endian architecture (which CEGUI // supports) is like BGRA. We need to convert that to RGBA. // // It is now: // RED_MASK 0x00FF0000 // GREEN_MASK 0x0000FF00 // BLUE_MASK 0x000000FF // ALPHA_MASK 0xFF000000 // // It should be: // RED_MASK 0x000000FF // GREEN_MASK 0x0000FF00 // BLUE_MASK 0x00FF0000 // ALPHA_MASK 0xFF000000 unsigned int pitch = FreeImage_GetPitch(img); unsigned int height = FreeImage_GetHeight(img); unsigned int width = FreeImage_GetWidth(img); std::uint8_t *rawBuf = new std::uint8_t[width * height << 2]; // convert the bitmap to raw bits (top-left pixel first) FreeImage_ConvertToRawBits(rawBuf, img, pitch, 32, FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, true); // We need to convert pixel format a little // NB: little endian only - I think(!) #if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_BGR for (unsigned int i = 0; i < height; ++i) { for (unsigned int j = 0; j < width; ++j) { unsigned int p = *(((unsigned int*)(rawBuf + i * pitch)) + j); unsigned int r = (p >> 16) & 0x000000FF; unsigned int b = (p << 16) & 0x00FF0000; p &= 0xFF00FF00; p |= r | b; // write the adjusted pixel back *(((unsigned int*)(rawBuf + i * pitch)) + j) = p; } } #endif FreeImage_Unload(img); img = 0; result->loadFromMemory(rawBuf, Sizef(static_cast<float>(width), static_cast<float>(height)), Texture::PixelFormat::Rgba); delete [] rawBuf; retval = result; } catch (Exception&) { } if (img != 0) FreeImage_Unload(img); if (mem != 0) FreeImage_CloseMemory(mem); return retval; } } // End of CEGUI namespace section
#ifndef LTUI_BUTTON_H #define LTUI_BUTTON_H #include "ftxui/component/component.hpp" #include <string> namespace ftxui { class Button : public Component { public: // Constructor. Button() = default; Button(const Button &) = default; Button(Button &&) = default; ~Button() override = default; Button &operator=(const Button &) = default; Button &operator=(Button &&) = default; void set_content(Element val); void set_style(Decorator val); void set_on_enter(std::function<void()> val); // Component implementation. Element Render() override; bool OnEvent(Event event) override; private: // State. Element content = text(L""); Decorator focused_style = inverted; Decorator normal_style = bgcolor(Color::Blue) | color(Color::White); // State update callback. std::function<void()> on_enter = []() {}; }; } // namespace ftxui #endif
#include "PUtils.h" #include "LBLibraryBase.h" float PUtils::playItemBounceEffect(Node* pNode, float time) { WJBase *base = WJBase::convertToWJBase(pNode); if (base) { float scale = base->getSavedScale(); pNode->stopActionByTag(NODE_BOUNCE_ACTION_TAG); pNode->runAction(Sequence::create(ScaleTo::create(time, scale * 1.2f), ScaleTo::create(time, scale * 0.8f), ScaleTo::create(time, scale * 1.1f), ScaleTo::create(time, scale * 0.9f), ScaleTo::create(time * 0.667f, scale), nullptr))->setTag(NODE_BOUNCE_ACTION_TAG); } return time * 4.667f; } float PUtils::playItemBounceEffect(Node* pNode, int num, float time) { WJBase *base = WJBase::convertToWJBase(pNode); if (base) { float scale = base->getSavedScale(); pNode->stopActionByTag(NODE_BOUNCE_ACTION_TAG); FiniteTimeAction* act = Sequence::create(ScaleTo::create(time, scale * 1.2f), ScaleTo::create(time, scale * 0.8f), ScaleTo::create(time, scale * 1.1f), ScaleTo::create(time, scale * 0.9f), ScaleTo::create(time * 0.667f, scale), nullptr); pNode->runAction(Repeat::create(act, num))->setTag(NODE_BOUNCE_ACTION_TAG); } return num * time * 4.667f; } void PUtils::playBubbleEffect(Node *node) { // 提示气泡的呼吸效果 node->stopAllActions(); Action *action = RepeatForever::create( Sequence::create( ScaleTo::create(1.0f, 0.95f, 1.0f), ScaleTo::create(1.0f, 1.0f, 0.95f), NULL)); node->runAction(action); } void PUtils::playNodeWaveEffect(Node *node) { // 节点的旋转效果 WJBase *base = dynamic_cast<WJBase*>(node); if (base && !node->getActionByTag(NODE_RUN_WAVE_ACTION_TAG)) { node->stopAllActions(); base->restoreSavedRotation(0.2f); Action *action = Sequence::create( RotateBy::create(0.2f, 10), RotateBy::create(0.2f, -10), RotateBy::create(0.2f, -10), RotateBy::create(0.2f, 10), NULL); node->runAction(action)->setTag(NODE_RUN_WAVE_ACTION_TAG); } } void PUtils::playBubbleEffectWithCurrentScale(Node* node) { float currentScaleX = node->getScaleX(); float currentScaleY = node->getScaleY(); node->stopAllActions(); node->runAction(RepeatForever::create(Sequence::createWithTwoActions( ScaleTo::create(1.0f, 0.95f * currentScaleX, currentScaleY), ScaleTo::create(1.0f, currentScaleX, 0.95f * currentScaleY)))); } void PUtils::playSuspenEffect(Node *node) { WJBase *base = WJBase::convertToWJBase(node); if (base && base->getSavedPosition() != Vec2::ZERO) base->restoreSavedPosition(0.0f); node->stopAllActions(); Action *action = RepeatForever::create( Sequence::create( MoveBy::create(1.0f, Vec2(0, 15)), MoveBy::create(1.0f, Vec2(0, -15)), NULL)); node->runAction(action); } void PUtils::playSuspenEffect(Node *node, float delay) { node->runAction(Sequence::create( DelayTime::create(delay), CCCallFunc::create([=](){ PUtils::playSuspenEffect(node); }), NULL)); } void PUtils::playNodeScaleAni(Node *node, int time, float delayTime) { WJBase *base = WJBase::convertToWJBase(node); if (base) { node->stopActionByTag(SHOW_SCALE_ACTION_TAG); node->runAction(CCRepeat::create( Sequence::create( ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), CCDelayTime::create(delayTime), NULL), time))->setTag(SHOW_SCALE_ACTION_TAG); } } void PUtils::playNodeScaleAniForever(Node *node, float delayTime) { WJBase *base = WJBase::convertToWJBase(node); if (base) { node->stopActionByTag(SHOW_SCALE_ACTION_TAG); node->runAction(CCRepeatForever::create( Sequence::create( CCDelayTime::create(delayTime), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), NULL)))->setTag(SHOW_SCALE_ACTION_TAG); } } void PUtils::playNodeScaleAniForeverFirst(Node *node, float delayTime) { WJBase *base = WJBase::convertToWJBase(node); if (base) { node->stopActionByTag(SHOW_SCALE_ACTION_TAG); node->runAction(CCRepeatForever::create( Sequence::create( ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), ScaleTo::create(0.15f, 1.1f * base->getSavedScale()), ScaleTo::create(0.15f, 1.0f * base->getSavedScale()), CCDelayTime::create(delayTime), NULL)))->setTag(SHOW_SCALE_ACTION_TAG); } } void PUtils::stopNodeScaleAction(Node *node) { WJBase *base = WJBase::convertToWJBase(node); if (base) { node->stopActionByTag(SHOW_SCALE_ACTION_TAG); base->restoreSavedScale(); } } bool PUtils::isOneCollideWithOne(Vec2 src, Vec2 des, float raduis) { return des.getDistance(src) <= raduis; } bool PUtils::isOneCollideWithAnotherOne(Node *src, Node *des, float raduis) { return GetDistance(src, des) <= raduis; } bool PUtils::isOneCollideWithOne(Node *src, Node *des, bool isPointCheck, Vec2 srcOffset, Vec2 desOffset) { Rect srcRect = WJUtils::calculateAABBInWorld(src); Rect desRect = WJUtils::calculateAABBInWorld(des); if (isPointCheck) { Vec2 ps = Vec2(srcRect.getMidX(), srcRect.getMidY()) + srcOffset; Vec2 pd = Vec2(desRect.getMidX(), desRect.getMidY()) + desOffset; return isOneCollideWithOne(ps, pd); } else { return desRect.intersectsRect(srcRect); } } bool PUtils::isOneCollideWithOne(Vec2 src, Node *des, bool isRectCheck, float halfWidth, float halfHeight) { Rect desRect = WJUtils::calculateAABBInWorld(des); if (isRectCheck) { Rect rect = Rect(src.x - halfWidth, src.y - halfHeight, halfWidth * 2, halfHeight * 2); return desRect.intersectsRect(rect); } else { return desRect.containsPoint(src); } } bool PUtils::isOneCollideWithOne(Node *src, Node*dest, float x, float y) { Rect srcRect = WJUtils::calculateAABBInWorld(src); Rect temp = WJUtils::calculateAABBInWorld(dest); Vec2 origin = temp.origin; float width = temp.size.width + x; float height = temp.size.height + y; Rect destRect(origin.x, origin.y, width, height); return destRect.intersectsRect(srcRect); } bool PUtils::isOneCollideWithOne(Vec2 src, Node*dest, float offsetX, float offsetY, float x, float y) { Rect temp = WJUtils::calculateAABBInWorld(dest); float ox = temp.origin.x + offsetX; float oy = temp.origin.y + offsetY; float width = temp.size.width + x; float height = temp.size.height + y; Rect destRect(ox, oy, width, height); return destRect.containsPoint(src); } float PUtils::GetDistance(Node* _node1, Node* _node2) { Vec2 _p1 = _node1->getParent()->convertToWorldSpace(_node1->getPosition()); Vec2 _p2 = _node2->getParent()->convertToWorldSpace(_node2->getPosition()); return _p1.getDistance(_p2); } bool PUtils::getPointImageIsTransparent(Image *m_textureImage, const Vec2 &pointImage) { if (pointImage.x <= 0 || pointImage.x >= m_textureImage->getWidth() || pointImage.y <= 0 || pointImage.y >= m_textureImage->getHeight()) return true; Color4B color = WJGraphics::getImagePointColor(m_textureImage, pointImage.x, m_textureImage->getHeight() - pointImage.y); if (color.r > 10 || color.g > 10 || color.b > 10) return false; return true; } void PUtils::runActionMoveTo(Node *node, const Vec2 &pointWorld, bool enableMoving /*= false*/, bool stopAllAction /*= true*/) { runActionMoveToWithCallBack(node, pointWorld, nullptr, enableMoving, stopAllAction); } void PUtils::runActionMoveToWithCallBack(Node *node, const Vec2 &pointWorld, const ActionEndCallback &callback /*= nullptr*/, bool enableMoving /*= false*/, bool stopAllAction /*= true*/) { WJBase *base = dynamic_cast<WJBase*>(node); if (base) { base->setEnabled(enableMoving); Vec2 &pointNow = base->getPositionWorld(); float distance = pointNow.getDistance(pointWorld); //float time = float(distance / GAME_ITEM_MOVE_SPEED); float time = 0.5f; if (stopAllAction) node->stopAllActions(); node->runAction(Sequence::create( MoveTo::create(time, node->getParent()->convertToNodeSpace(pointWorld)), CCCallFunc::create([=]() { dynamic_cast<WJBase*>(node)->setEnabled(true); }), nullptr)); // 移动完了的回调 WJUtils::delayExecute(time, [=](float d) { if (callback) callback(node); }); } } Vec2 PUtils::getPositionInWorldFromPoint(Node *node, const Vec2 &point) { if (node->getParent()) { return node->getParent()->convertToWorldSpace(point); } return node->getPosition(); } void PUtils::addListener(WJBase* base, const WJTouchBoolCallback &touchAble, const WJTouchBoolCallback &willMoveto, const WJTouchCallback &touchEnd, const WJTouchCallback &click) { base->noClickMoveEffect(); base->setRelativeMove(true); base->setTouchSwallowsTouches(true); base->setOnTouchAble(touchAble); base->setOnWillMoveTo(willMoveto); base->setOnTouchEnded(touchEnd); base->setOnClick(click); base->saveCurrentProperties(); } void PUtils::addListenerWithKey(WJLayerJson *json, const char * key, int fromint, int endInt, const WJTouchBoolCallback &touchAble, const WJTouchBoolCallback &willMoveto, const WJTouchCallback &touchEnd, const WJTouchCallback &click) { WJBase *base; for (int i = fromint; i <= endInt; i++) { std::string str = WJUtils::stringAddInt(key, i, 3); base = json->getSubBase(str.c_str()); base->setUserTag(i); PUtils::addListener(base, touchAble, willMoveto, touchEnd, click); } } void PUtils::setNodeShadowVisible(WJLayerJson *json, Node *node, bool visible) { // node对应的阴影的key默认为node的key + _shadow std::string key = json->getSubKeyByNode(node); key.append("_shadow"); Node *shadow = json->getSubSprite(key.c_str()); if (shadow) { shadow->setVisible(visible); } } void PUtils::addWJChildToAnotherParent(cocos2d::Node *child, cocos2d::Node*newParent) { WJBase *base = WJBase::convertToWJBase(child); if (base) { base->setAutoRegisterTouchEventListener(false); } child->retain(); child->removeFromParentAndCleanup(false); newParent->addChild(child); child->release(); if (base) { base->setAutoRegisterTouchEventListener(true); } } //为 1 时代表准确的获取每个像素, 值越大,越不准确 #define CZ 4 float PUtils::getImgBlankspace(Image* image) { unsigned char *data = image->getData(); size_t len = image->getDataLen(); int w = image->getWidth(); int h = image->getHeight(); int total_pixel = ((w + CZ - 1) / CZ) * ((h + CZ - 1) / CZ); int blankspace_pixel = 0; for (int i = 0; i < h; i += CZ) { for (int j = 0; j < w; j += CZ) { int index = i * w * 4 + j * 4 + 3; if (data[index] <= 20) { blankspace_pixel++; } } } return (float)blankspace_pixel / total_pixel; } void PUtils::playParticle(const char * fileName, Node *parent, const Vec2 &pointParent, int zOrder, int tag) { // 播放粒子特效 ParticleSystemQuad *particle = ParticleSystemQuad::create(fileName); particle->setPosition(pointParent); particle->setTag(tag); particle->setPositionType(ParticleSystem::PositionType::RELATIVE); parent->addChild(particle, zOrder); } Action * PUtils::delayPlayFunc(Node *node, CallFunc *call, float time) { return node->runAction(Sequence::create( DelayTime::create(time), call, nullptr)); } void PUtils::playNodeCircleTipForever(Node *node, float delayTime /*= 5.0f*/, float interval /*= 0.3f*/) { if (node) { node->runAction(RepeatForever::create(Sequence::create( DelayTime::create(interval), FadeOut::create(0.3f), DelayTime::create(interval), FadeIn::create(0.3f), DelayTime::create(interval), FadeOut::create(0.3f), DelayTime::create(interval), FadeIn::create(0.3f), DelayTime::create(interval), FadeOut::create(0.3f), DelayTime::create(delayTime), FadeIn::create(0.3f), DelayTime::create(interval), FadeOut::create(0.3f), nullptr ))); } }
// prgrm for making the reverse of the a given number #include<iostream.h> #include<conio.h> void main() { clrscr(); unsigned long int a,b,c,d=0; cout<<endl<<"enter a number :"; cin>>a; b=a; // logic for reverse of a number while(a>0) { c=a%10; d=(d*10)+c; a=a/10; } cout<<endl<<"the reverse of the no. "<<b<<" is : "<<d; getch(); }
#include <string> #include <vector> using namespace std; long long solution(int a, int b) { if (a > b) { swap(a, b); } long long answer = b; for (int i = 0; i < b - a; i++) { answer += a + i; } return answer; }
//----------------------------------------------------------------------------// // VIDEO THREAD CLASS // //----------------------------------------------------------------------------// // Author: Łukasz Korbel, e-mail: korbel85@gmail.com // // Licence: GPL // // Version: 1.0 // //----------------------------------------------------------------------------// // Version info: // // 1.0 - frame aquisition an rendering // //----------------------------------------------------------------------------// #ifndef VIDEO_THREAD_H #define VIDEO_THREAD_H //includes //----------------------------------------------------------------------------// #include <QThread> #include <QMutex> #include <QWaitCondition> #include <QImage> #include <QPainter> #include <QRect> #include <QPen> #include <QFont> #include <QBrush> #include "MicroCounter.h" #include "FaceDatabase.h" #include "VideoInput.h" //cant be forwarde cause of inlines #include "texteffects.h" class Matrix; // video input reading and main window videoWidget frame rendering //----------------------------------------------------------------------------// class VideoThread : public QThread { Q_OBJECT public: VideoThread (VideoInput* vi, FaceDatabase *fdb, QObject *parent = 0); ~VideoThread(); bool showFps() const; bool showFrame() const; void enableComputations( bool enable); signals: void rawFrame(const Matrix&); void newVideoFrame(const QImage&); public slots: void askedForData(); void showFps(bool on); void showFrame(bool on); /* Processed frame visualization is turned off in release version void processedFrame( const QImage&); */ void updateScanArea( int, int, int, int); void faceClassified( int); protected: void run(); private: //thread control QMutex mutex; QWaitCondition condition; bool abort, stopComputation; //video aquisition VideoInput *videoInput; Matrix matrixData_, dataToSend_; bool needNewMatrixData_; //rendering objects bool showFps_, showFrame_, showIndividual_; MicroCounter microCounter_; FaceDatabase * faceDatabase; Individual individual; QImage videoFrame_; //, processedFrame_; QPainter painter_; QPen pen_, dataPen_; QFont font_, dataFont_; QBrush dataBrush_; QRect scanRect_, faceRect_, nameRect_; TextEffects textEffects; }; //----------------------------------------------------------------------------// /* Processed frame visualization is turned off in release version inline void VideoThread:: processedFrame( const QImage& frame) { QMutexLocker locker( &mutex); processedFrame_ = frame; processedFrame_.setColorTable( videoInput->colorTable()); }*/ //----------------------------------------------------------------------------// inline void VideoThread:: updateScanArea(int x1, int y1, int x2, int y2) { QMutexLocker locker( &mutex); scanRect_.setCoords( x1, y1, x2, y2); } //----------------------------------------------------------------------------// inline bool VideoThread:: showFps() const { return showFps_; } //----------------------------------------------------------------------------// inline bool VideoThread:: showFrame() const { return showFrame_; } //----------------------------------------------------------------------------// inline void VideoThread:: showFps(bool on) { QMutexLocker locker( &mutex); showFps_ = on; } //----------------------------------------------------------------------------// inline void VideoThread:: showFrame(bool on) { QMutexLocker locker( &mutex); showFrame_ = on; } //----------------------------------------------------------------------------// #endif
#include "UIHandler.h" UIHandler::UIHandler() { } UIHandler::~UIHandler() { } void UIHandler::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext) { this->m_maxUIComponents = 28; this->m_nrOfUIComponents = 0; for (unsigned int i = 0; i < this->m_maxUIComponents; i++) { UIComponent* newUIComp = new UIComponent; this->m_UIComponents.push_back(newUIComp); } this->m_maxTextComponents = 35; this->m_nrOfTextComponents = 0; for (unsigned int i = 0; i < this->m_maxTextComponents; i++) { TextComponent* newTextComp = new TextComponent; this->m_textComponents.push_back(newTextComp); } this->m_spriteBatch = new DirectX::SpriteBatch(deviceContext); this->m_spriteFont = new DirectX::SpriteFont(device, L"../Assets/UIelements/consolas.spritefont"); this->m_nrOfTextures = 16; for (unsigned int i = 0; i < this->m_nrOfTextures; i++) { ID3D11ShaderResourceView* newTexture = nullptr; this->m_textures.push_back(newTexture); } DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/gamelogo.png", nullptr, &this->m_textures.at(0)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/background.png", nullptr, &this->m_textures.at(1)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/charswide.png", nullptr, &this->m_textures.at(2)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/cog.png", nullptr, &this->m_textures.at(3)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/button.png", nullptr, &this->m_textures.at(4)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/crosshair_aim.png", nullptr, &this->m_textures.at(5)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/Controls.png", nullptr, &this->m_textures.at(6)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/combinedframes.png", nullptr, &this->m_textures.at(7)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level0.png", nullptr, &this->m_textures.at(8)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level1.png", nullptr, &this->m_textures.at(9)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level2.png", nullptr, &this->m_textures.at(10)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level3.png", nullptr, &this->m_textures.at(11)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level4.png", nullptr, &this->m_textures.at(12)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/level5.png", nullptr, &this->m_textures.at(13)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/levelframe.png", nullptr, &this->m_textures.at(14)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/Sprites/Header.png", nullptr, &this->m_textures.at(15)); /*DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/cat.png", nullptr, &this->m_textures.at(0)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/gamelogo.png", nullptr, &this->m_textures.at(1)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/keymaps_temp.png", nullptr, &this->m_textures.at(2)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/menubg.png", nullptr, &this->m_textures.at(3)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/button.png", nullptr, &this->m_textures.at(4)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/crosshair.png", nullptr, &this->m_textures.at(5)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/crosshair_aim.png", nullptr, &this->m_textures.at(6)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level0.png", nullptr, &this->m_textures.at(7)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level1.png", nullptr, &this->m_textures.at(8)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level2.png", nullptr, &this->m_textures.at(9)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level3.png", nullptr, &this->m_textures.at(10)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level4.png", nullptr, &this->m_textures.at(11)); DirectX::CreateWICTextureFromFile(device, L"../Assets/UIelements/level5.png", nullptr, &this->m_textures.at(12));*/ D3D11_BLEND_DESC BlendState; ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC)); BlendState.RenderTarget[0].BlendEnable = TRUE; BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; BlendState.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; BlendState.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; BlendState.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; BlendState.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; BlendState.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA; BlendState.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; device->CreateBlendState(&BlendState, &this->m_blendState); } void UIHandler::DrawUI() { UIComponent* tempUIComp = nullptr; TextComponent* tempTextComp = nullptr; this->m_spriteBatch->Begin(DirectX::SpriteSortMode::SpriteSortMode_BackToFront, this->m_blendState); for (unsigned int i = 0; i < this->m_nrOfUIComponents; i++) { tempUIComp = this->m_UIComponents.at(i); if (tempUIComp->active) { if (tempUIComp->spriteID > 0 && tempUIComp->spriteID < this->m_textures.size()) { this->m_spriteBatch->Draw(this->m_textures.at(tempUIComp->spriteID), tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, tempUIComp->origin, tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth); } else { this->m_spriteBatch->Draw(this->m_textures.at(0), tempUIComp->position, nullptr, DirectX::Colors::White, tempUIComp->rotation, tempUIComp->origin, tempUIComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempUIComp->layerDepth); } } } for (unsigned int i = 0; i < this->m_nrOfTextComponents; i++) { tempTextComp = this->m_textComponents.at(i); if (tempTextComp->active) { if(!tempTextComp->useBlackText) this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::White, tempTextComp->rotation, tempTextComp->origin, tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth); else this->m_spriteFont->DrawString(this->m_spriteBatch, tempTextComp->text.c_str(), tempTextComp->position, DirectX::Colors::Black, tempTextComp->rotation, tempTextComp->origin, tempTextComp->scale, DirectX::SpriteEffects::SpriteEffects_None, tempTextComp->layerDepth); } } this->m_spriteBatch->End(); } void UIHandler::Shutdown() { for (unsigned int i = 0; i < this->m_maxUIComponents; i++) { delete this->m_UIComponents.at(i); } for (unsigned int i = 0; i < this->m_maxTextComponents; i++) { delete this->m_textComponents.at(i); } //this->m_spriteBatch.release(); if (this->m_spriteBatch) { delete this->m_spriteBatch; this->m_spriteBatch = nullptr; } if (this->m_spriteFont) { delete this->m_spriteFont; this->m_spriteFont = nullptr; } for (ID3D11ShaderResourceView* text : this->m_textures) { if (text != nullptr) { text->Release(); text = nullptr; } } } UIComponent* UIHandler::GetNextUIComponent() { if (this->m_nrOfUIComponents < this->m_maxUIComponents) { this->m_nrOfUIComponents++; return this->m_UIComponents.at(this->m_nrOfUIComponents - 1); } return nullptr; } int UIHandler::RemoveUIComponent(UIComponent * ptr) { if (ptr) { size_t nrOfUIComps = this->m_UIComponents.size(); for (size_t i = 0; i < nrOfUIComps; i++) { if (ptr == this->m_UIComponents.at(i)) { delete this->m_UIComponents.at(i); this->m_UIComponents.at(i) = nullptr; if (i < this->m_nrOfUIComponents - 1) { for (size_t k = i; k < nrOfUIComps - 1; k++) { this->m_UIComponents.at(k) = this->m_UIComponents.at(k + 1); } } UIComponent* newUIComp = new UIComponent; this->m_UIComponents.at(this->m_nrOfUIComponents - 1) = newUIComp; this->m_nrOfUIComponents--; return 1; } } } return 0; } int UIHandler::RemoveLastUIComponent() { this->m_nrOfUIComponents--; this->m_UIComponents.at(this->m_nrOfUIComponents)->ResetValuesToDefault(); return this->m_nrOfUIComponents; } TextComponent* UIHandler::GetNextTextComponent() { if (this->m_nrOfTextComponents < this->m_maxTextComponents) { return this->m_textComponents.at(this->m_nrOfTextComponents++); } return nullptr; } int UIHandler::RemoveLastTextComponent() { this->m_nrOfTextComponents--; this->m_textComponents.at(this->m_nrOfTextComponents)->ResetValuesToDefault(); return this->m_nrOfTextComponents; } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos); } } void UIHandler::UpdateUIComponentsclicked(DirectX::XMFLOAT2 mousePos, DirectX::XMFLOAT2 windowSize) { std::vector<UIComponent*>::iterator uiCompIter; for (uiCompIter = this->m_UIComponents.begin(); uiCompIter != this->m_UIComponents.end(); uiCompIter++) { (*uiCompIter)->UpdateClicked(mousePos, windowSize); } }
#include "PCB.h" #include "system.h" PCB::PCB(SpaceId c_pid, SpaceId c_parent_pid, Thread* c_thread, int c_status) { DEBUG('z', "Started making PCB\n"); pid = c_pid; parent_pid = c_parent_pid; thread = c_thread; status = c_status; files = new BitMap(MAX_USER_FILES); DEBUG('z', "Finished making PCB\n"); } SpaceId PCB::GetPID() { return pid; } SpaceId PCB::GetParentPID() { return parent_pid; } void PCB::SetParentPID(SpaceId p_pid) { parent_pid = p_pid; } Thread* PCB::GetThread() { return thread; } void PCB::SetThread(Thread* newThread) { thread = newThread; } int PCB::GetStatus() { return status; } void PCB::SetStatus(int stat) { status = stat; } void PCB::AddFile(UserOpenFile* file) { int index = files->Find(); if (index > -1) { openFiles[index] = file; } } UserOpenFile* PCB::GetFile(int index) { if (files->Test(index)) { return openFiles[index]; } return NULL; } void PCB::CloseFile(UserOpenFile* file) { for(int i=0; i<MAX_USER_FILES; i++) { if (files->Test(i) && openFiles[i] == file) { fm->Close(file->index); delete openFiles[i]; files->Clear(i); return; } } }
/* * Copyright (c) 2018 Nordic Semiconductor ASA * * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause */ extern "C"{ #include <drivers/clock_control.h> #include <drivers/clock_control/nrf_clock_control.h> } #include <irq.h> #include <logging/log.h> #include <nrf.h> #include <esb.h> #include <zephyr.h> #include <zephyr/types.h> #include <sys/reboot.h> #include <stdio.h> #include "simplemesh.h" LOG_MODULE_REGISTER(simplemesh, LOG_LEVEL_DBG); #ifdef CONFIG_SM_GPIO_DEBUG #include <drivers/gpio.h> const struct device *sm_gpio_dev; //0.625 us per toggle //#define PIN_SM_SET gpio_pin_set(sm_gpio_dev, CONFIG_SM_PIN_APP, 1) //#define PIN_SM_CLEAR gpio_pin_set(sm_gpio_dev, CONFIG_SM_PIN_APP, 0) #define PIN_SM_SET (*(int * const)0x50000508) = 1<<CONFIG_SM_PIN_APP #define PIN_SM_CLEAR (*(int *) 0x5000050C) = 1<<CONFIG_SM_PIN_APP void sm_gpio_init(const struct device *gpio_dev) { sm_gpio_dev = gpio_dev; } #else #define PIN_SM_SET #define PIN_SM_CLEAR #endif //----------------------------- rx event, thread and handler ----------------------------- void simplemesh_rx_thread(); bool rx_routing_handler(message_t &msg); void rx_gateway_handler(message_t &msg); void rx_json_handler(message_t &msg); void rx_file_header_handler(uint8_t * data,uint8_t size); void rx_file_section_handler(message_t &section_msg); //----------------------------- startup init ----------------------------- int esb_initialize(); //----------------------------- protocol specific hanlding ----------------------------- uint8_t coord_assign_short_id(std::string &longid); void mesh_set_node_id(std::string &longid, uint8_t shortid); bool mesh_request_node_id(); bool take_node_id(message_t &msg,uint8_t &nodeid); static mesh_rx_json_handler_t m_app_rx_json_handler = NULL; json request; bool critical_parse=false; //----------------------------- -------------------------- ----------------------------- #define STACKSIZE 8192 #define RX_PRIORITY 20 K_SEM_DEFINE(sem_rx, 0, 5);//can be assigned while already given K_THREAD_DEFINE(sm_receiver, STACKSIZE, simplemesh_rx_thread, NULL, NULL, NULL, RX_PRIORITY, 0, 0); K_SEM_DEFINE(sem_id_set, 0, 1); K_SEM_DEFINE(sem_ack, 0, 1); static struct esb_payload tx_payload; static struct esb_payload rx_payload; static message_t rx_msg; static message_t tx_msg; int64_t rx_timestamp; file_t file_data; static volatile bool esb_enabled = false; static volatile bool esb_completed = false; static volatile bool esb_tx_complete = false; static uint8_t g_ttl = 2; static uint8_t g_node_id = 0xff; static uint8_t g_node_is_router = false; static uint8_t g_retries = 3; static uint16_t g_retries_timeout_ms = 200; static uint16_t g_set_id_timeout_ms = 300; static std::string g_node_uid = ""; static std::string base_topic = "sm"; static std::string broadcast_topic_start = base_topic + "{"; static std::string self_topic; #ifdef CONFIG_SM_LISTENER static uint8_t g_active_listener = true; #else static uint8_t g_active_listener = false; #endif #if CONFIG_SM_COORDINATOR static uint8_t g_coordinator = true; #else static uint8_t g_coordinator = false; #endif std::map<std::string,uint8_t> nodes_ids; void mesh_pre_tx() { if(!esb_enabled) { esb_initialize(); } if(g_active_listener){ esb_stop_rx(); } } void mesh_post_tx() { #ifdef CONFIG_SM_LISTENER if(g_active_listener){ esb_start_rx(); LOG_DBG("switch to RX mode"); } #else esb_disable(); esb_enabled = false; #endif esb_tx_complete = true; } void mesh_message_2_esb_payload(message_t *msg, struct esb_payload *p_tx_payload) { //esb only parameters p_tx_payload->noack = true;//Never request an ESB acknowledge p_tx_payload->pipe = 0;//pipe is the selection of the address to use p_tx_payload->data[1] = msg->control; p_tx_payload->data[2] = msg->pid; p_tx_payload->data[3] = msg->source; uint8_t start_payload; if(MESH_IS_BROADCAST(msg->control)) { start_payload = sm::bcast_header_length; } else { p_tx_payload->data[4] = msg->dest; start_payload = sm::p2p_header_length; } //this is the total ESB packet length p_tx_payload->length = msg->payload_length + start_payload; p_tx_payload->data[0] = p_tx_payload->length; memcpy( p_tx_payload->data+start_payload, msg->payload, msg->payload_length); } void mesh_esb_2_message_payload(struct esb_payload *p_rx_payload,message_t *msg) { msg->control = p_rx_payload->data[1]; msg->pid = p_rx_payload->data[2]; msg->source = p_rx_payload->data[3]; msg->rssi = p_rx_payload->rssi; //dest is processed by esb rx function uint8_t payload_start; if(MESH_IS_BROADCAST(msg->control)) { msg->dest = 255; payload_start = 4; } else { msg->dest = p_rx_payload->data[4]; payload_start = 5; } msg->payload_length = p_rx_payload->length - payload_start; if(msg->payload_length > 0) { msg->payload = p_rx_payload->data + payload_start; } } //does not copy, must keep context, use tx_msg void mesh_tx_message(message_t* p_msg) { mesh_pre_tx(); mesh_message_2_esb_payload(p_msg,&tx_payload); esb_completed = false;//reset the check LOG_DBG("TX writing (%d) %d bytes",tx_payload.data[2],tx_payload.data[0]); //should not wait for esb_completed here as does not work from ISR context //NRF_ESB_TXMODE_AUTO is used no need to call nrf_esb_start_tx() //which could be used for a precise time transmission esb_write_payload(&tx_payload); } void mesh_tx_ack(message_t& msg, uint8_t ttl) { tx_msg.control = sm::control::ack | ttl; tx_msg.pid = msg.pid; tx_msg.source = msg.dest; tx_msg.dest = msg.source; tx_msg.payload = nullptr; tx_msg.payload_length = 0; mesh_tx_message(&tx_msg); } void mesh_bcast_packet(sm::pid pid,uint8_t * data=nullptr,uint8_t size=0) { if(size > sm::max_msg_size) { return; } tx_msg.control = sm::control::broadcast | g_ttl; tx_msg.pid = (uint8_t)pid; tx_msg.source = g_node_id; tx_msg.payload = data; tx_msg.payload_length = size; mesh_tx_message(&tx_msg); } void mesh_send_packet(sm::pid pid,uint8_t dest,uint8_t * data,uint8_t size) { tx_msg.control = sm::control::msg_no_ack | g_ttl; tx_msg.pid = (uint8_t)(pid); tx_msg.source = g_node_id; tx_msg.dest = dest; tx_msg.payload = data; tx_msg.payload_length = size; mesh_tx_message(&tx_msg); } bool mesh_send_packet_ack(sm::pid pid,uint8_t dest, uint8_t* data, uint8_t size) { tx_msg.control = sm::control::msg_needs_ack | g_ttl; tx_msg.pid = (uint8_t)pid; tx_msg.source = g_node_id; tx_msg.dest = dest; tx_msg.payload = data; tx_msg.payload_length = size; bool success = false; for(uint8_t i=0;i<g_retries;i++){ mesh_tx_message(&tx_msg); if(k_sem_take(&sem_ack,K_MSEC(g_retries_timeout_ms)) == 0){ LOG_DBG("sem_ack obtained"); success = true; break; } printf("sem_ack_error:timedout (%d)\n",i); } return success; } //----------------------------- rx event, thread and handler ----------------------------- void event_handler(struct esb_evt const *event) { switch (event->evt_id) { case ESB_EVENT_TX_SUCCESS: LOG_DBG("TX SUCCESS pid(%d)",tx_msg.pid); mesh_post_tx(); break; case ESB_EVENT_TX_FAILED: LOG_DBG("TX FAILED pid(%d)",tx_msg.pid); (void) esb_flush_tx(); mesh_post_tx(); break; case ESB_EVENT_RX_RECEIVED://not yet parsed in rx_msg rx_timestamp = k_uptime_ticks(); LOG_DBG("RX Event"); k_sem_give(&sem_rx); break; default: LOG_ERR("ESB Unhandled Event (%d)",event->evt_id); break; } esb_completed = true; } //thread jitter guard int64_t sm_rx_sync_ms(int lseq,int64_t delay) { int64_t target_ticks_delay = rx_timestamp + k_ms_to_ticks_floor64(delay); if(target_ticks_delay < k_uptime_ticks()){ int64_t delta = k_uptime_ticks() - target_ticks_delay; printf("sm> /!\\ target_ticks_delay missed by (%d) us at seq(%d)\n", (int)k_ticks_to_us_floor64(delta),lseq); } while((target_ticks_delay) > k_uptime_ticks()); return target_ticks_delay; } int64_t sm_sync_ms(int lseq,int64_t start,int64_t delay) { int64_t target_ticks_delay = start + k_ms_to_ticks_floor64(delay); if(target_ticks_delay < k_uptime_ticks()){ int64_t delta = k_uptime_ticks() - target_ticks_delay; printf("sm> /!\\ target_ticks_delay missed by (%d) us at seq(%d)\n", (int)k_ticks_to_us_floor64(delta),lseq); } while((target_ticks_delay) > k_uptime_ticks()); return target_ticks_delay; } void simplemesh_rx_thread() { while(true) { if(k_sem_take(&sem_rx,K_MSEC(100)) == 0){ while(esb_read_rx_payload(&rx_payload) == 0) { mesh_esb_2_message_payload(&rx_payload,&rx_msg); LOG_DBG("RX pid(%u) size(%u)",rx_msg.pid,rx_msg.payload_length); if(rx_routing_handler(rx_msg))//id get set / ack { //handled in function call }else if(m_app_rx_json_handler != NULL)//for sm::pid::json { rx_json_handler(rx_msg); } else{ rx_gateway_handler(rx_msg); } } } } } void rx_json_handler(message_t &msg) { if(msg.pid == (uint8_t)(sm::pid::json)){ std::string payload((char*)msg.payload,msg.payload_length); if(is_broadcast(payload) || is_self(payload)){ size_t json_begin = payload.find("{"); std::string topic = payload.substr(0,json_begin); std::string json_body = payload.substr(json_begin); critical_parse = true;//exceptions config not supported, ends in libc-hooks.c "exit\n" #ifdef CONFIG_EXCEPTIONS try{ request = json::parse(json_body); }catch(json::parse_error& ex){ printf("json::parse threw an exception at byte %d\n",ex.byte); } #else request = json::parse(json_body); #endif critical_parse = false; m_app_rx_json_handler(msg.source,topic,request); } } } void rx_gateway_handler(message_t &rx_msg) { //the gateway treats json as text if((rx_msg.pid == (uint8_t)(sm::pid::text)) || (rx_msg.pid == (uint8_t)(sm::pid::json))) { std::string text((char*)rx_msg.payload,rx_msg.payload_length); printf("%s\n",text.c_str()); }else if(rx_msg.pid == (uint8_t)sm::pid::file_info){ rx_file_header_handler(rx_msg.payload,rx_msg.payload_length); }else if(rx_msg.pid == (uint8_t)sm::pid::file_section){ rx_file_section_handler(rx_msg); } else { printf("%d:{\"pid\":0x%02X,\"length\":%d}\n",rx_msg.source,rx_msg.pid, rx_msg.payload_length); } } void rx_file_header_handler(uint8_t * data,uint8_t size) { std::string payload((char*)data,size); size_t json_begin = payload.find("{"); std::string topic = payload.substr(0,json_begin); std::string json_body = payload.substr(json_begin); critical_parse = true; request = json::parse(json_body); critical_parse = false; file_data.name = request["name"]; file_data.size = request["size"]; file_data.seq_size = request["seq_size"]; file_data.nb_seq = request["nb_seq"]; file_data.last_seq_size = request["last_seq_size"]; file_data.seq_count = 0; file_data.buffer_p = file_data.buffer; } void rx_file_section_handler(message_t &section_msg) { uint8_t this_seq_size = file_data.seq_size; if(file_data.seq_count > file_data.nb_seq-1){ printf("file_error;seq_count:%u;nb_seq:%u\n",file_data.seq_count,file_data.nb_seq); return; }else if(file_data.seq_count == file_data.nb_seq-1){ this_seq_size = file_data.last_seq_size; } if(section_msg.payload_length != this_seq_size){ printf("file_error;seq:%u;seq_size:%u;payload_length:%u\n",file_data.seq_count,this_seq_size,section_msg.payload_length); return; } memcpy(file_data.buffer_p,section_msg.payload,this_seq_size); file_data.buffer_p+=this_seq_size; file_data.seq_count++; if(file_data.seq_count == file_data.nb_seq){ printf("uwb_cir_acc;size:%u;nb_seq:%u;data:",file_data.size,file_data.nb_seq); for(uint32_t i=0;i<file_data.size;i++){ printf("%02X",file_data.buffer[i]); } printf("\n"); } } bool rx_routing_handler(message_t &msg) { LOG_DBG("dest(%d) ; self(%d) ; pid(%d) ; ctl(%d)",msg.dest, g_node_id, msg.pid, msg.control); if(MESH_IS_BROADCAST(msg.control)){ if(msg.pid == (uint8_t)sm::pid::node_id_get){ #ifdef CONFIG_SM_COORDINATOR printf("node_id_get\n"); if(g_coordinator){ LOG_DBG("coordinator received get node id"); std::string longid((char*)rx_msg.payload,rx_msg.payload_length); uint8_t newid = coord_assign_short_id(longid); mesh_set_node_id(longid,newid); }else{ LOG_DBG("get node id ignored, not coordinator"); } #endif return true; }else if(msg.pid == (uint8_t)sm::pid::node_id_set){ printf("received set node id\n"); bool taken = take_node_id(msg,g_node_id); if(taken){ printf("giving sem_id_set\n"); k_sem_give(&sem_id_set);//unleash the higher prio waiting for 'g_node_id' json j; j["rf_cmd"] = "sid"; j["sid"] = g_node_id; mesh_bcast_json(j); } return true; }else if(msg.pid == (uint8_t)sm::pid::node_id_reset){ //this feature cannot be supported in single threaded apps like the simple_mesh_cli where main is blocked with console_getline() LOG_DBG("rx node_id_reset calling mesh_request_node_id()"); //cannot call mesh_request_node_id() from same rx_thread due sem_id_set dead-lock sys_reboot(SYS_REBOOT_WARM);//param unused on ARM-M return true; } } else if(msg.dest == g_node_id){ LOG_DBG("dest == self (%d) for pid (%d)",g_node_id,msg.pid); if(MESH_WANT_ACKNOWLEDGE(msg.control)){ LOG_DBG("sending acknowledge back to (%d)",msg.source); mesh_tx_ack(msg,g_ttl); return false;//still have to process the received message further } else if(MESH_IS_ACKNOWLEDGE(msg.control)){ LOG_DBG("acknowledge received from (%d)",msg.source); k_sem_give(&sem_ack); return true; } } //only re-route messaegs directed to other than the current node itself else if(g_node_is_router) { //mesh_forward_message(msg);//a mesh forward is destructive, to be done at last step } return false; } //----------------------------- startup init ----------------------------- int clocks_start(void) { int err; int res; struct onoff_manager *clk_mgr; struct onoff_client clk_cli; clk_mgr = z_nrf_clock_control_get_onoff(CLOCK_CONTROL_NRF_SUBSYS_HF); if (!clk_mgr) { LOG_ERR("Unable to get the Clock manager"); return -ENXIO; } sys_notify_init_spinwait(&clk_cli.notify); err = onoff_request(clk_mgr, &clk_cli); if (err < 0) { LOG_ERR("Clock request failed: %d", err); return err; } do { err = sys_notify_fetch_result(&clk_cli.notify, &res); if (!err && res) { LOG_ERR("Clock could not be started: %d", res); return res; } } while (err); LOG_DBG("HF clock started"); return 0; } int esb_initialize() { int err; uint8_t base_addr_0[4] = {0xE7, 0xE7, 0xE7, 0xE7}; uint8_t base_addr_1[4] = {0xC2, 0xC2, 0xC2, 0xC2}; uint8_t addr_prefix[8] = {0xE7, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8}; struct esb_config config = ESB_DEFAULT_CONFIG; config.protocol = ESB_PROTOCOL_ESB_DPL; config.retransmit_delay = 600; config.bitrate = ESB_BITRATE_2MBPS; config.event_handler = event_handler; config.selective_auto_ack = true; err = esb_init(&config); if (err) { return err; } err = esb_set_base_address_0(base_addr_0); if (err) { return err; } err = esb_set_base_address_1(base_addr_1); if (err) { return err; } err = esb_set_prefixes(addr_prefix, ARRAY_SIZE(addr_prefix)); if (err) { return err; } err = esb_set_tx_power(ESB_TX_POWER_4DBM); if (err) { return err; } LOG_INF("setting channel (%d) RF Freq %d MHz",CONFIG_SM_CHANNEL,2400+CONFIG_SM_CHANNEL); err = esb_set_rf_channel(CONFIG_SM_CHANNEL); if (err) { return err; } #ifdef CONFIG_SM_LISTENER LOG_INF("Setting up for packet receiption"); err = esb_start_rx(); if (err) { LOG_ERR("RX setup failed, err %d", err); return err; } #endif esb_enabled = true; return 0; } void sm_start() { int err; err = clocks_start(); if (err) { return; } err = esb_initialize(); if (err) { LOG_ERR("ESB initialization failed, err %d", err); return; } LOG_INF("sm_start initialization complete"); long unsigned int id0 = NRF_FICR->DEVICEID[0];//just for type casting and readable printing long unsigned int id1 = NRF_FICR->DEVICEID[1]; char uid_text[20]; int str_len = sprintf(uid_text,"%08lX%08lX",id0,id1); g_node_uid = std::string(uid_text,str_len); self_topic = base_topic + "/" + g_node_uid; LOG_DBG("always start by requesting short id from [0]"); if(mesh_request_node_id()){//with broadcast retries and sem waiting for 'set id' if(g_coordinator){ g_coordinator = false;//request node id got acknowledged printf("sm_start> not coordinator\n"); } }else{ if(g_coordinator){ std::string uid = sm_get_uid(); g_node_id = 0; nodes_ids[uid] = g_node_id; printf("sm_start> [%s] acting as coordinator with short id [0]\n",uid.c_str()); json j; j["rf_cmd"] = "sid"; j["sid"] = g_node_id; mesh_bcast_json(j); }else{ printf("sm_start> waiting for coordinator, short id [%d]\n",g_node_id); } } if(g_coordinator){ k_sleep(K_MSEC(1)); mesh_bcast_packet(sm::pid::node_id_reset); } } void sm_set_callback_rx_json(mesh_rx_json_handler_t rx_json_handler) { m_app_rx_json_handler = rx_json_handler; } //----------------------------- protocol specific hanlding ----------------------------- //self_uid -> dest void mesh_send_file_info(uint8_t dest_id, json &data) { std::string message = sm_get_topic() + data.dump(); mesh_send_packet_ack(sm::pid::file_info,dest_id,(uint8_t*)message.c_str(),message.length()); } //blocking unlimited size void mesh_send_file(const char * name, uint8_t dest,uint8_t* data, uint32_t size) { uint8_t seq_size = sm::max_msg_size; uint32_t nb_seq = (size / seq_size); uint8_t last_seq_size = sm::max_msg_size; if(size <= seq_size){ nb_seq = 1; last_seq_size = size; }else if((size % seq_size) != 0){ nb_seq++; last_seq_size = size % seq_size; } json info; info["name"] = name; info["size"] = size; info["nb_seq"] = nb_seq; info["seq_size"] = seq_size; info["last_seq_size"] = last_seq_size; mesh_send_file_info(dest,info); for(uint32_t i=0;i<nb_seq;i++){ if(i == nb_seq-1){//if last seq_size = last_seq_size; } if(!mesh_send_packet_ack(sm::pid::file_section,dest,data,seq_size)){ LOG_ERR("mesh_tx_file_ack() failed"); continue; } if(i != nb_seq-1){//if not lat data += seq_size; } } } //--json //self_uid -> bcast void mesh_bcast_json(json &data) { std::string message = sm_get_topic() + data.dump(); mesh_bcast_packet(sm::pid::text,(uint8_t*)message.c_str(),message.length()); } //target_uid -> bcast void mesh_bcast_json_to(json &data,std::string &target) { std::string message = sm_get_base_topic() + "/" + target + data.dump(); mesh_bcast_packet(sm::pid::text,(uint8_t*)message.c_str(),message.length()); } //self_uid -> dest void mesh_send_json(uint8_t dest_id, json &data,bool ack = false) { std::string message = sm_get_topic() + data.dump(); if(ack){ mesh_send_packet_ack(sm::pid::json,dest_id,(uint8_t*)message.c_str(),message.length()); }else{ mesh_send_packet(sm::pid::json,dest_id,(uint8_t*)message.c_str(),message.length()); } } //--------------------------------- coordinator management functions --------------------------------- bool take_node_id(message_t &msg,uint8_t &nodeid) { std::string uid = sm_get_uid(); uint8_t len_node_id = uid.length(); if(msg.payload_length != len_node_id+3){ LOG_ERR("unexpected set node id length %d instead of %d",msg.payload_length,len_node_id+3); return false; } std::string this_node_id_str((char*)msg.payload,len_node_id); if(this_node_id_str.compare(uid) != 0){ LOG_DBG("not for this node id : uid[%s] received[%s]\n",uid.c_str(),this_node_id_str.c_str()); return false; } sscanf((char*)(msg.payload+len_node_id+1),"%2hhx",&nodeid); return true; } //a node id is needed before it's possible to send and receive directed messages bool mesh_request_node_id() { tx_msg.control = sm::control::broadcast | g_ttl; tx_msg.pid = (uint8_t)sm::pid::node_id_get; tx_msg.source = g_node_id; tx_msg.dest = 0; std::string uid = sm_get_uid(); tx_msg.payload = (uint8_t*)uid.c_str(); tx_msg.payload_length = uid.length(); bool success = false; for(uint8_t i=0;i<g_retries;i++){ mesh_tx_message(&tx_msg); int64_t start = k_uptime_ticks(); if(k_sem_take(&sem_id_set,K_MSEC(g_set_id_timeout_ms)) == 0){//result sscanf in g_node_id int64_t delta = k_uptime_ticks() - start; printf("sm> obtained node id set to [%u] after %d us\n",g_node_id,k_ticks_to_us_floor32(delta)); return true; }else{ int64_t delta = k_uptime_ticks() - start; printf("sm> sem_id_set timeout after %d us\n",k_ticks_to_us_floor32(delta)); } } printf("sm> id request retries out\n"); return success; } void mesh_set_node_id(std::string &longid, uint8_t shortid) { tx_msg.control = sm::control::broadcast | 2;//Peer to peer with 1 time to live tx_msg.pid = (uint8_t)(sm::pid::node_id_set); tx_msg.source = g_node_id;//does not matter char shortid_char[3]; sprintf(shortid_char,"%02x",shortid); std::string shortid_str(shortid_char,2); std::string response = longid + ":" +shortid_str; tx_msg.payload = (uint8_t*)response.c_str(); tx_msg.payload_length = response.length(); mesh_tx_message(&tx_msg); printf("sm> assigned node id (%u) to [%s]\n",shortid,longid.c_str()); } uint8_t coord_assign_short_id(std::string &longid) { if(nodes_ids.find(longid) != nodes_ids.end()){//remote node restart proof, keeps same id return nodes_ids[longid]; }else{ uint8_t newid = nodes_ids.size();//((size-1):index+1) nodes_ids[longid] = newid; return newid; } } bool is_self(std::string &payload) { return (payload.rfind(self_topic,0) == 0); } bool is_broadcast(std::string &payload) { return (payload.rfind(broadcast_topic_start,0) == 0); } std::string sm_get_base_topic() { return base_topic; } std::string sm_get_topic() { return self_topic; } std::string sm_get_uid() { return g_node_uid; } uint8_t sm_get_sid() { return g_node_id; } void sm_diag(json &data) { std::string rf_cmd = data["rf_cmd"]; if(rf_cmd.compare("ping") == 0){ json rf_cmd_response; rf_cmd_response["rf_cmd"] = "pong"; rf_cmd_response["sid"] = g_node_id; rf_cmd_response["rssi"] = rx_msg.rssi; rf_cmd_response["time"] = rx_timestamp; mesh_bcast_json(rf_cmd_response); printf("sm> ping -> pong ; rssi=-%d dBm; time = %d (1/%d ms)\n",rx_msg.rssi, (int)rx_timestamp,k_ms_to_ticks_floor32(1)); }else if(rf_cmd.compare("target_ping") == 0){ //Forward the request to the target json ping_request; ping_request["rf_cmd"] = "ping"; std::string target = data["target"]; mesh_bcast_json_to(ping_request, target); printf("sm> ping ; target=%s\n",target.c_str()); //then repsond for self diag json rf_cmd_response; rf_cmd_response["rf_cmd"] = "pinger"; rf_cmd_response["rssi"] = rx_msg.rssi; rf_cmd_response["sid"] = g_node_id; rf_cmd_response["time"] = rx_timestamp; mesh_bcast_json(rf_cmd_response); printf("sm> pinger ; rssi=-%d dBm; time = %d (1/%d ms)\n",rx_msg.rssi, (int)rx_timestamp,k_ms_to_ticks_floor32(1)); }else if(rf_cmd.compare("sid") == 0){ if(data.contains("sid")){ if(g_coordinator){//as someone else assigning ids coordinator roles is lost printf("sm> dropped coordinator role as got assigned an id\n"); g_coordinator = false; } uint8_t prev_id = g_node_id; g_node_id = data["sid"]; printf("sm> set node id updated (%d) -> (%d)\n",prev_id,g_node_id); } json rf_cmd_response; rf_cmd_response["rf_cmd"] = "sid"; rf_cmd_response["sid"] = g_node_id; mesh_bcast_json(rf_cmd_response); printf("sm> short id = %d\n",g_node_id); } } void sm_start_rx() { g_active_listener = true; esb_start_rx(); } void sm_stop_rx() { g_active_listener = false; esb_stop_rx(); }
#include "content\Singularity.Content.h" namespace Singularity { namespace Content { class SmurfModelImporter : public Singularity::Content::IModelImporter { private: #pragma region Nested Classes struct FileHeader { char FileId[5]; unsigned Version; unsigned MeshCount; unsigned ColliderCount; }; struct StaticMeshHeader { unsigned Type; unsigned MeshType; char MeshId[255]; unsigned VertexCount; unsigned IndexCount; unsigned MaterialCount; }; struct AnimatedMeshHeader { unsigned Type; unsigned MeshType; char MeshId[255]; unsigned VertexCount; unsigned IndexCount; unsigned MaterialCount; unsigned JointCount; unsigned FrameCount; unsigned KeyFrameCount; }; struct CollisionHeader { unsigned Type; unsigned ColliderCount; unsigned BoxColliderCount; unsigned SphereColliderCount; unsigned CapsuleColliderCount; }; struct FrameDescription { unsigned int JointIndex; unsigned int FrameNumber; Vector3 Translation[3]; Vector3 Rotation[3]; Vector3 Scale[3]; float RotationTangentX[4]; float RotationTangentY[4]; float RotationTangentZ[4]; float TranslationTangentX[4]; float TranslationTangentY[4]; float TranslationTangentZ[4]; }; struct MaterialDescription { unsigned Type; char TextureName[255]; float MainColor[4]; float AmbientColor[4]; float Diffuse; float Eccentricity; }; struct JointData { unsigned FrameId; unsigned JointCount; unsigned Joints; }; struct BoxColliderDescription { Vector3 Center; Vector3 HalfWidth; Quaternion Orientation; }; #pragma endregion #pragma region Variables String m_kDefaultPath; unsigned m_pBufferLength; char* m_pBuffer; #pragma endregion #pragma region Methods unsigned MoveToNextMesh(unsigned offset); Singularity::Graphics::Mesh* ExtractStaticMesh(StaticMeshHeader* header); Singularity::Graphics::SkinnedMesh* ExtractAnimatedMesh(AnimatedMeshHeader* header); Singularity::Graphics::Material* ExtractMaterial(AnimatedMeshHeader* header); Singularity::Animations::Animation* ExtractAnimation(AnimatedMeshHeader* header); Singularity::Components::GameObject* ExtractCollider(Singularity::Components::GameObject* parent, CollisionHeader* header, unsigned index, unsigned type); #pragma endregion protected: #pragma region Overriden Properties inline const int Get_ModelCount() { return ((FileHeader*)m_pBuffer)->MeshCount; }; #pragma endregion #pragma region IContentImporter Methods virtual void LoadFile(String path); #pragma endregion #pragma region IModelImporter Methods Singularity::Components::GameObject* LoadModel(unsigned index); Singularity::Graphics::Mesh* LoadMesh(unsigned index); Singularity::Graphics::Material* LoadMaterial(unsigned index); #pragma endregion public: #pragma region Constructors and Finalizers SmurfModelImporter(String defaultPath = "") : m_pBufferLength(0), m_pBuffer(NULL), m_kDefaultPath(defaultPath) { }; ~SmurfModelImporter(); #pragma endregion void LoadCollisionData(Singularity::Components::GameObject* object); }; } }
#include <stdio.h> int sum_Digits(int num); int main() { int num, sum; printf("Enter any number to find sum of digits: "); scanf("%d", &num); sum = sum_Digits(num); printf("Sum of digits of %d = %d", num, sum); return 0; } int sum_Digits(int num) { if(num == 0) return 0; return ((num % 10) + sum_Digits(num / 10)); }
#ifndef I2CBUS_H #define I2CBUS_H #include "LocalTypes.h" #include "IoError.h" #include "IoBuffer.h" class I2CBus { public: virtual Status Send(byte value) = 0; virtual Status Send(byte cmd, byte value) = 0; virtual Status Send(byte cmd, byte* data, int dataLen) = 0; virtual Status Send(byte cmd, word value) = 0; virtual Status Receive(byte& value) = 0; virtual Status Receive(byte cmd, byte& value) = 0; virtual Status Receive(byte cmd, byte* data, int dataLen) = 0; virtual Status Receive(byte cmd, word& value) = 0; }; #endif //I2CBUS_H
#include "stdafx.h" #include "BSplineCurve.h" BSplineCurve::BSplineCurve() { } BSplineCurve::~BSplineCurve() { } BSplineCurve::BSplineCurve(int num_vertices):Curve(num_vertices) { this->setFlag(1); } //float bezierToBSpline[4][4] = { { 1.0 / 6,0,0,0 },{ 2.0 / 3,2.0 / 3,1.0 / 3,1.0 / 6 },{ 1.0 / 6,1.0 / 3,2.0 / 3,2.0 / 3 },{ 0,0,0,1.0 / 6 } }; void BSplineCurve::OutputBezier(FILE *file) { int num_line = getNumVertices()-3; int num_verts = 3*num_line+1; float *bSplineToBezier = new float[16]{ 1.0f / 6,0,0,0, 2.0f / 3,2.0f / 3,1.0f / 3,1.0f / 6 , 1.0f / 6,1.0f / 3,2.0f / 3,2.0f / 3 , 0,0,0,1.0f / 6 }; Matrix bezierToBSplineM(bSplineToBezier); delete bSplineToBezier; for (size_t i = 0; i < num_line; i++) { fprintf(file, "\nbezier\nnum_vertices %d\n", 4); float *bspline = new float[12]{ getVertex(i).x(),getVertex(i + 1).x(),getVertex(i + 2).x(),getVertex(i + 3).x(), getVertex(i).y(),getVertex(i + 1).y(),getVertex(i + 2).y(),getVertex(i + 3).y(), getVertex(i).z(),getVertex(i + 1).z(),getVertex(i + 2).z(),getVertex(i + 3).z(), }; Matrix bsplineM(bspline); Matrix res = bsplineM * bezierToBSplineM; for (size_t i = 0; i < 4; i++) { fprintf(file, "%f %f %f\n", res.Get(i, 0), res.Get(i, 1), res.Get(i, 2)); } delete bspline; } } // void BSplineCurve::OutputBezier(FILE *file) { // fprintf(file, "\nbezier\n"); // fprintf(file, "num_vertices %d\n", getNumVertices()); // float bezierToBSpline[4][4] = { { 1.0 / 6,0,0,0 },{ 2.0 / 3,2.0 / 3,1.0 / 3,1.0 / 6 },{ 1.0 / 6,1.0 / 3,2.0 / 3,2.0 / 3 },{ 0,0,0,1.0 / 6 } }; // for (size_t i = 0; i < getNumVertices(); i++) // { // float x = 0, y = 0, z = 0; // for (size_t j = 0; j < getNumVertices(); j++) // { // x += getVertex(j).x()*bezierToBSpline[j][i]; // y += getVertex(j).y()*bezierToBSpline[j][i]; // z += getVertex(j).z()*bezierToBSpline[j][i]; // } // fprintf(file, "%f %f %f\n", x, y, z); // } // } void BSplineCurve::OutputBSpline(FILE *file) { fprintf(file, "\nbspline\n"); fprintf(file, "num_vertices %d\n", getNumVertices()); for (size_t i = 0; i < getNumVertices(); i++) { fprintf(file, "%f %f %f\n", getVertex(i).x(), getVertex(i).y(), getVertex(i).z()); } }
vector<int> rightView(Node *root) { vector<int> output; if(root==NULL) { return output; } int min_level = INT_MAX; int max_level = INT_MIN; queue<pair<Node*,int>> Q; unordered_map<int,vector<int>> hash; Q.push(make_pair(root,0)); while(!Q.empty()) { Node* first = Q.front().first; int second = Q.front().second; hash[second].push_back(first->data); Q.pop(); min_level = min(min_level,second); max_level = max(max_level,second); if(first->left!=NULL) { Q.push(make_pair(first->left,second+1)); } if(first->right!=NULL) { Q.push(make_pair(first->right,second+1)); } } for(int i=min_level;i<=max_level;i++) { output.push_back(hash[i].back()); } return output; }
// // PocketTextElite - port of Elite[TM] trading system // Copyright (C) 2008-2009 Michael Fink // /// \file MarketView.hpp Market view // #pragma once // forward references class IMainFrame; /// market view class MarketView : public CDialogImpl<MarketView>, public CDialogResize<MarketView>, public CWinDataExchange<MarketView> { public: MarketView(IMainFrame& mainFrame) :m_mainFrame(mainFrame) { } enum { IDD = IDD_MARKET_FORM }; BOOL PreTranslateMessage(MSG* pMsg) { return CWindow::IsDialogMessage(pMsg); } void SetSelectedPlanet(unsigned int uiSelectedPlanet){ m_uiSelectedPlanet = uiSelectedPlanet; } void UpdateView(); void UpdateBuySellButton(); private: friend class CDialogResize<MarketView>; BEGIN_DDX_MAP(MarketView) DDX_CONTROL_HANDLE(IDC_STATIC_TITLE, m_scTitle) DDX_CONTROL_HANDLE(IDC_STATIC_CASH_CARGO_INFO, m_scCashCargoInfo) DDX_CONTROL_HANDLE(IDC_BUTTON_MARKET_BUY, m_btnBuy) DDX_CONTROL_HANDLE(IDC_BUTTON_MARKET_SELL, m_btnSell) DDX_CONTROL_HANDLE(IDC_LIST_TRADEGOODS, m_lcTradegoods) END_DDX_MAP() BEGIN_DLGRESIZE_MAP(MarketView) DLGRESIZE_CONTROL(IDC_LIST_TRADEGOODS, DLSZ_SIZE_X | DLSZ_SIZE_Y) DLGRESIZE_CONTROL(IDC_STATIC_FUEL, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_BUTTON_BUY_FUEL_TENTH, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_BUTTON_BUY_FUEL_ONE, DLSZ_MOVE_Y) DLGRESIZE_CONTROL(IDC_BUTTON_BUY_FUEL_FULL, DLSZ_MOVE_Y) END_DLGRESIZE_MAP() BEGIN_MSG_MAP(MarketView) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_BUTTON_MARKET_BUY, BN_CLICKED, OnClickedButtonMarketBuy) COMMAND_HANDLER(IDC_BUTTON_MARKET_SELL, BN_CLICKED, OnClickedButtonMarketSell) COMMAND_HANDLER(IDC_BUTTON_BUY_FUEL_ONE, BN_CLICKED, OnClickedButtonBuyFuelOne) COMMAND_HANDLER(IDC_BUTTON_BUY_FUEL_TENTH, BN_CLICKED, OnClickedButtonBuyFuelTenth) COMMAND_HANDLER(IDC_BUTTON_BUY_FUEL_FULL, BN_CLICKED, OnClickedButtonBuyFuelFull) NOTIFY_HANDLER(IDC_LIST_TRADEGOODS, LVN_ITEMCHANGED, OnListTradegoodsSelChanged) CHAIN_MSG_MAP(CDialogResize<MarketView>) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/); LRESULT OnClickedButtonMarketBuy(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnClickedButtonMarketSell(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnClickedButtonBuyFuelOne(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnClickedButtonBuyFuelTenth(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnClickedButtonBuyFuelFull(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); LRESULT OnListTradegoodsSelChanged(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/); private: IMainFrame& m_mainFrame; /// currently selected planet; may differ from current unsigned int m_uiSelectedPlanet; CStatic m_scTitle; CStatic m_scCashCargoInfo; CButton m_btnBuy; CButton m_btnSell; CListViewCtrl m_lcTradegoods; };
#include <bits/stdc++.h> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } ll startX, startY, x2, y2; ll n; string s; vector<pr> winds; bool check(ll days){ ll windsX = 0; ll windsY = 0; for(char c : s){ if(c == 'U'){ windsY++; } else if(c == 'D'){ windsY--; } else if(c == 'L'){ windsX--; } else if(c == 'R'){ windsX++; } } ll takeWind = days / n; ll remainWind = days % n; windsX *= takeWind; windsY *= takeWind; for(ll i = 0; i < remainWind; i++){ if(s[i] == 'U'){ windsY++; } else if(s[i] == 'D'){ windsY--; } else if(s[i] == 'L'){ windsX--; } else if(s[i] == 'R'){ windsX++; } } ll oriX = startX + windsX; ll oriY = startY + windsY; ll need = abs(oriX - x2) + abs(oriY - y2); return need <= days; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); cin >> startX >> startY >> x2 >> y2; cin >> n; cin >> s; ll left = 0; ll right = 1e18; ll ans = -1; while(left < right){ ll mid = left + (right - left)/2; if(check(mid)){ ans = mid; right = mid; } else{ left = mid + 1; } } cout << ans << endl; }
#pragma once #include "base/ast.hpp" #include "base/error.hpp" namespace z { namespace Ast { /*! \brief A compilation unit The Unit AST node is the owner for all AST nodes in the unit. This node maintains two namespace hierarchies - the root namespace is the namespace for all types defined in this unit - the import namespace is the namespace for all types imported into the unit from other modules. */ class Unit { public: typedef SLst<z::Ast::Namespace> NamespaceStack; typedef SLst<z::Ast::Scope> ScopeStack; typedef SLst<z::Ast::TypeSpec> TypeSpecStack; typedef std::map<const z::Ast::TypeSpec*, Ptr<const z::Ast::Expr> > DefaultValueList; typedef SLst<const Body> BodyList; typedef SLst<const z::Ast::CoerceList> CoerceListList; typedef std::list<Token> NsPartList; typedef std::map<z::string, int> HeaderFileList; typedef size_t UniqueId_t; typedef z::stack<const Ast::ForeachStatement*> ForeachStack; public: Unit(); ~Unit(); public: // everything related to imported header files /// \brief Return the header file list /// \return The header file list inline const HeaderFileList& headerFileList() const {return _headerFileList;} /// \brief Add a header file to the unit /// \param list the header file to add inline void addheaderFile(const z::string& filename) {_headerFileList[filename]++;} private: /// \brief The list of header files imported into this unit HeaderFileList _headerFileList; public: // everything related to namespace stack inline NamespaceStack& namespaceStack() {return _namespaceStack;} inline void addNamespace(z::Ast::Namespace& ns) {_namespaceStack.push(ns);} void leaveNamespace(); private: NamespaceStack _namespaceStack; public: // everything related to namesace of current unit /// \brief Add a namespace part to the unit /// \param part NS part to add inline void addNamespacePart(const Token& part) {_nsPartList.push_back(part);} /// \brief Return the namespace part list /// \return The namespace part list inline const NsPartList& nsPartList() const {return _nsPartList;} private: /// \brief Unit Unit namespace NsPartList _nsPartList; public: // everything related to root namespace /// \brief Return the root namespace /// \return The root namespace inline Root& rootNS() {return _rootNS.get();} inline const Root& rootNS() const {return _rootNS.get();} private: /// \brief This NS contains all types defined in the current compilation unit. Ptr<z::Ast::Root> _rootNS; public: // everything related to import namespace /// \brief Return the import namespace /// \return The import namespace inline Root& importNS() {return _importNS.get();} inline const Root& importNS() const {return _importNS.get();} private: /// \brief This NS contains all imported typespec's. /// It is not used for source file generation, only for reference. Ptr<z::Ast::Root> _importNS; public: // everything related to anonymous namespace /// \brief add to the anonymous namespace inline void addAnonymous(z::Ast::ChildTypeSpec& ts) {_anonymousNS.get().addChild(ts);} inline const Root& anonymousNS() const {return _anonymousNS.get();} private: /// \brief This NS contains all imported typespec's. /// It is not used for source file generation, only for reference. Ptr<z::Ast::Root> _anonymousNS; public: // everything related to default values /// \brief Return the default value list /// \return The default value list inline const DefaultValueList& defaultValueList() const {return _defaultValueList;} /// \brief Add a default value to the unit /// \param typeSpec the typeSpec to add /// \param expr the expr to add inline void addDefaultValue(const TypeSpec& typeSpec, const Expr& expr) {_defaultValueList[z::ptr(typeSpec)].reset(expr);} private: /// \brief The list of default values for types in this unit DefaultValueList _defaultValueList; public: // everything related to type coercion struct CoercionResult { enum T { None, Lhs, Rhs }; }; public: const z::Ast::QualifiedTypeSpec* canCoerceX(const z::Ast::QualifiedTypeSpec& lhs, const z::Ast::QualifiedTypeSpec& rhs, CoercionResult::T& mode) const; inline const z::Ast::QualifiedTypeSpec* canCoerce(const z::Ast::QualifiedTypeSpec& lhs, const z::Ast::QualifiedTypeSpec& rhs) const; const z::Ast::QualifiedTypeSpec& coerce(const z::Ast::Token& pos, const z::Ast::QualifiedTypeSpec& lhs, const z::Ast::QualifiedTypeSpec& rhs); public: /// \brief Return the coercion list /// \return The coercion list inline const CoerceListList& coercionList() const {return _coerceListList;} /// \brief Add a coercion list to the unit /// \param list the coercion list to add inline void addCoercionList(const CoerceList& list) {_coerceListList.add(list);} private: /// \brief The coercion list for all types in this unit CoerceListList _coerceListList; public: // everything related to scope stack struct ScopeCallback { virtual void enteringScope(z::Ast::Scope& scope) = 0; virtual void leavingScope(z::Ast::Scope& scope) = 0; protected: inline ScopeCallback() {} }; public: z::Ast::Scope& enterScope(const z::Ast::Token& pos); z::Ast::Scope& enterScope(z::Ast::Scope& scope); void leaveScope(); void leaveScope(z::Ast::Scope& scope); z::Ast::Scope& currentScope(); const z::Ast::VariableDefn* hasMember(const z::Ast::Scope& scope, const z::Ast::Token& name) const; const z::Ast::VariableDefn* getVariableDef(const z::Ast::Token& name, z::Ast::RefType::T& refType) const; inline void setScopeCallback(ScopeCallback* val) {_scopeCallback = val;} private: ScopeStack _scopeStack; ScopeCallback* _scopeCallback; public: // everything related to struct-init stack inline void pushStructInit(const z::Ast::StructDefn& structDefn) {_structInitStack.push_back(z::ptr(structDefn));} inline void popStructInit() {_structInitStack.pop_back();} inline const z::Ast::StructDefn* structInit() {if(_structInitStack.size() == 0) return 0; return _structInitStack.back();} private: typedef std::list<const z::Ast::StructDefn*> StructInitStack; StructInitStack _structInitStack; public: // everything related to current typespec template <typename T> inline const T* setCurrentRootTypeRef(const size_t& level, const z::Ast::Token& name) { const T& td = getRootTypeSpec<T>(level, name); _currentTypeRef = z::ptr(td); _currentImportedTypeRef = hasImportRootTypeSpec(level, name); return z::ptr(td); } template <typename T> inline const T* setCurrentChildTypeRef(const z::Ast::TypeSpec& parent, const z::Ast::Token& name, const z::string& extype) { if(z::ptr(parent) != _currentTypeRef) { throw z::Exception("Unit", zfmt(name, "Internal error: %{s} parent mismatch '%{t}'") .arg("s", extype) .arg("t", name) ); } const T* td = z::ref(_currentTypeRef).hasChild<const T>(name.string()); if(td) { _currentTypeRef = td; if(_currentImportedTypeRef) { const T* itd = z::ref(_currentImportedTypeRef).hasChild<const T>(name.string()); if(itd) { _currentImportedTypeRef = itd; } else { _currentImportedTypeRef = 0; } } return td; } if(_currentImportedTypeRef) { const T* itd = z::ref(_currentImportedTypeRef).hasChild<const T>(name.string()); if(itd) { _currentImportedTypeRef = 0; _currentTypeRef = itd; return itd; } else { _currentImportedTypeRef = 0; } } throw z::Exception("Unit", zfmt(name, "%{s} type expected '%{t}'").arg("s", extype).arg("t", name)); } template <typename T> inline const T* resetCurrentTypeRef(const T& typeSpec) { _currentTypeRef = 0; return z::ptr(typeSpec); } const z::Ast::TypeSpec* currentTypeRefHasChild(const z::Ast::Token& name) const; private: const z::Ast::TypeSpec* _currentTypeRef; const z::Ast::TypeSpec* _currentImportedTypeRef; public: // everything related to typespec-stack z::Ast::Root& getRootNamespace(const size_t& level); const z::Ast::TypeSpec* hasRootTypeSpec(const size_t& level, const z::Ast::Token& name) const; inline TypeSpecStack& typeSpecStack() {return _typeSpecStack;} inline const TypeSpecStack& typeSpecStack() const {return _typeSpecStack;} public: template <typename T> const T& getRootTypeSpec(const size_t& level, const z::Ast::Token& name) const { const z::Ast::TypeSpec* typeSpec = hasRootTypeSpec(level, name); if(!typeSpec) { throw z::Exception("Unit", zfmt(name, "Unknown root type '%{s}'").arg("s", name )); } // check if type is expected type const T* tTypeSpec = dynamic_cast<const T*>(typeSpec); if(tTypeSpec) { return z::ref(tTypeSpec); } // check if type is a templated type const z::Ast::TemplateDecl* td1 = dynamic_cast<const z::Ast::TemplateDecl*>(typeSpec); if(td1 != 0) { const z::Ast::TypeSpec* innerTypeSpec = z::ptr(z::ref(td1).typeSpec()); const T* tInnerTypeSpec = dynamic_cast<const T*>(innerTypeSpec); if(tInnerTypeSpec != 0) { return z::ref(tInnerTypeSpec); } } throw z::Exception("Unit", zfmt(name, "Type mismatch '%{s}' (%{t})").arg("s", name).arg("t", typeid(*typeSpec).name())); } private: inline const z::Ast::TypeSpec* findTypeSpec(const z::Ast::TypeSpec& parent, const z::Ast::Token& name) const; public: z::Ast::TypeSpec& currentTypeSpec() const; z::Ast::TypeSpec& enterTypeSpec(z::Ast::TypeSpec& typeSpec); z::Ast::TypeSpec& leaveTypeSpec(z::Ast::TypeSpec& typeSpec); z::Ast::StructDefn& getCurrentStructDefn(const z::Ast::Token& pos); z::Ast::InterfaceDefn& getCurrentInterfaceDefn(const z::Ast::Token& pos); private: const z::Ast::TypeSpec* hasImportRootTypeSpec(const size_t& level, const z::Ast::Token& name) const; private: TypeSpecStack _typeSpecStack; public: // everything related to expected typespec struct ExpectedTypeSpec { enum Type { etNone, etAuto, etVarArg, etCallArg, etListVal, etDictKey, etDictVal, etAssignment, etEventHandler, etStructInit }; typedef std::vector<const z::Ast::QualifiedTypeSpec*> List; inline ExpectedTypeSpec(const Type& type, const z::Ast::QualifiedTypeSpec& typeSpec) : _type(type), _typeSpec(typeSpec) {} inline ExpectedTypeSpec(const Type& type) : _type(type) {} inline const Type& type() const {return _type;} inline bool hasTypeSpec() const {return (!_typeSpec.empty());} inline const z::Ast::QualifiedTypeSpec& typeSpec() const {return _typeSpec.get();} private: Type _type; const z::Ast::Ptr<const z::Ast::QualifiedTypeSpec> _typeSpec; }; typedef std::list<ExpectedTypeSpec> ExpectedTypeSpecStack; public: const z::Ast::StructDefn* isStructExpected() const; const z::Ast::Function* isFunctionExpected() const; const z::Ast::TemplateDefn* isPointerExpected() const; const z::Ast::TemplateDefn* isPointerToExprExpected(const z::Ast::Expr& expr) const; const z::Ast::StructDefn* isPointerToStructExpected() const; const z::Ast::StructDefn* isListOfStructExpected() const; const z::Ast::StructDefn* isListOfPointerToStructExpected() const; public: void pushExpectedTypeSpec(const ExpectedTypeSpec::Type& type, const z::Ast::QualifiedTypeSpec& qTypeSpec); void pushExpectedTypeSpec(const ExpectedTypeSpec::Type& type); void popExpectedTypeSpec(const z::Ast::Token& pos, const ExpectedTypeSpec::Type& type); bool popExpectedTypeSpecOrAuto(const z::Ast::Token& pos, const ExpectedTypeSpec::Type& type); const z::Ast::QualifiedTypeSpec* getExpectedTypeSpecIfAny() const; const z::Ast::QualifiedTypeSpec& getExpectedTypeSpec(const z::Ast::Token& pos, const z::Ast::QualifiedTypeSpec* qTypeSpec) const; private: inline z::string getExpectedTypeName(const z::Ast::Token& pos, const ExpectedTypeSpec::Type& exType); inline ExpectedTypeSpec::Type getExpectedType(const z::Ast::Token& pos) const; inline const ExpectedTypeSpec& getExpectedTypeList(const z::Ast::Token& pos) const; inline const z::Ast::QualifiedTypeSpec& getExpectedTypeSpecEx(const z::Ast::Token& pos) const; public: const z::Ast::TemplateDefn* isEnteringList() const; private: inline const z::Ast::TypeSpec* isListOfPointerExpected() const; inline const z::Ast::TemplateDefn* isEnteringTemplate() const; public: void pushCallArgList(const z::Ast::Scope& in); void popCallArgList(const z::Ast::Token& pos, const z::Ast::Scope& in); void popCallArg(const z::Ast::Token& pos); private: ExpectedTypeSpecStack _expectedTypeSpecStack; public: // everything related to function body lists /// \brief Return the function implementation list /// \return The function implementation list inline const BodyList& bodyList() const {return _bodyList;} /// \brief Add a function implementation to the unit /// \param functionDefnBase the function implementation to add inline void addBody(const Body& body) {_bodyList.add(body);} private: /// \brief The list of all function implementations in this unit BodyList _bodyList; public: // owning-list of all nodes template<typename T> inline T& addNode(T* node) {/*_nodeList.push_back(node); */return z::ref(node);} public: // A unique numeric id for anonymous functions /// \brief Return unique id /// \return unique id inline UniqueId_t uniqueIdx() {return ++_uniqueIdx;} private: /// \brief unique id value UniqueId_t _uniqueIdx; public: inline const Ast::ForeachStatement* getForeach() const {if(_foreachStack.size() == 0) return 0; return _foreachStack.top();} inline void enterForeach(const Ast::ForeachStatement& stmt) {_foreachStack.push(z::ptr(stmt));} inline void leaveForeach(const Ast::ForeachStatement& stmt) {assert(_foreachStack.size() > 0); assert(_foreachStack.top() == z::ptr(stmt)); _foreachStack.pop();} private: /// \brief stack of nested foreach statements ForeachStack _foreachStack; }; ////////////////////////////////////////////////////////////////// /*! \brief A module The Module stores all the global statements in the unit. */ class Module { public: typedef size_t Level_t; public: inline Module(Unit& unit, const z::string& filename, const Level_t& level) : _unit(unit), _filename(filename), _level(level) { z::Ast::CompoundStatement& gs = _unit.addNode(new z::Ast::CompoundStatement(Token(_filename, 0, 0, ""))); _globalStatementList.reset(gs); } private: inline Module(const Module& src) : _unit(src._unit), _filename(src._filename), _level(src._level) {} public: /// \brief Return the unit /// \return The unit inline z::Ast::Unit& unit() const {return _unit;} private: /// \brief Unit z::Ast::Unit& _unit; public: inline const z::string& filename() const {return _filename;} private: const z::string _filename; public: inline const Level_t& level() const {return _level;} private: const Level_t _level; public: /// \brief Return the statement list /// \return The statement list inline const CompoundStatement& globalStatementList() const {return _globalStatementList.get();} /// \brief Add a statement to the module /// \param statement the statement to add inline void addGlobalStatement(const Statement& statement) {_globalStatementList.get().addStatement(statement);} /// \brief Clear statement list inline void clearGlobalStatementList() { } private: /// \brief The list of all import statements in this module Ptr<CompoundStatement> _globalStatementList; }; } }
/* * This is the example of safe_ptr object * It has been taken from <https://www.codeproject.com/Articles/1183379/We-make-any-object-thread-safe> * and slightly modified */ #include <iostream> #include <vector> #include <string> #include <map> #include <unordered_map> #include <memory> #include <thread> #include <mutex> #include <numeric> using namespace std; /* Execute around paradigm */ template <typename T, typename mutex_type = std::recursive_mutex> class execute_around { std::shared_ptr<mutex_type> mtx; std::shared_ptr<T> p; void lock() const { mtx->lock(); } void unlock() const { mtx->unlock(); } public: std::shared_ptr<T> get_p() const { return p; } std::shared_ptr<mutex_type> get_mtx() const { return mtx; } public: class proxy { std::unique_lock<mutex_type> lock; T *const p; public: proxy(T * const _p, mutex_type &_mtx) : lock(_mtx), p(_p) { std::cout << "locked\n"; } proxy(proxy &&px) : lock(std::move(px.lock)), p(px.p) {} ~proxy() { std::cout << "unlocked\n"; } T* operator -> () { return p; } const T* operator -> () const { return p; } }; template<typename ...Args> execute_around (Args ... args) : mtx(std::make_shared<mutex_type>()), p(std::make_shared<T>(args...)) {} proxy operator -> () { return proxy(p.get(), *mtx); } const proxy operator->() const { return proxy(p.get(), *mtx); } template<class... mutex_types> friend class std::lock_guard; }; /* Thread-safe container for any type */ template <typename T, typename mutex_t = std::recursive_mutex, typename x_lock_t = std::unique_lock<mutex_t>, typename s_lock_t = std::unique_lock<mutex_t>> class safe_ptr { typedef mutex_t mtx_t; const std::shared_ptr<T> ptr; std::shared_ptr<mutex_t> mtx_ptr; template<typename req_lock> class auto_lock_t { T * const ptr; req_lock lock; public: auto_lock_t(auto_lock_t &&o) : ptr(std::move(o.ptr)), lock(std::move(o.lock)) {} auto_lock_t(T * const _ptr, mutex_t &_mtx) : ptr(_ptr), lock(_mtx) {} T *operator->() { return ptr; } const T* operator->() const { return ptr; } }; template<typename req_lock> class auto_lock_obj_t { T * const ptr; req_lock lock; public: auto_lock_obj_t(auto_lock_obj_t &&o): ptr(std::move(o.ptr)), lock(std::move(o.lock)) {} auto_lock_obj_t(T * const _ptr, mutex_t &_mtx) : ptr(_ptr), lock(_mtx) {} template<typename arg_t> auto operator[](arg_t arg) -> decltype((*ptr)[arg]) { return (*ptr)[arg]; } }; void lock() { mtx_ptr->lock(); } void unlock() { mtx_ptr->unlock(); } friend struct link_safe_ptrs; template<class... mutex_types> friend class std::lock_guard; public: template<typename... Args> safe_ptr(Args... args) : ptr(std::make_shared<T>(args...)), mtx_ptr(std::make_shared<mutex_t>()) {} auto_lock_t<x_lock_t> operator->() { return auto_lock_t<x_lock_t>(ptr.get(), *mtx_ptr); } auto_lock_obj_t<x_lock_t> operator* () { return auto_lock_obj_t<x_lock_t>(ptr.get(), *mtx_ptr); } const auto_lock_t<s_lock_t> operator-> () const { return auto_lock_t<s_lock_t>(ptr.get(), *mtx_ptr); } const auto_lock_obj_t<s_lock_t> operator* () const {return auto_lock_obj_t<s_lock_t>(ptr.get(), *mtx_ptr); } }; safe_ptr<std::map<std::string, std::pair<std::string, int>>> safe_map_strings_global; void func(decltype(safe_map_strings_global) safe_map_strings) { (*safe_map_strings)["apple"].first = "fruit"; (*safe_map_strings)["potato"].first = "vegetable"; for(size_t i = 0; i < 10000; ++i) { safe_map_strings->at("apple").second++; safe_map_strings->find("potato")->second.second++; } auto const readonly_safe_map_string = safe_map_strings; std::cout << "potato is " << readonly_safe_map_string->at("potato").first << " " << readonly_safe_map_string->at("potato").second << ", apple is " << readonly_safe_map_string->at("apple").first << " " << readonly_safe_map_string->at("apple").second << std::endl; } void test_execute_around() { typedef execute_around<std::vector<int>> T; T vecc(10, 10); int res = std::accumulate(vecc->begin(), vecc->end(), 0); std::cout << "1. execute_around::accumulate:res = " << res << std::endl; res = std::accumulate( (vecc.operator ->())->begin(), (vecc.operator ->())->end(), 0); std::cout << "2. execute_around::accumulate:res = " << res << std::endl; res = std::accumulate( T::proxy(vecc.get_p().get(), *vecc.get_mtx())->begin(), T::proxy(vecc.get_p().get(), *vecc.get_mtx())->end(), 0); std::cout << "3. execute_around::accumulate:res = " << res << std::endl; /* Further, according to standard - temporary proxy type objects * will be created before the function starts executing and will be * destroyed after end of the function (after the end of the entire expression) */ T::proxy tmp1(vecc.get_p().get(), *vecc.get_mtx()); //Lock 1 std::recursive_mutex T::proxy tmp2(vecc.get_p().get(), *vecc.get_mtx()); //Lock 2 std::recursive_mutex res = std::accumulate(tmp1->begin(), tmp2->end(), 0); std::cout << "4. execute_around::accumulate:res = " << res << std::endl; tmp2.~proxy(); //unlock 2 std::recursive_mutex tmp1.~proxy(); //unlock 1 std::recursive_mutex } void test_safe_ptr() { std::vector<std::thread> vec_thread(10); for(auto &i : vec_thread) i = std::move(std::thread(func, safe_map_strings_global)); for(auto &i : vec_thread) i.join(); } int main() { typedef void (*test_function)(); std::unordered_map<std::string, test_function> test_table; test_table.insert(std::make_pair("test_execute_around", &test_execute_around)); test_table.insert(std::make_pair("test_safe_ptr", &test_safe_ptr)); int i(1); for(std::unordered_map<std::string, test_function>::const_iterator it = test_table.cbegin(); it != test_table.cend(); ++it) { std::cout << "=== Start test <" << it->first << "> #" << i << " ===" << std::endl; it->second(); ++i; } std::cout << "end"; int b; std::cin >> b; return 0; }
#include <stdio.h> int main() { int value[55]; char str[100][51]; for(int i=0;i<100;i++) scanf("%s",str[i]); for(int i=0;i<55;i++) value[i] = 0; for(int i=0;i<50;i++) { int index = 49-i; int sum = 0; for(int j=0;j<100;j++) { sum += ((int)str[j][index] - 48); } sum += value[i]; sum += (value[i+1]*10); value[i] = sum % 10; value[i+1] = (sum%100) / 10; value[i+2] = sum/100; } for(int i=55;i>=40;i--) printf("%d",value[i]); printf("\n"); }
#include<bits/stdc++.h> using namespace std; bool match_5(string s){ if(s == "ahmed" || s=="shiva") return true; else return false; } bool match_6(string s){ if(s == "rakesh") return true; else return false; } int main(){ int n; string s; cin >> n >> s; int ans = 0; for(int i = 0; i <= n - 5; i++){ if(match_5(s.substr(i, 5))){ i += 4; ans ++; } else if( i + 6 <= n && match_6(s.substr(i, 6))){ i += 5; ans ++; } } cout << ans << "\n"; return 0; }
/* BAEKJOON 3190. 뱀 1) queue를 사용한 것 - 배열을 사용했으면 체크할 때 배열을 모두 순회해야했다 - 시간 체크 -> queue를 사용해서 맨 앞에 것만 체크하고 pop해주었다 - 뱀 -> 꼬리가 먼저 들어오고, 꼬리를 삭제 해주므로 queue를 선택 2) 문제를 제대로 안읽어서 좌표 확인을 잘못한 것 */ #include <iostream> #include <algorithm> #include <queue> #define MAX 101 using namespace std; struct node { int r, c; node(); node(int _r, int _c): r(_r), c(_c) {} }; struct direction { int s; char d; direction(); direction(int _s, char _d): s(_s), d(_d) {} }; int K, N, L; int r, c, s; char d; int map[MAX][MAX] {0}; // 0은 아무것도 없음, 1은 뱀, 2는 사과 queue<node> q_snake; queue<direction> q_dir; // 방향 정보를 배열이 아닌 queue로 사용한 이유 // 배열모두 순회해 보는 것이 아니라 // 맨 앞에 있는 방향 정보의 시간만 체크하면 되니깐 // 그리고 pop(선입 선출)해버리면 되니깐 int dr[4] = {0, 1, 0, -1}; // 우, 하, 좌, 상 int dc[4] = {1, 0, -1, 0}; int main(int argc, char** argv) { cin >> N >> K; // 사과 for(int i=0; i<K; i++){ cin >> r >> c; map[r][c] = 2; } // 방향 전환 정보 cin >> L; for(int i=0; i<L; i++){ cin >> s >> d; q_dir.push(direction(s, d)); } int cnt = 0; int now_dir = 0; // 방향 오른쪽으로 // 뱀의 시작 위치 = (1,1) int nr = 1; int nc = 1; map[nr][nc] = 1; q_snake.push(node(nr,nc)); while(1){ cnt++; nr += dr[now_dir]; nc += dc[now_dir]; // 벽이거나, 뱀이거나 -> 탈출 if(nr < 1 || nc < 1 || nr > N || nc > N || map[nr][nc] == 1) { break; } // 사과가 있으면 그냥 머리 추가 if(map[nr][nc] == 2) { q_snake.push(node(nr,nc)); map[nr][nc] = 1; } // 아무것도 없으면 꼬리 삭제 -> 꼬리 0으로 // 꼬리가 제일 먼저 들어간 node이므로 pop하면 삭제된다 else if(map[nr][nc] == 0) { q_snake.push(node(nr,nc)); map[nr][nc] = 1; map[q_snake.front().r][q_snake.front().c] = 0; q_snake.pop(); } // 방향 변경 if(!q_dir.empty() && cnt == q_dir.front().s){ if(q_dir.front().d == 'D') { // 오른쪽 90도 now_dir = (now_dir+1) % 4; } else if(q_dir.front().d == 'L') { // 왼쪽 90도 if(now_dir == 0){ now_dir = 3; } else { now_dir -= 1; } } // 방향 변경하는 초가 지났으니 pop해준다 q_dir.pop(); } } cout << cnt; return 0; }
#include "as/ScriptContext.hpp" #include <angelscript.h> namespace as { ScriptContext::~ScriptContext() { context->Release(); } int ScriptContext::getId() const { return id; } asIScriptContext* ScriptContext::getRaw() { return context; } const asIScriptContext* ScriptContext::getRaw() const { return context; } ScriptContext::ScriptContext( ScriptEngine& theEngine, asIScriptContext* theContext, int theId ) : engine( theEngine ), context( theContext ), id( theId ) { } }
// // SMImagePickerScene.h // iPet // // Created by KimSteve on 2017. 6. 26.. // Copyright © 2017년 KimSteve. All rights reserved. // #ifndef SMImagePickerScene_h #define SMImagePickerScene_h #include "../../SMFrameWork/Base/SMScene.h" #include "../../SMFrameWork/Util/ImageFetcher.h" #include "../../SMFrameWork/UI/ImagePickerView.h" #include "../../SMFrameWork/UI/CaptureView.h" #include "../../SMFrameWork/Util/ImageDownloader.h" #include "../../SMFrameWork/Util/DownloadProtocol.h" #include <cocos2d.h> class SMPageView; class SMButton; class OnImageSelectedListener { public: virtual void onImageSelected(int callIndex, cocos2d::Sprite *image) = 0; }; class OnQRBarCodeListener { public: virtual void onQRBarCodeResult(std::string result) = 0; }; class SMImagePickerScene : public SMScene, public OnImagePickerListener, public OnCaptureListener, public OnClickListener, public DownloadProtocol { public: enum Mode { // Profile 만들기 1:1 Crop PROFILE_PHOTO, // 일반 Image 선택 IMAGE_SELECT, }; enum StartWith { ALBUM, CAMERA, ALBUM_ONLY, CAMERA_ONLY, EDIT_ONLY, }; static SMImagePickerScene * createForQRBarCode(OnQRBarCodeListener * l=nullptr, Intent* sceneParam=nullptr, int index=-1); static SMImagePickerScene * createForEdit(Mode mode, StartWith startWith, SwipeType type=SwipeType::DISMISS, Intent* sceneProgram=nullptr); static SMImagePickerScene * create(OnImageSelectedListener * l, int index, SwipeType type=SwipeType::DISMISS, Intent* sceneProgram=nullptr); void setQRBarCode(bool enable) {_forQRBarCode=enable;}; void setOnQRBarCodeListener(OnQRBarCodeListener* l) {_qrListener = l;} void closeImagePicker(); virtual void onSceneResult(SMScene* fromScene, Intent* result) override; protected: StartWith getStartWithTypeFromSceneParam(Intent* sceneParam=nullptr); bool canSwipe(const cocos2d::Vec2& worldPoint); bool initWithMode(Mode mode, StartWith startWith); virtual void onClick(SMView* view) override; virtual void finishScene(Intent* result=nullptr) override; // capture view listener virtual void onStillImageCaptured(cocos2d::Sprite * captureImage, float x, float y, const std::string tempUrl) override; virtual void onVideoCaptured(cocos2d::Data* capturedData, std::string tempUrl) override ; virtual void onDetectedScanCode(int type, std::string codeResult) override; // image picker listener virtual void onImageItemClick(SMView * view, const ImageItemInfo& item) override; #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID virtual void onGroupSelect(const ImageGroupInfo* group, bool immediate) override; #else virtual void onGroupSelect(const std::string& name, bool immediate) override; #endif virtual void onGroupSelectViewOpen(bool bOpen) override; virtual void onTransitionStart(const Transition t, const int flag) override; virtual void onTransitionComplete(const Transition t, const int flag) override; virtual void onImageLoadComplete(cocos2d::Sprite* sprite, int tag, bool direct) override; protected: SMImagePickerScene(); virtual ~SMImagePickerScene(); private: cocos2d::Node * cellForRowAtIndexPath(const IndexPath& indexPath); int numberOfRowsInSection(int section); void onPageScroll(float position, float distance); void onPagenChanged(int page); void startProfileCropScene(SMView * view, const std::string& imagePath, int width, int height, int orient, int from); void startImageSelectScene(SMView* view, const std::string& imagePath, int with, int height, int orient, int from); void goImageEditor(cocos2d::Sprite * sendSprite); void goDrawDirect(float t); private: SMView * _topMenuView; SMButton * _closeButton; // close, back, menu from swipe type SMButton * _cameraButton; SMButton * _albumButton; SMButton * _titleButton; SMButton * _groupButton; SMPageView * _pageView; ImagePickerView * _imagePickerView; CaptureView * _captureView; bool _canSwipe; int _currentPage; SMView * _deliverCell; Mode _mode; // for Test SMView * _pageA; SMView * _pageB; StartWith _startWith; OnImageSelectedListener * _listener; bool _forQRBarCode; bool _forPicker; int _callIndex; OnQRBarCodeListener * _qrListener; bool _sendQRBarCodeResult; std::string _strQRCodeResult; std::string _pickerType; bool _needDraw; }; #endif /* SMImagePickerScene_h */
#include <bits/stdc++.h> using namespace std; struct Node { int val; Node *next; Node *back; Node() : val(-1), next(NULL){}; Node(int val) : val(val), next(NULL), back(NULL){}; }; class Queue { private: int _size = 0; Node *head = new Node(), *end = head; public: int size() { return this->_size; } int front() { if (!this->head) return -1; return this->head->val; } int push(int val) { Node *temp = new Node(val); this->end->next = temp; temp->back = this->end; this->end = this->end->next; this->_size++; } int pop_front() { if(!this->head) return -1; int val = this->head->val; this->head = this->head->next; this->_size--; return val; } int pop() { if(!this->end) return -1; int val = this->end->val; this->end = this->end->back; this->_size--; return val; } void clear() { Node *temp = head; while (temp) { temp = temp->next; free(temp); } this->_size = 0; free(this->end); } void push_front(int val) { Node *temp = new Node(val); this->head->back = temp; this->head = temp; this->_size++; } };
#include <node.h> #include <nan.h> #include <cstdlib> #include "get.h" #include "netstat.h" using v8::Array; using v8::Number; using v8::Local; using v8::Object; using v8::String; #define MAC_SIZE 18 #define MAC_TPL "%02x:%02x:%02x:%02x:%02x:%02x" NAN_METHOD(get) { NanScope(); node_netstat_iaddress_t* addresses; node_netstat_iface_t* ifaces; uint i_count, a_count, i, j; char ip[INET6_ADDRSTRLEN]; char netmask[INET6_ADDRSTRLEN]; char mac[MAC_SIZE]; Local<Object> aobj, ifobj; Local<String> family; Local<Array> ret, ifarr; // create return value array ret = NanNew<Array>(); int err = node_netstat_interface_addresses(&ifaces, &addresses, &i_count, &a_count); if (err) { NanReturnValue(ret); } // iterate ifaces for (i = 0; i < i_count; i++) { ifobj = NanNew<Object>(); // prepare mac snprintf(mac, MAC_SIZE, MAC_TPL, static_cast<unsigned char>(ifaces[i].phys_addr[0]), static_cast<unsigned char>(ifaces[i].phys_addr[1]), static_cast<unsigned char>(ifaces[i].phys_addr[2]), static_cast<unsigned char>(ifaces[i].phys_addr[3]), static_cast<unsigned char>(ifaces[i].phys_addr[4]), static_cast<unsigned char>(ifaces[i].phys_addr[5])); ifobj->Set(NanNew<String>("name"), NanNew<String>(ifaces[i].name)); ifobj->Set(NanNew<String>("mac"), NanNew<String>(mac)); ifobj->Set(NanNew<String>("ibytes"), NanNew<Number>(ifaces[i].ibytes)); ifobj->Set(NanNew<String>("obytes"), NanNew<Number>(ifaces[i].obytes)); ifobj->Set(NanNew<String>("internal"), ifaces[i].is_internal ? NanTrue() : NanFalse()); ifarr = NanNew<Array>(); // iterate addresses for (j = 0; j < a_count; j++) { if (strcmp(ifaces[i].name, addresses[j].name) == 0) { aobj = NanNew<Object>(); if (addresses[j].address.address4.sin_family == AF_INET) { uv_ip4_name(&addresses[j].address.address4, ip, sizeof(ip)); uv_ip4_name(&addresses[j].netmask.netmask4, netmask, sizeof(netmask)); family = NanNew<String>("ipv4"); } else if (addresses[j].address.address4.sin_family == AF_INET6) { uv_ip6_name(&addresses[j].address.address6, ip, sizeof(ip)); uv_ip6_name(&addresses[j].netmask.netmask6, netmask, sizeof(netmask)); family = NanNew<String>("ipv6"); } else { strncpy(ip, "<unknown sa family>", INET6_ADDRSTRLEN); family = NanNew<String>("unknown"); } aobj->Set(NanNew<String>("address"), NanNew<String>(ip)); aobj->Set(NanNew<String>("netmask"), NanNew<String>(netmask)); aobj->Set(NanNew<String>("family"), family); ifarr->Set(ifarr->Length(), aobj); } } ifobj->Set(NanNew<String>("addresses"), ifarr); ret->Set(ret->Length(), ifobj); } node_netstat_free_interface_addresses(ifaces, addresses, i_count, a_count); NanReturnValue(ret); }
/************************************************************* * > File Name : P2015_3.cpp * > Author : Tony * > Created Time : 2019/06/18 12:59:16 * > Algorithm : [DP]Tree **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 110; int n, q, dp[maxn][maxn]; struct Edge { int from, to, val; Edge(int u, int v, int w) : from(u), to(v), val(w) {} }; vector<Edge> edges; vector<int> G[maxn]; void add(int u, int v, int w) { edges.push_back(Edge(u, v, w)); edges.push_back(Edge(v, u, w)); int mm = edges.size(); G[v].push_back(mm - 1); G[u].push_back(mm - 2); } void DP(int u, int fa) { for (int i = 0; i < G[u].size(); ++i) { Edge& e = edges[G[u][i]]; if (e.to == fa) continue; DP(e.to, u); for (int j = q; j >= 0; j--) { for (int k = 0; k < j; ++k) { dp[u][j] = max(dp[u][j], dp[e.to][k] + dp[u][j - k - 1] + e.val); } } } } int main() { n = read(); q = read(); for (int i = 1; i < n; ++i) { int u = read(), v = read(), w = read(); add(u, v, w); } DP(1, 0); printf("%d\n", dp[1][q]); return 0; }
#include<iostream> using namespace std; bool ternarySearch(int ar[], int left, int right, int num) { if (left <= right) { int mid1 = left + right/3; int mid2 = mid1 + right/3; if (ar[mid1] == num) return true; if (ar[mid2] == num) return true; if (num < ar[mid1]) return ternarySearch(ar, left, mid1-1, num); if (num > ar[mid2]) return ternarySearch(ar, mid2+1, right, num); return ternarySearch(ar, mid1+1, mid2-1, num); } return false; } int main() { int array_size,num,search_number_in_array; cout<<"Enter the Array size: "; cin>>array_size; int ar[array_size]; cout<<endl<<"Enter the Array Element: "; for(int i=0; i<array_size; i++) { cin>>num; ar[i] = num; } cout<<endl<<"Which number you want to search in the array: "; cin>>search_number_in_array; bool p = ternarySearch(ar,0,array_size-1,search_number_in_array); if(p) cout<<"Your number is found in the array"<<endl; else cout<<"Your number is not in the array"<<endl; return 0; }
#ifndef __TOKEN_H__ #define __TOKEN_H__ #include <string> using namespace std; class Token { public: const int tag; Token(int t) : tag(t) {} virtual string toString(); }; #endif
/************************************************************* * > File Name : P1484.cpp * > Author : Tony * > Created Time : 2019/09/14 15:18:38 * > Algorithm : priority_queue+链表 **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 500010; struct Node { LL val; int id; bool operator < (Node a) const { return val < a.val; } }; LL a[maxn], ans; int l[maxn], r[maxn]; bool valid[maxn]; priority_queue<Node> q; int main() { int n = read(), k = read(); for (int i = 1; i <= n; ++i) { scanf("%lld", &a[i]); q.push((Node){a[i], i}); l[i] = i - 1; r[i] = i + 1; } int len = n; for (int i = 1; i <= k; ++i) { while (!q.empty() && valid[q.top().id]) { q.pop(); } if (q.empty() || q.top().val < 0) { break; } Node top = q.top(); q.pop(); ans += top.val; valid[top.id] = true; valid[l[top.id]] = true; valid[r[top.id]] = true; a[++len] = a[l[top.id]] + a[r[top.id]] - a[top.id]; l[len] = l[l[top.id]]; r[len] = r[r[top.id]]; r[l[len]] = len; l[r[len]] = len; q.push((Node){a[len], len}); } printf("%lld\n", ans); return 0; }
#ifndef TESTS_H #define TESTS_H class XMTestBase { public: static void MasterAction(){ }; static void SlaveAction(){ }; }; void testAll(bool isMaster); extern FILE *logFile; #endif
/*NodeStoreAsync.h NodeStoreAsync copyright Vixac Ltd. All Rights Reserved */ #ifndef INCLUDED_NODESTOREASYNC #define INCLUDED_NODESTOREASYNC #include "Node.h" #include <iostream> #include "AsyncFunctor.h" #include <set> namespace vixac { namespace ina { class NodeGenAsync; // --// class NodeStoreAsync; class NodeHandle; class PhenodeAsync; class NodeAsyncObserver; namespace SortTypes//TODO server needs to understand this enum { enum Type { Update =0, Creation=1, Sequence=2, }; } const int64_t QUANTITY_ALL =0; struct SequenceRequest { SequenceRequest(): isSet_(false), nodeId(0), type(""), quantity(QUANTITY_ALL), // that means all asc(true), skip(0), sort(SortTypes::Creation) {} SequenceRequest(vixac::inout::NodeId nodeId, vixac::inout::TieType type): isSet_(true), nodeId(nodeId), type(type), quantity(QUANTITY_ALL), // that means all asc(true), skip(0), sort(SortTypes::Creation) {} vixac::inout::NodeId nodeId; vixac::inout::TieType type; int64_t quantity; bool asc; int64_t skip; SortTypes::Type sort; bool isSet_; }; } } class vixac::ina::NodeAsyncObserver { public: NodeAsyncObserver():store_(NULL){} void bindToStore(vixac::ina::NodeStoreAsync * store) { store_= store; } virtual void tieGained(TieChange t){std::cout<<"default tie gained called " <<t.tie.type().type <<std::endl;} virtual void tieRemoved(TieChange t){} virtual void tieRecieved(TieChange t){} virtual void stringChanged(StringChange t){} virtual void intChanged(IntChange t){} virtual void nodeIDChanged(NodeIdChange t){} ~NodeAsyncObserver(); private: vixac::ina::NodeStoreAsync * store_; //TODO make weak ptr }; class vixac::ina::NodeStoreAsync { public: friend class PhenodeAsync; friend class NodeAsync; void useThisGenerator(vixac::ina::NodeGenAsync * gen){gen_ = gen;} virtual void newNode(vixac::inout::NodeType, NodeIdFunc f){f(-1);} //i just want to do getNode really. thats the trick. so it has a const state, or soemthing? // ok so the store is used to collect that data. i guess so it needs to be possible to call all that shit. //which then gets wrapped in the construction of the node. but th enode needs to be able to get to its biznis. //the async store hmm. //ok what if getNode reutrned somethng eles. i dont know what. something that knows how to populateitself. thats what i was virtual void addTie(vixac::inout::NodeId, vixac::inout::Tie, DoneFunc f){} virtual void removeTie(vixac::inout::NodeId, vixac::inout::Tie, DoneFunc f){} virtual void injectNode(vixac::inout::Node const& n, DoneFunc f){} //TODO consider a variant. consider moving over to Meta. virtual void setStringMeta( vixac::inout::NodeId, std::string const& key, std::string const& value, DoneFunc f){} virtual void setIntMeta(vixac::inout::NodeId, std::string const& key, int64_t value, DoneFunc f){} virtual void setFloatMeta(vixac::inout::NodeId, std::string const& key, double value, DoneFunc f){} virtual void getStringMeta(vixac::inout::NodeId, std::string const& key, StringFunc f){} virtual void getFloatMeta(vixac::inout::NodeId, std::string const& key, FloatFunc f){} virtual void getIntMeta(vixac::inout::NodeId, std::string const& key, IntFunc f){} //ok if i write here get getMeta, and getMetaVec. then i can use a string to request phenetic crap. virtual void getPrimary(vixac::inout::NodeId, vixac::inout::TieType type, NodeIdFunc f){} virtual void getActiveTies(vixac::inout::NodeId, vixac::inout::TieType type, NodeIdVecFunc f){}//takes a node and fin //virtual void getBulkMeta(NodeIdVec const& vec, std::vector<std::string> const& fieldVec, MetaVecFunc f){} virtual void phenGetMeta(const PhenodeAsync * phen, std::string const& phenCall, KeyMetaMap const& data, MetaVecFunc f){} virtual void phenGetTies(const PhenodeAsync * phen, std::string const& phenCall, KeyMetaMap const& data, NodeIdVecFunc f){} virtual void phenDo(const PhenodeAsync * phen, std::string const& phenCall, KeyMetaMap const& data, BoolFunc f){} //the sequence request is used for the fields of asc, quantity, sort, and skip. //i could change the api to be a vector of sequenceReqeusts. apart frmo the node field, that would make a whole lot more sense. THat way i expose //sorting and whatnot down the request, which is really cool, and i basically have that for free the way ive implemented it in eve. virtual void getNqlMeta(NodeIdVec const& vec, std::vector<vixac::inout::TieType> const& walkVec, std::vector<std::string> const& fieldVec, SequenceRequest, MetaVecFunc f){} //TODO ad these to local node store? I guess. Also why use ties if i am goign to use sequences. // its just ties, but a different table. // virtual void getSequence(vixac::inout::NodeId nodeId, vixac::inout::TieType seqName,int64_t quantity, bool asc, int64_t skip, NodeIdVecFunc f){} //TODO what tod o with getsequence? virtual void getSequence(SequenceRequest, NodeIdVecFunc f){} virtual void incSequence(vixac::inout::NodeId nodeId, vixac::inout::NodeId target, vixac::inout::TieType seqName, int64_t inc, bool additive, DoneFunc f){} void subscribeToNode(vixac::inout::NodeId, NodeAsyncObserver * obs ); void unsubToNode(vixac::inout::NodeId, NodeAsyncObserver * obs ); void unsub(NodeAsyncObserver * obs); //TODO this is a fat interface. when this gets called , the obsevers are notified. This is the way that a proxy store NOTIFIIES this async store. // its a shame thta this is puiblic. I'd like to have it as its own class or something. // so you can say postman = store->postman; //then i can say serverconnection.usethispostman(postman). //postman is a friend to nodestoreasync, and can privately call tieGained and whatnot. //very clever. thanks. void tieGained(TieChange t); void tieRemoved(TieChange t); void stringChanged(StringChange t); void intChanged(IntChange t); void nodeIdChanged(NodeIdChange t); //used by the phenode Api, the client Id is the person who is making the calls. This is how eventually the api will return different results based on whos asking. vixac::inout::NodeId clientId() const {return clientId_;} void setClientId(vixac::inout::NodeId nodeId) {clientId_ = nodeId;} protected: //implement these if you need to some extra work to ensure that the subscription actually does anything. virtual void handleSubscriptionToNode(vixac::inout::NodeId, NodeAsyncObserver * obs){}; virtual void handleUnsubToNode(vixac::inout::NodeId, NodeAsyncObserver * obs){}; //TODO make private? Its only protected for a gtest std::map<vixac::inout::NodeId, std::set<NodeAsyncObserver *> > observers_; private: vixac::inout::NodeId clientId_; void tieRecieved(TieChange t); std::set<NodeAsyncObserver *> observersForNodeId(vixac::inout::NodeId nodeId); vixac::ina::NodeGenAsync * gen_; }; #endif
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 556 - Amazing */ #include <iostream> #include <sstream> #include <vector> #include <string> #include <algorithm> #include <iomanip> using namespace std; int main() { typedef struct DELTA_POS { DELTA_POS(int nDeltaRow, int nDeltaColumn) : nDeltaRow(nDeltaRow), nDeltaColumn(nDeltaColumn) {} int nDeltaRow, nDeltaColumn; } DELTA_POS_TYPE; vector<DELTA_POS_TYPE> oVecDeltas; oVecDeltas.push_back(DELTA_POS(+0, +1)); oVecDeltas.push_back(DELTA_POS(-1, +0)); oVecDeltas.push_back(DELTA_POS(+0, -1)); oVecDeltas.push_back(DELTA_POS(+1, +0)); while (true) { string oLine; getline(cin, oLine); stringstream oStringStream(oLine); int nR, nC; oStringStream >> nR >> nC; if (!nR && !nC) break; vector<string> oVecMap; oVecMap.push_back(""); for (int nLoopRow = 0; nLoopRow < nR; nLoopRow++) { getline(cin, oLine); replace(oLine.begin(), oLine.end(), '1', 'x'); oLine = 'x' + oLine + 'x'; oVecMap.push_back(oLine); } oVecMap.push_back(""); for (int nLoopColumn = 0; nLoopColumn <= nC + 1; nLoopColumn++) { oVecMap[0] = oVecMap[0] + 'x'; oVecMap[nR + 1] = oVecMap[nR + 1] + 'x'; } int nCurrentRow = nR, nCurrentCol = 1, nCurrentDir = 0; // oVecMap[nCurrentRow][nCurrentCol]++; do { int nDirNorm = (oVecDeltas.size() + nCurrentDir - 1) % oVecDeltas.size(); int nRowRight = nCurrentRow + oVecDeltas[nDirNorm].nDeltaRow, nColumnRight = nCurrentCol + oVecDeltas[nDirNorm].nDeltaColumn; int nNewRow, nNewColumn, nNewDir = nCurrentDir; if (oVecMap[nRowRight][nColumnRight] != 'x') { nNewRow = nCurrentRow + oVecDeltas[nDirNorm].nDeltaRow; nNewColumn = nCurrentCol + oVecDeltas[nDirNorm].nDeltaColumn; nNewDir = nDirNorm; } else { do { nNewRow = nCurrentRow + oVecDeltas[nNewDir].nDeltaRow; nNewColumn = nCurrentCol + oVecDeltas[nNewDir].nDeltaColumn; if (oVecMap[nNewRow][nNewColumn] == 'x') nNewDir = (nNewDir + 1) % oVecDeltas.size(); else break; } while (true); } oVecMap[nNewRow][nNewColumn]++; nCurrentRow = nNewRow; nCurrentCol = nNewColumn; nCurrentDir = nNewDir; } while (nCurrentRow != nR || nCurrentCol != 1); vector<int> oVecSol(5); for (int nLoopRow = 1; nLoopRow <= nR; nLoopRow++) for (int nLoopColumn = 1; nLoopColumn <= nC; nLoopColumn++) if (oVecMap[nLoopRow][nLoopColumn] != 'x') oVecSol[oVecMap[nLoopRow][nLoopColumn] - '0']++; cout << setw(3) << oVecSol[0] << setw(3) << oVecSol[1] << setw(3) << oVecSol[2] << setw(3) << oVecSol[3] << setw(3) << oVecSol[4] << endl; } return 0; }
#include "StdAfx.h" #include "RResource.h" #include "AThread.h" #include "BDrawLinePass.h" #include "BLineBatcher.h" #include "BViewport.h" #include "BDriver.h" BDrawLinePass::BDrawLinePass() { } BDrawLinePass::~BDrawLinePass() { } void BDrawLinePass::DrawPrimitive(BLineBatcher* LineBatcher) { size_t NumLines = LineBatcher->Lines.Size(); if (NumLines > 0) { struct VD { TVector3 Pos; }; VD *Vertices = new VD[(NumLines * 2)]; for (unsigned int i = 0; i < NumLines; ++i) { Vertices[i * 2 + 0].Pos = LineBatcher->Lines(i).Point1; Vertices[i * 2 + 1].Pos = LineBatcher->Lines(i).Point2; } GDriver->DrawPrimitiveUP(PrimitiveType_LineList, (unsigned int) (NumLines), Vertices, sizeof(VD)); delete Vertices; } }
#include <iostream> #include <opencv2/opencv.hpp> #include <fstream> #include "darknet.h" using namespace std; using namespace cv; void imgConvert(const cv::Mat &img, float *dst); void imgResize(float *src, float *dst, int srcWidth, int srcHeight, int dstWidth, int dstHeight); void resizeInner(float *src, float *dst, int srcWidth, int srcHeight, int dstWidth, int dstHeight); float colors[6][3] = {{1, 0, 1}, {0, 0, 1}, {0, 1, 1}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}}; float get_color(int c, int x, int max) { float ratio = ((float) x / max) * 5; int i = floor(ratio); int j = ceil(ratio); ratio -= i; float r = (1 - ratio) * colors[i][c] + ratio * colors[j][c]; return r; } void imgConvert(const cv::Mat &img, float *dst) { uchar *data = img.data; int h = img.rows; int w = img.cols; int c = img.channels(); for (int k = 0; k < c; ++k) { for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { dst[k * w * h + i * w + j] = data[(i * w + j) * c + k] / 255.; } } } } void imgResize(float *src, float *dst, int srcWidth, int srcHeight, int dstWidth, int dstHeight) { int new_w = srcWidth; int new_h = srcHeight; if (((float) dstWidth / srcWidth) < ((float) dstHeight / srcHeight)) { new_w = dstWidth; new_h = (srcHeight * dstWidth) / srcWidth; } else { new_h = dstHeight; new_w = (srcWidth * dstHeight) / srcHeight; } float *ImgReInner; size_t sizeInner = new_w * new_h * 3 * sizeof(float); ImgReInner = (float *) malloc(sizeInner); resizeInner(src, ImgReInner, srcWidth, srcHeight, new_w, new_h); for (int i = 0; i < dstWidth * dstHeight * 3; i++) { dst[i] = 0.5; } for (int k = 0; k < 3; ++k) { for (int y = 0; y < new_h; ++y) { for (int x = 0; x < new_w; ++x) { float val = ImgReInner[k * new_w * new_h + y * new_w + x]; dst[k * dstHeight * dstWidth + ((dstHeight - new_h) / 2 + y) * dstWidth + (dstWidth - new_w) / 2 + x] = val; } } } free(ImgReInner); } void resizeInner(float *src, float *dst, int srcWidth, int srcHeight, int dstWidth, int dstHeight) { float *part; size_t sizePa = dstWidth * srcHeight * 3 * sizeof(float); part = (float *) malloc(sizePa); float w_scale = (float) (srcWidth - 1) / (dstWidth - 1); float h_scale = (float) (srcHeight - 1) / (dstHeight - 1); for (int k = 0; k < 3; ++k) { for (int r = 0; r < srcHeight; ++r) { for (int c = 0; c < dstWidth; ++c) { float val = 0; if (c == dstWidth - 1 || srcWidth == 1) { val = src[k * srcWidth * srcHeight + r * srcWidth + srcWidth - 1]; } else { float sx = c * w_scale; int ix = (int) sx; float dx = sx - ix; val = (1 - dx) * src[k * srcWidth * srcHeight + r * srcWidth + ix] + dx * src[k * srcWidth * srcHeight + r * srcWidth + ix + 1]; } part[k * srcHeight * dstWidth + r * dstWidth + c] = val; } } } for (int k = 0; k < 3; ++k) { for (int r = 0; r < dstHeight; ++r) { float sy = r * h_scale; int iy = (int) sy; float dy = sy - iy; for (int c = 0; c < dstWidth; ++c) { float val = (1 - dy) * part[k * dstWidth * srcHeight + iy * dstWidth + c]; dst[k * dstWidth * dstHeight + r * dstWidth + c] = val; } if (r == dstHeight - 1 || srcHeight == 1) continue; for (int c = 0; c < dstWidth; ++c) { float val = dy * part[k * dstWidth * srcHeight + (iy + 1) * dstWidth + c]; dst[k * dstWidth * dstHeight + r * dstWidth + c] += val; } } } free(part); } int main() { // yolo *y = new yolo(); // y->init(); // y->pullImg(); // y->getRes(); string cfgfile = "/home/dean/dean.test/darknet/cfg/yolov3.cfg";//读取模型文件,请自行修改相应路径 string weightfile = "/home/dean/dean.test/darknet/yolov3.weights"; float thresh = 0.5;//参数设置 float nms = 0.35; int classes = 80; network *net = load_network((char *) cfgfile.c_str(), (char *) weightfile.c_str(), 0);//加载网络模型 set_batch_network(net, 1); VideoCapture capture(0);//读取视频,请自行修改相应路径 Mat frame; Mat rgbImg; vector<string> classNamesVec; ifstream classNamesFile("/home/dean/dean.test/darknet/data/coco.names");//标签文件coco有80类 if (classNamesFile.is_open()) { string className = ""; while (getline(classNamesFile, className)) classNamesVec.push_back(className); } bool stop = false; while (!stop) { if (!capture.read(frame)) { printf("fail to read.\n"); return 0; } cvtColor(frame, rgbImg, cv::COLOR_BGR2RGB); float *srcImg; size_t srcSize = rgbImg.rows * rgbImg.cols * 3 * sizeof(float); srcImg = (float *) malloc(srcSize); imgConvert(rgbImg, srcImg);//将图像转为yolo形式 float *resizeImg; size_t resizeSize = net->w * net->h * 3 * sizeof(float); resizeImg = (float *) malloc(resizeSize); imgResize(srcImg, resizeImg, frame.cols, frame.rows, net->w, net->h);//缩放图像 network_predict(net, resizeImg);//网络推理 int nboxes = 0; detection *dets = get_network_boxes(net, rgbImg.cols, rgbImg.rows, thresh, 0.5, 0, 1, &nboxes); if (nms) { do_nms_sort(dets, nboxes, classes, nms); } vector<cv::Rect> boxes; boxes.clear(); vector<int> classNames; for (int i = 0; i < nboxes; i++) { bool flag = 0; int className; for (int j = 0; j < classes; j++) { if (dets[i].prob[j] > thresh) { if (!flag) { flag = 1; className = j; } } } if (flag) { int left = (dets[i].bbox.x - dets[i].bbox.w / 2.) * frame.cols; int right = (dets[i].bbox.x + dets[i].bbox.w / 2.) * frame.cols; int top = (dets[i].bbox.y - dets[i].bbox.h / 2.) * frame.rows; int bot = (dets[i].bbox.y + dets[i].bbox.h / 2.) * frame.rows; if (left < 0) left = 0; if (right > frame.cols - 1) right = frame.cols - 1; if (top < 0) top = 0; if (bot > frame.rows - 1) bot = frame.rows - 1; Rect box(left, top, fabs(left - right), fabs(top - bot)); boxes.push_back(box); classNames.push_back(className); } } free_detections(dets, nboxes); for (int i = 0; i < boxes.size(); i++) { int offset = classNames[i] * 123457 % 80; float red = 255 * get_color(2, offset, 80); float green = 255 * get_color(1, offset, 80); float blue = 255 * get_color(0, offset, 80); rectangle(frame, boxes[i], Scalar(blue, green, red), 2); String label = String(classNamesVec[classNames[i]]); int baseLine = 0; Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); putText(frame, label, Point(boxes[i].x, boxes[i].y + labelSize.height), FONT_HERSHEY_SIMPLEX, 1, Scalar(red, blue, green), 2); } imshow("video", frame); int c = waitKey(30); if ((char) c == 27) break; else if (c >= 0) waitKey(0); free(srcImg); free(resizeImg); } free_network(net); capture.release(); return 0; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CompareHdf5ResultsFiles.hpp" #include <iostream> #include <vector> #include "DistributedVectorFactory.hpp" #include "Hdf5DataReader.hpp" #include "petscvec.h" bool CompareFilesViaHdf5DataReader(std::string pathname1, std::string filename1, bool makeAbsolute1, std::string pathname2, std::string filename2, bool makeAbsolute2, double tol, std::string datasetName) { Hdf5DataReader reader1(pathname1, filename1, makeAbsolute1, datasetName); Hdf5DataReader reader2(pathname2, filename2, makeAbsolute2, datasetName); unsigned number_nodes1 = reader1.GetNumberOfRows(); unsigned number_nodes2 = reader2.GetNumberOfRows(); if (number_nodes1 != number_nodes2) { std::cout << "Number of nodes " << number_nodes1 << " and " << number_nodes2 << " don't match\n"; return false; } // Check the variable names and units std::vector<std::string> variable_names1 = reader1.GetVariableNames(); std::vector<std::string> variable_names2 = reader2.GetVariableNames(); std::string unlimited_variable1 = reader1.GetUnlimitedDimensionName(); std::string unlimited_variable2 = reader2.GetUnlimitedDimensionName(); std::string unlimited_variable_unit1 = reader1.GetUnlimitedDimensionUnit(); std::string unlimited_variable_unit2 = reader2.GetUnlimitedDimensionUnit(); unsigned num_vars = variable_names1.size(); if (num_vars != variable_names2.size()) { std::cout << "Number of variables " << variable_names1.size() << " and " << variable_names2.size() << " don't match\n"; return false; } if (unlimited_variable1 != unlimited_variable2) { std::cout << "Unlimited variable names " << unlimited_variable1 << " and " << unlimited_variable2 << " don't match\n"; return false; } if (unlimited_variable_unit1 != unlimited_variable_unit2) { std::cout << "Unlimited variable units " << unlimited_variable_unit1 << " and " << unlimited_variable_unit2 << " don't match\n"; return false; } for (unsigned var = 0; var < num_vars; var++) { std::string var_name = variable_names1[var]; if (var_name != variable_names2[var]) { std::cout << "Variable names " << var_name << " and " << variable_names2[var] << " don't match\n"; return false; } if (reader1.GetUnit(var_name) != reader2.GetUnit(var_name)) { std::cout << "Units names " << reader1.GetUnit(var_name) << " and " << reader2.GetUnit(var_name) << " don't match\n"; return false; } } // Check the timestep vectors std::vector<double> times1 = reader1.GetUnlimitedDimensionValues(); std::vector<double> times2 = reader2.GetUnlimitedDimensionValues(); if (times1.size() != times2.size()) { std::cout << "Number of time steps " << times1.size() << " and " << times2.size() << " don't match\n"; return false; } for (unsigned timestep = 0; timestep < times1.size(); timestep++) { ///\todo remove magic number? (#1884) if (fabs(times1[timestep] - times2[timestep]) > 1e-8) { std::cout << "Time step " << timestep << " doesn't match. First file says " << times1[timestep] << " and second says " << times2[timestep] << std::endl; return false; } } bool is_complete1 = reader1.IsDataComplete(); bool is_complete2 = reader2.IsDataComplete(); if (is_complete1 != is_complete2) { std::cout << "One of the readers has incomplete data and the other doesn't\n"; return false; } if (is_complete1) { DistributedVectorFactory factory(number_nodes1); Vec data1 = factory.CreateVec(); Vec data2 = factory.CreateVec(); for (unsigned timestep = 0; timestep < times1.size(); timestep++) { for (unsigned var = 0; var < num_vars; var++) { reader1.GetVariableOverNodes(data1, variable_names1[var], timestep); reader2.GetVariableOverNodes(data2, variable_names2[var], timestep); #if (PETSC_VERSION_MAJOR == 2 && PETSC_VERSION_MINOR == 2) //PETSc 2.2 double minus_one = -1.0; VecAXPY(&minus_one, data2, data1); #else //[note: VecAXPY(y,a,x) computes y = ax+y] VecAXPY(data1, -1.0, data2); #endif PetscReal difference_norm; VecNorm(data1, NORM_2, &difference_norm); if (difference_norm > tol) { std::cout << "Time " << times1[timestep] << ": vectors differ in NORM_2 by " << difference_norm << std::endl; return false; } } } PetscTools::Destroy(data1); PetscTools::Destroy(data2); } else { // Incomplete data // Check the index vectors std::vector<unsigned> indices1 = reader1.GetIncompleteNodeMap(); std::vector<unsigned> indices2 = reader2.GetIncompleteNodeMap(); if (indices1.size() != indices2.size()) { std::cout << "Index map sizes " << indices1.size() << " and " << indices2.size() << " don't match\n"; return false; } for (unsigned index = 0; index < indices1.size(); index++) { if (indices1[index] != indices2[index]) { std::cout << "Node indices " << indices1[index] << " and " << indices2[index] << " don't match\n"; return false; } } // Check all the data for (unsigned index = 0; index < indices1.size(); index++) { unsigned node_index = indices1[index]; for (unsigned var = 0; var < num_vars; var++) { std::vector<double> var_over_time1 = reader1.GetVariableOverTime(variable_names1[var], node_index); std::vector<double> var_over_time2 = reader2.GetVariableOverTime(variable_names1[var], node_index); for (unsigned time_step = 0; time_step < var_over_time1.size(); time_step++) { if (fabs(var_over_time1[time_step] - var_over_time2[time_step]) > tol) { std::cout << "Node " << node_index << " at time step " << time_step << " variable " << variable_names1[var] << " differs (" << var_over_time1[time_step] << " != " << var_over_time2[time_step] << ")" << std::endl; return false; } } } } } return true; } bool CompareFilesViaHdf5DataReaderGlobalNorm(std::string pathname1, std::string filename1, bool makeAbsolute1, std::string pathname2, std::string filename2, bool makeAbsolute2, double tol, std::string datasetName) { Hdf5DataReader reader1(pathname1, filename1, makeAbsolute1, datasetName); Hdf5DataReader reader2(pathname2, filename2, makeAbsolute2, datasetName); unsigned number_nodes1 = reader1.GetNumberOfRows(); bool is_the_same = true; std::vector<std::string> variable_names1 = reader1.GetVariableNames(); std::vector<std::string> variable_names2 = reader2.GetVariableNames(); std::vector<double> times1 = reader1.GetUnlimitedDimensionValues(); unsigned num_vars = variable_names1.size(); DistributedVectorFactory factory(number_nodes1); Vec data1 = factory.CreateVec(); Vec data2 = factory.CreateVec(); for (unsigned timestep = 0; timestep < times1.size(); timestep++) { for (unsigned var = 0; var < num_vars; var++) { reader1.GetVariableOverNodes(data1, variable_names1[var], timestep); reader2.GetVariableOverNodes(data2, variable_names2[var], timestep); PetscReal data1_norm; PetscReal data2_norm; VecNorm(data1, NORM_2, &data1_norm); VecNorm(data2, NORM_2, &data2_norm); PetscReal norm = fabs(data1_norm - data2_norm); if (norm > tol) { is_the_same = false; std::cout << "Vectors differ in global NORM_2 by " << norm << std::endl; } } } PetscTools::Destroy(data1); PetscTools::Destroy(data2); return is_the_same; }
// Copyright [2014] <lgb (LiuGuangBao)> //===================================================================================== // // Filename: proc.hpp // // Description: Linux proc 文件系统 // // Version: 1.0 // Created: 2013年12月26日 14时49分23秒 // Revision: none // Compiler: gcc // // Author: lgb (LiuGuangBao), easyeagel@gmx.com // Organization: ezbty.org // //===================================================================================== #ifndef PPSH_PROC_HPP #define PPSH_PROC_HPP #include<ctime> #include<string> #include<vector> namespace ppsh { typedef ::pid_t PID_t; class ProcessInfo { public: ProcessInfo()=default; ProcessInfo(PID_t pid) :pid_(pid) {} PID_t pidGet() const { return pid_; } const std::string& cmdGet() const { return cmd_; } std::time_t startTimeGet() const { return startTime_; } bool refresh(); static ProcessInfo cmdInfoRead(const std::string& cmd); bool empty() const { return pid_==0; } private: PID_t pid_=0; std::string cmd_; std::time_t startTime_; }; class SysProc { public: void refresh(); const ProcessInfo* find(const std::string& name) const; private: std::vector<ProcessInfo> proc_; }; } #endif //PPSH_PROC_HPP
// Tap_Proxy.cpp : 구현 파일입니다. // #include "stdafx.h" #include "NSS Ver 1.1.h" #include "Tap_Proxy.h" #include "afxdialogex.h" // Tap_Proxy 대화 상자입니다. IMPLEMENT_DYNAMIC(Tap_Proxy, CDialogEx) Tap_Proxy::Tap_Proxy(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_Proxy, pParent) { } Tap_Proxy::~Tap_Proxy() { } void Tap_Proxy::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB1, Proxy_Option); LPCTSTR tap1 = _T("HTTP"); LPCTSTR tap2 = _T("HTTPS"); Proxy_Option.InsertItem(1, tap1); Proxy_Option.InsertItem(1, tap2); } BEGIN_MESSAGE_MAP(Tap_Proxy, CDialogEx) END_MESSAGE_MAP() // Tap_Proxy 메시지 처리기입니다.
// conversion status: type and call issues resolved, algorithm adaptation to coloredAmounts still needs work. // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Copyright (c) 2013+ The Coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php #include "wallet.h" #include "base58.h" #include "coincontrol.h" #include "net.h" #include <inttypes.h> #include <boost/algorithm/string/replace.hpp> #include <openssl/rand.h> using namespace std; ////////////////////////////////////////////////////////////////////////////// // // mapWallet // struct CompareValueOnly { bool operator()(const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t1, const pair<int64_t, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; // FIXME, There is a problem here in that coloredAmounts are multivalent. IE, a coloredAmount may hold various amounts of various different // coins so that it's not entirely certain how to sort them. If A has only mixcoins and B has only shekels, then neither of them is "less" // than the other, so either sort order is ... right for some reasons and wrong for others. We probably need to restructure things - if we // assume that each txout contains only one kind of coin, then we could sort on one color, pick txouts for that color, sort on another // color, pick txouts for that color, etc. Or we could sort on two keys; first by color and then by amount. But both of those plans create // problems when an individual txout may contain multiple different coin colors -- it makes them incomparable again under the second scheme, // and introduces unwanted "noise" in the first because selected txouts may have colors not wanted in the transaction as well as colors // wanted. // We should probably filter first so we don't 'see' coins that have colors the TargetValue does not have. In most cases that will fix the // problem because the targetvalue is very likely to be denominated in exactly one color and the majority of txouts will also be denominated // in one color. But it's not a very general solution. struct CompareCaValueOnly { bool operator()(const pair<coloredAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<coloredAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; CPubKey CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey) { if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta) { if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::Unlock(const SecureString& strWalletPassphrase) { CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))) / 2); if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a private-key-encrypted wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))) / 2); if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb) { int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; if (txin.prevout.n >= wtx.vout.size()) LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str()); else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { LogPrintf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCaCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { unsigned int latestNow = wtx.nTimeReceived; unsigned int latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry *const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime; wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString().c_str(), wtxIn.hashBlock.ToString().c_str()); } } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if ( !strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } void CWallet::SyncTransaction(const uint256 &hash, const CTransaction& tx, const CBlock* pblock) { AddToWalletIfInvolvingMe(hash, tx, pblock, true); } // remove a tx from the wallet. void CWallet::EraseFromWallet(const uint256 &hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } // determine whether a txin is mine or not. Iterates recursively over the tx whose hash matches, to verify the existence of a txin whose // ... size? ... matches. bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } coloredAmount CWallet::GetCaDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].caValue; } } return 0; } // FIXME: It's not entirely clear that handling change specially is a good idea. Anyway, we certainly ought not leave any evidence of which // txout is change in the blockchain. This is used to group change with "sender" info, and also used in a couple of places to avoid // displaying change. All calls are within this file. bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; // TODO: fix handling of 'change' outputs. The assumption is that any payment to a TX_PUBKEYHASH that is mine but isn't in the address // book is change. That assumption is likely to break when we implement multisignature wallets that return change back into a // multi-signature-protected address; a better way of identifying which outputs are 'the send' and which are 'the change' will need to // be implemented (maybe extend CWalletTx to remember which output, if any, was change). if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } // GetAmounts is called with strSentAccount set. It finds the account and fills the two lists with the address and amounts of the txOuts // spent and created, respectively. It also records the transaction fee in caFee. void CWalletTx::GetAmounts(list<pair<CTxDestination, coloredAmount> >& listReceived, list<pair<CTxDestination, coloredAmount> >& listSent, coloredAmount& caFee, string& strSentAccount) const { caFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: coloredAmount caDebit = GetCaDebit(); if (caDebit.anygreaterthan(0)) { // debit>0 means we signed/sent this transaction coloredAmount caValueOut = GetCaValueOut(); caFee = caDebit - caValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { bool fIsMine; // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (caDebit.anygreaterthan(0)) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; fIsMine = pwallet->IsMine(txout); } else if (!(fIsMine = pwallet->IsMine(txout))) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); address = CNoDestination(); } // If we are debited by the transaction, add the output as a "sent" entry if (caDebit > 0) listSent.push_back(make_pair(address, txout.caValue)); // If we are receiving the output, add it as a "received" entry if (fIsMine) listReceived.push_back(make_pair(address, txout.caValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, coloredAmount& caReceived, coloredAmount& caSent, coloredAmount& caFee) const { caReceived = caSent = caFee = coloredAmount(0); coloredAmount allFee; string strSentAccount; list<pair<CTxDestination, coloredAmount> > listReceived; list<pair<CTxDestination, coloredAmount> > listSent; // GetAmounts sets listRecieved, listSent, and allFee GetAmounts(listReceived, listSent, allFee, strSentAccount); if (strAccount == strSentAccount) { // add the amount of each element in the sent list to the caSent total. BOOST_FOREACH(const PAIRTYPE(CTxDestination,coloredAmount)& s, listSent) caSent += s.second; caFee = allFee; } { LOCK(pwallet->cs_wallet); // for every amount in the recieved list, ... // if pwallet contains the corresponding address, OR the corresponding address has no balance, then add the amount to the received total. BOOST_FOREACH(const PAIRTYPE(CTxDestination,coloredAmount)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) caReceived += r.second; } else if (strAccount.empty()) { caReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions() { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::AcceptWalletTransaction() { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash)) tx.AcceptToMemoryPool(false); } } return AcceptToMemoryPool(false); } return false; } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) if (nTimeFirstKey && (pindex->nTime < (nTimeFirstKey - 7200))) { pindex = chainActive.Next(pindex); continue; } CBlock block; ReadBlockFromDisk(block, pindex); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); } } return ret; } void CWallet::ReacceptWalletTransactions() { bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; bool fMissing = false; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if (wtx.IsCoinBase() && wtx.IsSpent(0)) continue; CCoins coins; bool fUpdated = false; bool fFound = pcoinsTip->GetCoins(wtx.GetHash(), coins); if (fFound || wtx.GetDepthInMainChain() > 0) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat for (unsigned int i = 0; i < wtx.vout.size(); i++) { if (wtx.IsSpent(i)) continue; if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; fMissing = true; } } if (fUpdated) { LogPrintf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney((wtx.GetCaCredit())).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Re-accept any txes of ours that aren't already in a block if (!wtx.IsCoinBase()) wtx.AcceptWalletTransaction(); } } if (fMissing) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(chainActive.Genesis())) fRepeat = true; // Found missing transactions: re-do re-accept. } } } void CWalletTx::RelayWalletTransaction() { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) if (tx.GetDepthInMainChain() == 0) RelayTransaction((CTransaction)tx, tx.GetHash()); } if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); LogPrintf("Relaying wtx %s\n", hash.ToString().c_str()); RelayTransaction((CTransaction)*this, hash); } } } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // coloredAmount CWallet::GetCaBalance() const { coloredAmount caTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsConfirmed()) caTotal += pcoin->GetAvailableCaCredit(); } } return caTotal; } coloredAmount CWallet::GetUnconfirmedCaBalance() const { coloredAmount caTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || !pcoin->IsConfirmed()) caTotal += pcoin->GetAvailableCaCredit(); } } return caTotal; } coloredAmount CWallet::GetImmatureCaBalance() const { coloredAmount caTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; caTotal += pcoin->GetImmatureCaCredit(); } } return caTotal; } // populate vCoins with vector of spendable COutputs void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const { vCoins.clear(); { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && !IsLockedCoin((*it).first, i) && pcoin->vout[i].caValue > 0 && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain())); } } } } // FIXME, In order to avoid linking transactions more than is needful, this should never spend just part of the coinage at a particular address. // Then again, that flaw is irrelevant if I can fix it so addresses are never reused in the first place. // FIXME, algorithm needs to be revised because of multivalent amounts. static void ApproximateBestSubset(vector<pair<coloredAmount, pair<const CWalletTx*, unsigned int> > >vValue, coloredAmount caTotalLower, coloredAmount caTargetValue, vector<char>& vfBest, coloredAmount& caBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); caBest = caTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && caBest != caTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); coloredAmount caTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i]) { caTotal += vValue[i].first; vfIncluded[i] = true; if (caTotal >= caTargetValue) { fReachedTarget = true; if (caTotal < caBest) { caBest = caTotal; vfBest = vfIncluded; } caTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // attempts to find the set of txouts having at least nConfTheirs confirmations that sums to the smallest amount greater than the targetvalue. // nconfmine is always 0 or 1, and 1 in every case except looking for zero-confirm tokens. // There is some randomization code in here but it has no effect unless there are multiple txouts with exactly the same value. bool CWallet::SelectCoinsMinConf(coloredAmount caTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, coloredAmount& caValueRet) const { setCoinsRet.clear(); caValueRet = 0; // List of values less than target pair<coloredAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger; // FIXME, creates a value with MAX of type zero, which is not "greater" than a value containing any positive amount of something else. But we // need to figure out what "somethings else" we need to care about from the caTargetValue. coinLowestLarger.first = coloredAmount(std::numeric_limits<int64_t>::max()); coinLowestLarger.second.first = NULL; vector<pair<coloredAmount, pair<const CWalletTx*,unsigned int> > > vValue; coloredAmount caTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; int i = output.i; coloredAmount n = pcoin->vout[i].caValue; pair<coloredAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); if (n == caTargetValue) { setCoinsRet.insert(coin.second); caValueRet += coin.first; return true; } else if (n < caTargetValue + caCENT) { vValue.push_back(coin); caTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (caTotalLower == caTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); caValueRet += vValue[i].first; } return true; } if (caTotalLower < caTargetValue) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.insert(coinLowestLarger.second); caValueRet += coinLowestLarger.first; return true; } // Solve subset sum by stochastic approximation. // FIXME, this sort fails on coloredAmounts containing multiple coin colors -- they are incomparable, one of them is "less" in one // color, and the other is "less" in the other color. Either way, CompareCaValueOnly will return false. sort(vValue.rbegin(), vValue.rend(), CompareCaValueOnly()); vector<char> vfBest; coloredAmount caBest; ApproximateBestSubset(vValue, caTotalLower, caTargetValue, vfBest, caBest, 1000); if (caBest != caTargetValue && caTotalLower >= caTargetValue + caCENT) ApproximateBestSubset(vValue, caTotalLower, caTargetValue + caCENT, vfBest, caBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((caBest != caTargetValue && caBest < caTargetValue + caCENT) || coinLowestLarger.first <= caBest)) { setCoinsRet.insert(coinLowestLarger.second); caValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); caValueRet += vValue[i].first; } LogPrint("selectcoins", "SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first).c_str()); LogPrint("selectcoins", "total %s\n", FormatMoney(caBest).c_str()); } return true; } // Coin control allows user to designate txouts to spend in a particular transaction. If coin control is in use and those txouts are // insufficient to match the target amount, this returns false. If coin control is in use and the txouts are sufficient, returns true. // Otherwise (coin control is not in use) it tries SelectCoinsMinConf three times to try and get a set of txouts that will work. Results are // returned via caValueRet (the total amount of the selected txouts) and setCoinsRet (the set of selected txouts). bool CWallet::SelectCoins(coloredAmount caTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, coloredAmount& caValueRet, const CCoinControl* coinControl) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { caValueRet += out.tx->vout[out.i].caValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (caValueRet >= caTargetValue); } return (SelectCoinsMinConf(caTargetValue, 1, 6, vCoins, setCoinsRet, caValueRet) || // looks for txouts that have at least 6 confirms. If it doesn't find them... SelectCoinsMinConf(caTargetValue, 1, 1, vCoins, setCoinsRet, caValueRet) || // looks for txouts that have at least 1 confirm. And if it doesn't find that.... SelectCoinsMinConf(caTargetValue, 0, 1, vCoins, setCoinsRet, caValueRet)); // it looks for unconfirmed txouts. } bool CWallet::CreateTransaction(const vector<pair<CScript, coloredAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, coloredAmount& caFeeRet, std::string& strFailReason, const CCoinControl* coinControl) { coloredAmount caValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, coloredAmount)& s, vecSend) { if (caValue.anylessthan(0)) { strFailReason = _("Transaction amounts must be positive"); return false; } caValue += s.second; } if (vecSend.empty() || caValue.anylessthan(0)) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); { caFeeRet = caTransactionFee; while (true) { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; coloredAmount caTotalValue = caValue + caFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, coloredAmount)& s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(CTransaction::caMinRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } wtxNew.vout.push_back(txout); } // Choose coins to use set<pair<const CWalletTx*,unsigned int> > setCoins; coloredAmount caValueIn = 0; if (!SelectCoins(caTotalValue, setCoins, caValueIn, coinControl)) { strFailReason = _("Insufficient funds"); return false; } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { coloredAmount caCredit = pcoin.first->vout[pcoin.second].caValue; //The priority after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //FIXME, we have to find a better way to calculate priority on coloredAmounts. dPriority += (double)(caCredit.amountOf(0)) * (pcoin.first->GetDepthInMainChain()+1); } coloredAmount caChange = caValueIn - caValue - caFeeRet; // The following if statement should be removed once enough miners // have upgraded to the 0.9 GetMinFee() rules. Until then, this avoids // creating free transactions that have change outputs less than // caCENT. if (caFeeRet < CTransaction::caMinTxFee && caChange > 0 && caChange < caCENT) { coloredAmount caMoveToFee = min(caChange, CTransaction::caMinTxFee - caFeeRet); caChange -= caMoveToFee; caFeeRet += caMoveToFee; } if (caChange.anygreaterthan(0)) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-coin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange.SetDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange.SetDestination(vchPubKey.GetID()); } CTxOut newTxOut(caChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(CTransaction::caMinRelayTxFee)) { caFeeRet += caChange; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()+1); wtxNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Check that enough fee is included coloredAmount caPayFee = caTransactionFee * (1 + (int64_t)nBytes / 1000); bool fAllowFree = AllowFree(dPriority); coloredAmount caMinFee = GetMinFee(wtxNew, nBytes, fAllowFree, GMF_SEND).amountOf(0); if (caFeeRet < max(caPayFee, caMinFee)) { if (caPayFee > caMinFee) caFeeRet = caPayFee; caFeeRet = caMinFee; continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, coloredAmount caValue, CWalletTx& wtxNew, CReserveKey& reservekey, coloredAmount& caFeeRet, std::string& strFailReason, const CCoinControl *coinControl) { vector< pair<CScript, coloredAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, caValue)); return CreateTransaction(vecSend, wtxNew, reservekey, caFeeRet, strFailReason, coinControl); } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } return true; } string CWallet::SendMoney(CScript scriptPubKey, coloredAmount caValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); coloredAmount caFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SendMoney() : %s", strError.c_str()); return strError; } string strError; if (!CreateTransaction(scriptPubKey, caValue, wtxNew, reservekey, caFeeRequired, strError)) { if ((caValue + caFeeRequired).anygreaterthan(GetCaBalance())) { strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(caFeeRequired).c_str()); } LogPrintf("SendMoney() : %s\n", strError.c_str()); return strError; } if (fAskFee && !uiInterface.ThreadSafeAskFee(caFeeRequired)) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); return ""; } string CWallet::SendMoneyToDestination(const CTxDestination &address, coloredAmount caValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (caValue <= 0) return _("Invalid amount"); if (caValue + caTransactionFee > GetCaBalance()) return _("Insufficient funds"); // Parse Coin address CScript scriptPubKey; scriptPubKey.SetDestination(address); return SendMoney(scriptPubKey, caValue, wtxNew, fAskFee); } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); return DB_LOAD_OK; } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) { std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), mapAddressBook[address].purpose, (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CCoinAddress(address).ToString(), strPurpose)) return false; return CWalletDB(strWalletFile).WriteName(CCoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) { mapAddressBook.erase(address); NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), "", CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CCoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CCoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %" PRId64 " new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %" PRId64 ", size=%" PRIszu "\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %" PRId64 "\n", nIndex); } } int64_t CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64_t nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %" PRId64 "\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %" PRId64 "\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, coloredAmount> CWallet::GetAddressCaBalances() { map<CTxDestination, coloredAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsConfirmed()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe() ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; coloredAmount n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].caValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set< set<CTxDestination> > CWallet::GetAddressGroupings() { set< set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx *pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH(CTxIn txin, pcoin->vin) { CTxDestination address; if(!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH(CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if(!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it BOOST_FOREACH(set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set< set<CTxDestination>* > hits; map< CTxDestination, set<CTxDestination>* >::iterator it; BOOST_FOREACH(CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH(set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH(CTxDestination element, *merged) setmap[element] = merged; } set< set<CTxDestination> > ret; BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } // Return the given address if it has a zero balance; // create and return a new balance whenever the given balance has a nonzero balance. // this is to prevent the client from defaulting to the reuse of addresses. // referred to from: This file, rpcwallet.cpp, rpcserver.cpp, contrib/coind/bash-completion, // contrib/debian-manpages/coind.1, crontrib/bitrpc.py, qt/paymentserver.cpp. set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { set<CTxDestination> result; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { if (pwallet->vchDefaultKey.IsValid()) { LogPrintf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!"); vchPubKey = pwallet->vchDefaultKey; } else return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } void CWallet::UpdatedTransaction(const uint256 &hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) NotifyTransactionChanged(this, hashTx, CT_UPDATED); } } void CWallet::LockCoin(COutPoint& output) { setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const { mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH(const CKeyID &keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx &wtx = (*it).second; std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH(const CTxOut &txout, wtx.vout) { // iterate over all their outputs ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected); BOOST_FOREACH(const CKeyID &keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) //FIXME, this is ridiculous mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off }
#pragma once #include <cstdint> #include <random> #define JSON_DUMP_SPACES (2) #define JSON_FILE_IMPORT_KEY ("_file_") // comment out to use dynamic names //#define STATIC_DB_NAME (":memory:") //#define STATIC_DB_LOG_NAME ("sqlitedb.log") #define PI (3.14159265359) #define ONE_MiB (1048576.0) //2^20 #define ONE_GiB (1073741824.0) // 2^30 #define BYTES_TO_GiB(x) ((x) / ONE_GiB) #define GiB_TO_BYTES(x) ((x) * ONE_GiB) #define SECONDS_PER_DAY (86400.0) // 60 * 60 * 24 #define SECONDS_PER_MONTH (SECONDS_PER_DAY * 30.0) #define SECONDS_TO_MONTHS(x) ((x)/SECONDS_PER_MONTH) #define DAYS_TO_SECONDS(x) ((x) * SECONDS_PER_DAY) typedef std::minstd_rand RNGEngineType; typedef std::uint64_t TickType; typedef std::uint64_t IdType; inline IdType GetNewId() { static IdType id = 0; return ++id; }
#pragma once #include <algorithm> #include <functional> #include <mutex> #include <stdexcept> #include <vector> #include <dsnutil/singleton.h> namespace dsn { namespace event { /// \brief Queue implementation for broadcast channels /// /// This template provides the facilities to register/unregister handlers for \p Tmessage type /// broadcast events as well as sending a broadcast to all currently registered handler objects /// that implement the corresponding \a broadcast_handler templated interface. /// /// \internal This shouldn't be used directly since the Singleton API is painful. Use the /// simplified interface that is provided through \a broadcast_channel instead. /// /// \see broadcast_channel /// \see broadcast_handler template <typename Tmessage> class channel_queue : public dsn::Singleton<channel_queue<Tmessage> > { friend class dsn::Singleton<channel_queue<Tmessage> >; private: channel_queue() = default; /// \brief Type alias for handler functions /// /// \internal This is used internally since we wrap each templated call to a handler in /// a lambda and then put that into \a m_handlers using handler_type = std::function<void(const Tmessage&)>; /// \brief Type alias for mutex /// /// This is used to alias the mutex implementation for synchronizing access to the handler /// queue. using mutex_type = std::mutex; /// \brief Type alias for scoped mutex lock /// /// This is used to alias a scoped mutex lock for \a mutex_type. using scoped_lock = std::lock_guard<mutex_type>; /// \brief Mutex for queue access /// /// This is used to synchronize access to the handler queue from different threads. /// /// \note This needs to be mutable since we require mutex locking in \p const methods too. mutable mutex_type m_mutex; /// \brief Event handlers /// /// This contains the auto-generated lambdas which invoke a registered event handler. std::vector<handler_type> m_handlers; /// \brief Pointers to registered handler objects /// /// This contains pointers to all currently registered \a broadcast_handler objects std::vector<void*> m_original_pointers; public: template <typename Thandler> void add_handler(Thandler* handler); template <typename Thandler> void remove_handler(Thandler* handler); void clear_handlers(); size_t num_handlers() const; void broadcast(const Tmessage& message); }; /// \brief Add handler to channel /// /// This adds a handler object of type \p Th to the channel queue for events of type \p Tm. /// /// \param handler Pointer to the handler that shall be called on \p Tm events /// /// \tparam Tm Event's message type /// \tparam Th Handler object's type /// /// \throw std::runtime_error if the user tries to register the same handler multiple times template <typename Tm> template <typename Th> void channel_queue<Tm>::add_handler(Th* handler) { scoped_lock guard(m_mutex); auto it = std::find(m_original_pointers.begin(), m_original_pointers.end(), handler); if (it != m_original_pointers.end()) { throw std::invalid_argument("Tried to add the same handler object multiple times!"); } m_handlers.push_back([handler](const Tm& message) { (*handler)(message); }); m_original_pointers.push_back(handler); } /// \brief Remove handler form channel /// /// This removes a handler object of type \p Th from the channel queue for events of type \p Tm. /// /// \param handler Pointer to the handler that shall be removed from the queue for \p Tm broadcasts. /// /// \tparam Tm Event's message type /// \tparam Th Handler object's type template <typename Tm> template <typename Th> void channel_queue<Tm>::remove_handler(Th* handler) { scoped_lock guard(m_mutex); auto it = std::find(m_original_pointers.begin(), m_original_pointers.end(), handler); if (it == m_original_pointers.end()) { throw std::invalid_argument("Tried to remove a handler object that wasn't registered!"); } auto index = it - std::begin(m_original_pointers); m_handlers.erase(m_handlers.begin() + index); m_original_pointers.erase(it); } /// \brief Clear all handlers for a given message type /// /// Removes all handlers currently installed for \p Tm type broadcasts. template <typename Tm> void channel_queue<Tm>::clear_handlers() { scoped_lock guard(m_mutex); m_handlers.clear(); m_original_pointers.clear(); } /// \brief Get numbers of handlers for a given message type /// /// \return Number of handlers currently installed for \p Tm type broadcasts template <typename Tm> size_t channel_queue<Tm>::num_handlers() const { scoped_lock guard(m_mutex); return m_handlers.size(); } /// \brief Broadcast message to all registered handlers /// /// Broadcasts a \p Tm type \a message to all handlers currently registered. /// /// \note This works with a copy of \p m_handlers and allows modifications to the handler list from /// other threads while handlers are being executed in the current one. Any changes made by the /// executed handlers will be in effect starting with the next call to this method and not corrupt /// the list for the current call. template <typename Tm> void channel_queue<Tm>::broadcast(const Tm& message) { // create thread-local copy of active handlers so our queue can be changed while // we execute them without missing a currently installed handler std::vector<handler_type> handlers; { scoped_lock guard(m_mutex); handlers.reserve(m_handlers.size()); handlers = m_handlers; } // execute all installed handlers for (auto& handler : handlers) { handler(message); } } } }
// SPDX-License-Identifier: LGPL-2.1 /* * Copyright (C) 2017 VMware Inc, Yordan Karadzhov <ykaradzhov@vmware.com> */ /** * @file KsSession.cpp * @brief KernelShark Session. */ // KernelShark #include "libkshark.h" #include "libkshark-tepdata.h" #include "KsSession.hpp" #include "KsMainWindow.hpp" /** Create a KsSession object. */ KsSession::KsSession() { _config = kshark_session_config_new(KS_CONFIG_JSON); } /** Destroy a KsSession object. */ KsSession::~KsSession() { kshark_free_config_doc(_config); } /** Import a user session from a Json file. */ bool KsSession::importFromFile(QString jfileName) { kshark_config_doc *configTmp = kshark_open_config_file(jfileName.toStdString().c_str(), "kshark.config.session"); if (configTmp) { kshark_free_config_doc(_config); _config = configTmp; return true; } return false; } /** Export the current user session from a Json file. */ void KsSession::exportToFile(QString jfileName) { kshark_save_config_file(jfileName.toStdString().c_str(), _config); } /** * @brief Save the state of the visualization model. * * @param histo: Input location for the model descriptor. */ void KsSession::saveVisModel(kshark_trace_histo *histo) { kshark_config_doc *model = kshark_export_model(histo, KS_CONFIG_JSON); kshark_config_doc_add(_config, "Model", model); } /** * @brief Load the state of the visualization model. * * @param model: Input location for the KsGraphModel object. */ void KsSession::loadVisModel(KsGraphModel *model) { kshark_config_doc *modelConf = kshark_config_alloc(KS_CONFIG_JSON); if (!kshark_config_doc_get(_config, "Model", modelConf)) return; kshark_import_model(model->histo(), modelConf); model->update(); } /** Save the trace data file. */ void KsSession::saveDataFile(QString fileName, QString dataSetName) { kshark_config_doc *file = kshark_export_trace_file(fileName.toStdString().c_str(), dataSetName.toStdString().c_str(), KS_CONFIG_JSON); kshark_config_doc_add(_config, "Data", file); } /** Get the trace data file. */ QString KsSession::getDataFile(kshark_context *kshark_ctx) { kshark_config_doc *file = kshark_config_alloc(KS_CONFIG_JSON); int sd; if (!kshark_config_doc_get(_config, "Data", file)) return QString(); sd = kshark_import_trace_file(kshark_ctx, file); if (sd) return QString(kshark_ctx->stream[sd]->file); return QString(); } /** * @brief Save the configuration of the filters to file. * * @param kshark_ctx: Input location for context pointer. */ void KsSession::saveFilters(kshark_context *kshark_ctx, const QString &fileName) { kshark_config_doc *conf(nullptr); kshark_export_all_dstreams(kshark_ctx, &conf); kshark_save_config_file(fileName.toStdString().c_str(), conf); kshark_free_config_doc(conf); } /** * @brief Load the configuration of the filters and filter the data. * * @param kshark_ctx: Input location for context pointer. * @param data: Input location for KsDataStore object; */ void KsSession::loadFilters(kshark_context *kshark_ctx, const QString &fileName, KsDataStore *data) { json_object *jconf, *jall_stream, *jstream, *jdata, *jfile, *jfilters; kshark_config_doc *conf = kshark_open_config_file(fileName.toStdString().c_str(), "kshark.config.filter"); int n, sd, *streamIds = kshark_all_streams(kshark_ctx); bool doReload(false); if (!conf) return; if (conf->format != KS_CONFIG_JSON) return; jconf = KS_JSON_CAST(conf->conf_doc); if (!json_object_object_get_ex(jconf, "data streams", &jall_stream)) return; if (json_object_get_type(jall_stream) != json_type_array) return; n = json_object_array_length(jall_stream); for (int i = 0; i < kshark_ctx->n_streams; ++i) { sd = streamIds[i]; for (int j = 0; j < n; ++j) { char abs_path[FILENAME_MAX]; const char *file; jstream = json_object_array_get_idx(jall_stream, j); json_object_object_get_ex(jstream, "data", &jdata); json_object_object_get_ex(jdata, "file", &jfile); file = json_object_get_string(jfile); if (!realpath(kshark_ctx->stream[sd]->file, abs_path)) continue; if (strcmp(file, abs_path) == 0) { json_object_object_get_ex(jstream, "filters", &jfilters); kshark_config_doc *filters = kshark_json_to_conf(jfilters); kshark_import_all_filters(kshark_ctx, sd, filters); kshark_free_config_doc(filters); } } if (kshark_ctx->stream[sd]->format == KS_TEP_DATA && kshark_tep_filter_is_set(kshark_ctx->stream[sd])) doReload = true; } free(streamIds); if (doReload) data->reload(); else data->update(); emit data->updateWidgets(data); } /** * @brief Save the configuration information for all load Data streams. * * @param kshark_ctx: Input location for context pointer. */ void KsSession::saveDataStreams(kshark_context *kshark_ctx) { kshark_export_all_dstreams(kshark_ctx, &_config); } /** * @brief Load Data streams. * * @param kshark_ctx: Input location for context pointer. * @param data: Input location for KsDataStore object; * @param plugins: Input location for KsPluginManager object; */ void KsSession::loadDataStreams(kshark_context *kshark_ctx, KsDataStore *data) { ssize_t dataSize; data->unregisterCPUCollections(); dataSize = kshark_import_all_dstreams(kshark_ctx, _config, data->rows_r()); if (dataSize < 0) { data->clear(); return; } data->setSize(dataSize); data->registerCPUCollections(); } /** * @brief Save the state of the table. * * @param view: Input location for the KsTraceViewer widget. */ void KsSession::saveTable(const KsTraceViewer &view) { kshark_config_doc *topRow = kshark_config_alloc(KS_CONFIG_JSON); int64_t r = view.getTopRow(); topRow->conf_doc = json_object_new_int64(r); kshark_config_doc_add(_config, "ViewTop", topRow); } /** * @brief Load the state of the table. * * @param view: Input location for the KsTraceViewer widget. */ void KsSession::loadTable(KsTraceViewer *view) { kshark_config_doc *topRow = kshark_config_alloc(KS_CONFIG_JSON); size_t r = 0; if (!kshark_config_doc_get(_config, "ViewTop", topRow)) return; if (_config->format == KS_CONFIG_JSON) r = json_object_get_int64(KS_JSON_CAST(topRow->conf_doc)); view->setTopRow(r); } /** * @brief Save the KernelShark Main window size. * * @param window: Input location for the KsMainWindow widget. */ void KsSession::saveMainWindowSize(const QMainWindow &window) { kshark_config_doc *windowConf = kshark_config_alloc(KS_CONFIG_JSON); int width = window.width(), height = window.height(); json_object *jwindow; if (window.isFullScreen()) { jwindow = json_object_new_string("FullScreen"); } else { jwindow = json_object_new_array(); json_object_array_put_idx(jwindow, 0, json_object_new_int(width)); json_object_array_put_idx(jwindow, 1, json_object_new_int(height)); } windowConf->conf_doc = jwindow; kshark_config_doc_add(_config, "MainWindow", windowConf); } /** * @brief Load the KernelShark Main window size. * * @param window: Input location for the KsMainWindow widget. */ void KsSession::loadMainWindowSize(KsMainWindow *window) { kshark_config_doc *windowConf = kshark_config_alloc(KS_CONFIG_JSON); json_object *jwindow, *jwidth, *jheight; int width, height; if (!kshark_config_doc_get(_config, "MainWindow", windowConf)) return; if (_config->format == KS_CONFIG_JSON) { jwindow = KS_JSON_CAST(windowConf->conf_doc); if (json_object_get_type(jwindow) == json_type_string && QString(json_object_get_string(jwindow)) == "FullScreen") { window->setFullScreenMode(true); return; } jwidth = json_object_array_get_idx(jwindow, 0); jheight = json_object_array_get_idx(jwindow, 1); width = json_object_get_int(jwidth); height = json_object_get_int(jheight); window->setFullScreenMode(false); window->resize(width, height); } } /** * @brief Save the state of the Main window spliter. * * @param splitter: Input location for the splitter widget. */ void KsSession::saveSplitterSize(const QSplitter &splitter) { kshark_config_doc *spl = kshark_config_alloc(KS_CONFIG_JSON); json_object *jspl = json_object_new_array(); QList<int> sizes = splitter.sizes(); json_object_array_put_idx(jspl, 0, json_object_new_int(sizes[0])); json_object_array_put_idx(jspl, 1, json_object_new_int(sizes[1])); spl->conf_doc = jspl; kshark_config_doc_add(_config, "Splitter", spl); } /** * @brief Load the state of the Main window spliter. * * @param splitter: Input location for the splitter widget. */ void KsSession::loadSplitterSize(QSplitter *splitter) { kshark_config_doc *spl = kshark_config_alloc(KS_CONFIG_JSON); json_object *jspl, *jgraphsize, *jviewsize; int graphSize(1), viewSize(1); QList<int> sizes; if (!kshark_config_doc_get(_config, "Splitter", spl)) return; if (_config->format == KS_CONFIG_JSON) { jspl = KS_JSON_CAST(spl->conf_doc); jgraphsize = json_object_array_get_idx(jspl, 0); jviewsize = json_object_array_get_idx(jspl, 1); graphSize = json_object_get_int(jgraphsize); viewSize = json_object_get_int(jviewsize); if (graphSize == 0 && viewSize == 0) { /* 0/0 spliter ratio is undefined. Make it 1/1. */ viewSize = graphSize = 1; } } sizes << graphSize << viewSize; splitter->setSizes(sizes); } /** @brief Save the Color scheme used. */ void KsSession::saveColorScheme() { kshark_config_doc *colSch = kshark_config_alloc(KS_CONFIG_JSON); double s = KsPlot::Color::getRainbowFrequency(); colSch->conf_doc = json_object_new_double(s); kshark_config_doc_add(_config, "ColorScheme", colSch); } /** @brief Get the Color scheme used. */ float KsSession::getColorScheme() { kshark_config_doc *colSch = kshark_config_alloc(KS_CONFIG_JSON); /* Default color scheme. */ float s = 0.75; if (!kshark_config_doc_get(_config, "ColorScheme", colSch)) return s; if (_config->format == KS_CONFIG_JSON) s = json_object_get_double(KS_JSON_CAST(colSch->conf_doc)); return s; } /** * @brief Save the list of the graphs plotted. * * @param kshark_ctx: Input location for context pointer. * @param graphs: Input location for the KsTraceGraph widget.. */ void KsSession::saveGraphs(kshark_context *kshark_ctx, KsTraceGraph &graphs) { int *streamIds = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) { _saveCPUPlots(streamIds[i], graphs.glPtr()); _saveTaskPlots(streamIds[i], graphs.glPtr()); } free(streamIds); _saveComboPlots(graphs.glPtr()); } /** * @brief Load the list of the graphs and plot. * * @param kshark_ctx: Input location for context pointer. * @param graphs: Input location for the KsTraceGraph widget. */ void KsSession::loadGraphs(kshark_context *kshark_ctx, KsTraceGraph &graphs) { int nCombos, sd, *streamIds = kshark_all_streams(kshark_ctx); QVector<int> combos; for (int i = 0; i < kshark_ctx->n_streams; ++i) { sd = streamIds[i]; graphs.cpuReDraw(sd, _getCPUPlots(sd)); graphs.taskReDraw(sd, _getTaskPlots(sd)); } free(streamIds); combos = _getComboPlots(&nCombos); if (nCombos > 0) graphs.comboReDraw(nCombos, combos); } void KsSession::_savePlots(int sd, KsGLWidget *glw, bool cpu) { kshark_config_doc *streamsConf = kshark_config_alloc(KS_CONFIG_JSON); json_object *jallStreams, *jstream, *jstreamId, *jplots; QVector<int> plotIds; int nStreams; if (cpu) { plotIds = glw->_streamPlots[sd]._cpuList; } else { plotIds = glw->_streamPlots[sd]._taskList; } if (!kshark_config_doc_get(_config, "data streams", streamsConf) || streamsConf->format != KS_CONFIG_JSON) return; jallStreams = KS_JSON_CAST(streamsConf->conf_doc); if (json_object_get_type(jallStreams) != json_type_array) return; nStreams = json_object_array_length(jallStreams); for (int i = 0; i < nStreams; ++i) { jstream = json_object_array_get_idx(jallStreams, i); if (json_object_object_get_ex(jstream, "stream id", &jstreamId) && json_object_get_int(jstreamId) == sd) break; jstream = nullptr; } free(streamsConf); if (!jstream) return; jplots = json_object_new_array(); for (int i = 0; i < plotIds.count(); ++i) { json_object *jcpu = json_object_new_int(plotIds[i]); json_object_array_put_idx(jplots, i, jcpu); } if (cpu) json_object_object_add(jstream, "CPUPlots", jplots); else json_object_object_add(jstream, "TaskPlots", jplots); } void KsSession::_saveCPUPlots(int sd, KsGLWidget *glw) { _savePlots(sd, glw, true); } void KsSession::_saveTaskPlots(int sd, KsGLWidget *glw) { _savePlots(sd, glw, false); } void KsSession::_saveComboPlots(KsGLWidget *glw) { kshark_config_doc *combos = kshark_config_alloc(KS_CONFIG_JSON); json_object *jcombos, *jplots, *jplt; int var; jcombos = json_object_new_array(); for (auto const &c: glw->_comboPlots) { jplots = json_object_new_array(); for (auto const &p: c) { jplt = json_object_new_array(); var = p._streamId; json_object_array_put_idx(jplt, 0, json_object_new_int(var)); var = p._type; json_object_array_put_idx(jplt, 1, json_object_new_int(var)); var = p._id; json_object_array_put_idx(jplt, 2, json_object_new_int(var)); json_object_array_add(jplots, jplt); } json_object_array_add(jcombos, jplots); } combos->conf_doc = jcombos; kshark_config_doc_add(_config, "ComboPlots", combos); } QVector<int> KsSession::_getPlots(int sd, bool cpu) { kshark_config_doc *streamsConf = kshark_config_alloc(KS_CONFIG_JSON); json_object *jallStreams, *jstream, *jstreamId, *jplots; int nStreams, nPlots, id; const char *plotKey; QVector<int> plots; if (!kshark_config_doc_get(_config, "data streams", streamsConf) || streamsConf->format != KS_CONFIG_JSON) return plots; jallStreams = KS_JSON_CAST(streamsConf->conf_doc); if (json_object_get_type(jallStreams) != json_type_array) return plots; nStreams = json_object_array_length(jallStreams); for (int i = 0; i < nStreams; ++i) { jstream = json_object_array_get_idx(jallStreams, i); if (json_object_object_get_ex(jstream, "stream id", &jstreamId) && json_object_get_int(jstreamId) == sd) break; jstream = nullptr; } if (!jstream) return plots; if (cpu) plotKey = "CPUPlots"; else plotKey = "TaskPlots"; if (!json_object_object_get_ex(jstream, plotKey, &jplots) || json_object_get_type(jplots) != json_type_array) return plots; nPlots = json_object_array_length(jplots); for (int i = 0; i < nPlots; ++i) { id = json_object_get_int(json_object_array_get_idx(jplots, i)); plots.append(id); } return plots; } QVector<int> KsSession::_getCPUPlots(int sd) { return _getPlots(sd, true); } QVector<int> KsSession::_getTaskPlots(int sd) { return _getPlots(sd, false); } QVector<int> KsSession::_getComboPlots(int *n) { kshark_config_doc *combos = kshark_config_alloc(KS_CONFIG_JSON); int nCombos, nPlots, sd, type, id; json_object *jcombos, *jplots, *jplt, *jvar; QVector<int> vec; *n = 0; if (!kshark_config_doc_get(_config, "ComboPlots", combos)) return {}; if (_config->format == KS_CONFIG_JSON) { jcombos = KS_JSON_CAST(combos->conf_doc); if (json_object_get_type(jcombos) != json_type_array) return {}; *n = nCombos = json_object_array_length(jcombos); for (int i = 0; i < nCombos; ++i) { jplots = json_object_array_get_idx(jcombos, i); if (json_object_get_type(jplots) != json_type_array) return {}; nPlots = json_object_array_length(jplots); vec.append(nPlots); for (int j = 0; j < nPlots; ++j) { jplt = json_object_array_get_idx(jplots, j); if (json_object_get_type(jplt) != json_type_array) return {}; jvar = json_object_array_get_idx(jplt, 0); sd = json_object_get_int(jvar); jvar = json_object_array_get_idx(jplt, 1); type = json_object_get_int(jvar); jvar = json_object_array_get_idx(jplt, 2); id = json_object_get_int(jvar); vec.append({sd, type, id}); } } } return vec; } /** * @brief Save the state of the Dual marker. * * @param dm: Input location for the KsDualMarkerSM object. */ void KsSession::saveDualMarker(KsDualMarkerSM *dm) { kshark_config_doc *markers = kshark_config_new("kshark.config.markers", KS_CONFIG_JSON); json_object *jd_mark = KS_JSON_CAST(markers->conf_doc); auto save_mark = [&jd_mark] (KsGraphMark *m, const char *name) { json_object *jmark = json_object_new_object(); if (m->_isSet) { json_object_object_add(jmark, "isSet", json_object_new_boolean(true)); json_object_object_add(jmark, "row", json_object_new_int(m->_pos)); } else { json_object_object_add(jmark, "isSet", json_object_new_boolean(false)); } json_object_object_add(jd_mark, name, jmark); }; save_mark(&dm->markerA(), "markA"); save_mark(&dm->markerB(), "markB"); if (dm->getState() == DualMarkerState::A) json_object_object_add(jd_mark, "Active", json_object_new_string("A")); else json_object_object_add(jd_mark, "Active", json_object_new_string("B")); kshark_config_doc_add(_config, "Markers", markers); } /** * @brief Load the state of the Dual marker. * * @param dm: Input location for the KsDualMarkerSM object. * @param graphs: Input location for the KsTraceGraph widget. */ void KsSession::loadDualMarker(KsDualMarkerSM *dm, KsTraceGraph *graphs) { uint64_t pos; dm->reset(); dm->setState(DualMarkerState::A); if (_getMarker("markA", &pos)) { graphs->markEntry(pos); } else { dm->markerA().remove(); } dm->setState(DualMarkerState::B); if (_getMarker("markB", &pos)) { graphs->markEntry(pos); } else { dm->markerB().remove(); } dm->setState(_getMarkerState()); if (dm->activeMarker()._isSet) { pos = dm->activeMarker()._pos; emit graphs->glPtr()->updateView(pos, true); } } json_object *KsSession::_getMarkerJson() { kshark_config_doc *markers = kshark_config_alloc(KS_CONFIG_JSON); if (!kshark_config_doc_get(_config, "Markers", markers) || !kshark_type_check(markers, "kshark.config.markers")) return nullptr; return KS_JSON_CAST(markers->conf_doc); } bool KsSession::_getMarker(const char* name, size_t *pos) { json_object *jd_mark, *jmark; *pos = 0; jd_mark = _getMarkerJson(); if (!jd_mark) return false; if (json_object_object_get_ex(jd_mark, name, &jmark)) { json_object *jis_set; json_object_object_get_ex(jmark, "isSet", &jis_set); if (!json_object_get_boolean(jis_set)) return false; json_object *jpos; json_object_object_get_ex(jmark, "row", &jpos); *pos = json_object_get_int64(jpos); } return true; } DualMarkerState KsSession::_getMarkerState() { json_object *jd_mark, *jstate; const char* state; jd_mark = _getMarkerJson(); json_object_object_get_ex(jd_mark, "Active", &jstate); state = json_object_get_string(jstate); if (strcmp(state, "A") == 0) return DualMarkerState::A; return DualMarkerState::B; } /** * @brief Save the configuration of the plugins. * * @param pm: Input location for the KsPluginManager object. */ void KsSession::savePlugins(const KsPluginManager &pm) { kshark_config_doc *plugins = kshark_config_new("kshark.config.plugins", KS_CONFIG_JSON); json_object *jplugins = KS_JSON_CAST(plugins->conf_doc); json_object *jplg, *jlist = json_object_new_array(); for (auto const p: pm.getUserDataPlugins()) { kshark_config_doc *lib = kshark_export_plugin_file(p, KS_CONFIG_JSON); jplg = KS_JSON_CAST(lib->conf_doc); json_object_array_add(jlist, jplg); free(lib); } json_object_object_add(jplugins, "obj. files", jlist); kshark_config_doc_add(_config, "User Plugins", plugins); } /** * @brief Load the configuration of the plugins. * * @param kshark_ctx: Input location for context pointer. * @param pm: Input location for the KsPluginManager object. */ void KsSession::loadPlugins(kshark_context *kshark_ctx, KsPluginManager *pm) { kshark_config_doc *plugins = kshark_config_alloc(KS_CONFIG_JSON); if (!kshark_config_doc_get(_config, "User Plugins", plugins)) return; kshark_import_all_plugins(kshark_ctx, plugins); }
#include "elf_reader.h" #include <stdlib.h> ELF_Reader::ELF_Reader() { cadr = 0; csize = 0; cvadr = 0; dadr = 0; dsize = 0; dvadr = 0; gp = 0; madr = 0; mend = 0; endPC = 0; entry = 0; val_n = 0; padr = 0; psize = 0; pnum = 0; sadr = 0; ssize = 0; snum = 0; symadr = 0; symsize = 0; symnum = 0; name_table = NULL; symname_table = NULL; intere = NULL; n_intere = 0; file = NULL; elf = NULL; } bool ELF_Reader::open_file(const char *filename, const char *elfname) { file = fopen(filename, "r"); elf = fopen(elfname, "w+"); if (file != NULL && elf != NULL) return true; return false; } bool ELF_Reader::read_elf(const char *filename, const char *elfname, char **interested, int n_interested) { if(!open_file(filename, elfname)) return false; intere = interested; n_intere = n_interested; fprintf(elf,"ELF Header:\n"); read_Elf_header(); fprintf(elf,"\n\nSection Headers:\n"); read_elf_sections(); fprintf(elf,"\n\nProgram Headers:\n"); read_Phdr(); fprintf(elf,"\n\nSymbol table:\n"); read_symtable(); fclose(elf); elf = NULL; fclose(file); file = NULL; return true; } void ELF_Reader::read_Elf_header() { //file should be relocated fseek(file, 0, 0); fread(&elf64_hdr, 1, sizeof(elf64_hdr), file); fprintf(elf," magic number:\t"); for (int i = 0; i < EI_NIDENT; i++) fprintf(elf, "%02x ", elf64_hdr.e_ident[i]); fprintf(elf, "\n"); switch(elf64_hdr.e_ident[EI_CLASS]) { case 0: fprintf(elf," Class:\t\tELFCLASSNONE\n"); break; case 1: fprintf(elf," Class:\t\tELFCLASS32\n"); break; case 2: fprintf(elf," Class:\t\tELFCLASS64\n"); break; default: fprintf(elf," Class:\t\tUNKNOWN\n"); break; } switch(elf64_hdr.e_ident[EI_DATA]) { case 0: fprintf(elf," Data:\t\tinvalid data encoding\n"); break; case 1: fprintf(elf," Data:\t\tlittle-endian\n"); break; case 2: fprintf(elf," Data:\t\tbig-endian\n"); break; default: fprintf(elf," Data:\t\tUNKNOWN\n"); break; } fprintf(elf," Version:\t%x\n", elf64_hdr.e_ident[EI_VERSION]); switch (elf64_hdr.e_ident[EI_OSABI]) { case 0x00: fprintf(elf," OS/ABI:\tUNIX Syetem V\n"); break; case 0x03: fprintf(elf," OS/ABI:\tLINUX\n"); break; case 0x06: fprintf(elf," OS/ABI:\tSolaris\n"); break; case 0x09: fprintf(elf," OS/ABI:\tFreeBSD\n"); break; default: fprintf(elf," OS/ABI:\tUnknown\n"); break; } fprintf(elf," ABI Version:\t%x\n", elf64_hdr.e_ident[EI_ABIVERSION]); switch ((unsigned short)elf64_hdr.e_type) { case ET_NONE: fprintf(elf," Type:\t\tInvalid\n"); break; case ET_REL: fprintf(elf," Type:\t\tRelocatable\n"); break; case ET_EXEC: fprintf(elf," Type:\t\tExecutable\n"); break; case ET_DYN: fprintf(elf," Type:\t\tShared-obj\n"); break; case ET_CORE: fprintf(elf," Type:\t\tCore\n"); break; case ET_LOPROC: case ET_HIPROC: fprintf(elf," Type:\t\tProcessor-specific\n"); break; default: fprintf(elf," Type:\t\tUnknown\n"); break; } fprintf(elf," Type:\t\t%hu\n", (unsigned short)elf64_hdr.e_type); fprintf(elf," Machine:\t%hu\n", (unsigned short)elf64_hdr.e_machine); fprintf(elf," Version:\t%hu\n", (unsigned int)elf64_hdr.e_version); fprintf(elf," Entry point address:\t\t0x%llx\n", (unsigned long long)elf64_hdr.e_entry); entry = (unsigned long long)elf64_hdr.e_entry; fprintf(elf," Start of program headers:\t%llu (bytes into file)\n", (unsigned long long)elf64_hdr.e_phoff); padr = (unsigned long long)elf64_hdr.e_phoff; fprintf(elf," Start of section headers:\t%llu (bytes into file)\n", (unsigned long long)elf64_hdr.e_shoff); sadr = (unsigned long long)elf64_hdr.e_shoff; fprintf(elf," Flags:\t\t\t\t0x%x\n", (unsigned int)elf64_hdr.e_flags); fprintf(elf," Size of this header:\t\t%hu Bytes\n", (unsigned short)elf64_hdr.e_ehsize); fprintf(elf," Size of program headers:\t%hu Bytes\n", (unsigned short)elf64_hdr.e_phentsize); psize = (unsigned short)elf64_hdr.e_phentsize; fprintf(elf," Number of program headers:\t%hu\n", (unsigned short)elf64_hdr.e_phnum); pnum = (unsigned short)elf64_hdr.e_phnum; fprintf(elf," Size of section headers:\t%hu Bytes\n", (unsigned short)elf64_hdr.e_shentsize); ssize = (unsigned short)elf64_hdr.e_shentsize; fprintf(elf," Number of section headers:\t%hu\n", (unsigned short)elf64_hdr.e_shnum); snum = (unsigned short)elf64_hdr.e_shnum; fprintf(elf," Section header string table index:\t%hu\n", (unsigned short)elf64_hdr.e_shstrndx); } void ELF_Reader::read_elf_sections() { Elf64_Shdr elf64_shdr, name_shdr; fseek(file, 0, 0); fread(&elf64_hdr, 1, sizeof(elf64_hdr), file); fseek(file, sadr+elf64_hdr.e_shstrndx*sizeof(Elf64_Shdr), 0); fread(&name_shdr,1,sizeof(Elf64_Shdr),file); name_table = new char[(unsigned long long)name_shdr.sh_size + 10]; fseek(file, name_shdr.sh_offset, 0); fread(name_table, 1, (unsigned long long)name_shdr.sh_size, file); fseek(file, sadr, 0); for(unsigned int c=0;c<snum;c++) { fprintf(elf," [%3d]\n",c); //file should be relocated fread(&elf64_shdr,1,sizeof(elf64_shdr),file); fprintf(elf," Name: %-13s", name_table+(unsigned int)elf64_shdr.sh_name); switch ((unsigned int)elf64_shdr.sh_type) { case SHT_NULL: fprintf(elf," Type: %-8s", "NULL"); break; case SHT_PROGBITS: fprintf(elf," Type: %-8s", "PROGBITS"); break; case SHT_SYMTAB: fprintf(elf," Type: %-8s", "SYMTAB"); break; case SHT_STRTAB: fprintf(elf," Type: %-8s", "STRTAB"); break; case SHT_RELA: fprintf(elf," Type: %-8s", "RELA"); break; case SHT_HASH: fprintf(elf," Type: %-8s", "HASH"); break; case SHT_DYNAMIC: fprintf(elf," Type: %-8s", "DYNAMIC"); break; case SHT_NOTE: fprintf(elf," Type: %-8s", "NOTE"); break; case SHT_NOBITS: fprintf(elf," Type: %-8s", "NOBITS"); break; case SHT_REL: fprintf(elf," Type: %-8s", "REL"); break; case SHT_SHLIB: fprintf(elf," Type: %-8s", "SHLIB"); break; case SHT_DYNSYM: fprintf(elf," Type: %-8s", "DYNSYM"); break; case SHT_LOPROC: fprintf(elf," Type: %-8s", "LOPROC"); break; case SHT_HIPROC: fprintf(elf," Type: %-8s", "HIPROC"); break; case SHT_LOUSER: fprintf(elf," Type: %-8s", "LOUSER"); break; case SHT_HIUSER: fprintf(elf," Type: %-8s", "HIUSER"); break; default: fprintf(elf," Type: %-8s", "UNKNOWN"); break; } fprintf(elf," Address: %016llx", (unsigned long long)elf64_shdr.sh_addr); fprintf(elf," Offest: %016llx\n", (unsigned long long)elf64_shdr.sh_offset); fprintf(elf," Size: %016llx", (unsigned long long)elf64_shdr.sh_size); fprintf(elf," Entsize: %016llx", (unsigned long long)elf64_shdr.sh_entsize); switch ((unsigned long long)elf64_shdr.sh_flags) { case SHF_WRITE: fprintf(elf," Flags: %-4s", "W"); break; case SHF_ALLOC: fprintf(elf," Flags: %-4s", "A"); break; case SHF_EXECINSTR: fprintf(elf," Flags: %-4s", "X"); break; case SHF_MASKPROC: fprintf(elf," Flags: %-4s", "M"); break; case SHF_WRITE | SHF_ALLOC: fprintf(elf," Flags: %-4s", "WA"); break; case SHF_WRITE | SHF_EXECINSTR: fprintf(elf," Flags: %-4s", "WX"); break; case SHF_ALLOC | SHF_EXECINSTR: fprintf(elf," Flags: %-4s", "AX"); break; case SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR: fprintf(elf," Flags: %-4s", "WAX"); break; default: fprintf(elf," Flags: %-4s", "U"); break; } fprintf(elf," Link: %u", (unsigned int)elf64_shdr.sh_link); fprintf(elf," Info: %u", (unsigned int)elf64_shdr.sh_info); fprintf(elf," Align: %llu\n", (unsigned long long)elf64_shdr.sh_addralign); if ((unsigned int)elf64_shdr.sh_type == SHT_SYMTAB) { symadr = (unsigned long long)elf64_shdr.sh_offset; symsize = (unsigned long long)elf64_shdr.sh_size; symnum = symsize / sizeof(Elf64_Sym); } } delete []name_table; } void ELF_Reader::read_Phdr() { Elf64_Phdr elf64_phdr; fseek(file, 0, 0); fread(&elf64_hdr, 1, sizeof(elf64_hdr), file); fseek(file, padr, 0); for(unsigned int c=0;c<pnum;c++) { fprintf(elf," [%3d]\n",c); //file should be relocated fread(&elf64_phdr,1,sizeof(elf64_phdr),file); switch((unsigned int)elf64_phdr.p_type) { case PT_NULL: fprintf(elf," Type: %-9s", "Invalid"); break; case PT_LOAD: fprintf(elf," Type: %-9s", "LOAD"); break; case PT_DYNAMIC: fprintf(elf," Type: %-9s", "DYNAMIC"); break; case PT_INTERP: fprintf(elf," Type: %-9s", "INTERP"); break; case PT_NOTE: fprintf(elf," Type: %-9s", "NOTE"); break; case PT_SHLIB: fprintf(elf," Type: %-9s", "SHLIB"); break; case PT_PHDR: fprintf(elf," Type: %-9s", "PHDR"); break; case PT_TLS: fprintf(elf," Type: %-9s", "TLS"); break; case PT_NUM: fprintf(elf," Type: %-9s", "NUM"); break; case PT_LOOS: fprintf(elf," Type: %-9s", "LOOS"); break; default: fprintf(elf," Type: %-9s", "Unknown"); break; } fprintf(elf," Offset: 0x%016llx", (unsigned long long)elf64_phdr.p_offset); fprintf(elf," VirtAddr: 0x%016llx", (unsigned long long)elf64_phdr.p_vaddr); fprintf(elf," PhysAddr: 0x%016llx\n", (unsigned long long)elf64_phdr.p_paddr); fprintf(elf," FileSiz: 0x%016llx", (unsigned long long)elf64_phdr.p_filesz); fprintf(elf," MemSiz: 0x%016llx", (unsigned long long)elf64_phdr.p_memsz); switch ((unsigned int)elf64_phdr.p_flags) { case 0x01: fprintf(elf," Flags: %-4s", "X"); break; case 0x02: fprintf(elf," Flags: %-4s", "W"); break; case 0x03: fprintf(elf," Flags: %-4s", "WX"); break; case 0x04: fprintf(elf," Flags: %-4s", "R"); break; case 0x05: fprintf(elf," Flags: %-4s", "RX"); break; case 0x06: fprintf(elf," Flags: %-4s", "RW"); break; case 0x07: fprintf(elf," Flags: %-4s", "RWX"); break; default: fprintf(elf," Flags: %-4s", "U"); break; } fprintf(elf," Align: 0x%llx\n", (unsigned long long)elf64_phdr.p_align); if ((unsigned int)elf64_phdr.p_flags == 0x05 && (unsigned int)elf64_phdr.p_type == PT_LOAD) { cadr = (unsigned long long)elf64_phdr.p_offset; csize = (unsigned long long)elf64_phdr.p_filesz; cvadr = (unsigned long long)elf64_phdr.p_vaddr; } if ((unsigned int)elf64_phdr.p_flags == 0x06 && (unsigned int)elf64_phdr.p_type == PT_LOAD) { dadr = (unsigned long long)elf64_phdr.p_offset; dsize = (unsigned long long)elf64_phdr.p_filesz; dvadr = (unsigned long long)elf64_phdr.p_vaddr; } } } void ELF_Reader::read_symtable() { Elf64_Sym elf64_sym; Elf64_Shdr elf64_shdr, name_shdr; fseek(file, 0, 0); fread(&elf64_hdr, 1, sizeof(elf64_hdr), file); fseek(file, sadr+elf64_hdr.e_shstrndx*sizeof(Elf64_Shdr), 0); fread(&name_shdr,1,sizeof(Elf64_Shdr),file); name_table = new char[(unsigned long long)name_shdr.sh_size + 10]; fseek(file, (unsigned long long)name_shdr.sh_offset, 0); fread(name_table, 1, (unsigned long long)name_shdr.sh_size, file); fseek(file, sadr, 0); for(unsigned int c=0;c<snum;c++) { fread(&elf64_shdr,1,sizeof(elf64_shdr),file); if (strcmp(name_table+(unsigned int)elf64_shdr.sh_name, ".strtab") == 0) { symname_table = new char[(unsigned long long)elf64_shdr.sh_size + 10]; fseek(file, (unsigned long long)elf64_shdr.sh_offset, 0); fread(symname_table, 1, (unsigned long long)elf64_shdr.sh_size, file); break; } } delete []name_table; fseek(file, symadr, 0); for(unsigned int c=0;c<symnum;c++) { fprintf(elf," [%3d] ",c); //file should be relocated fread(&elf64_sym,1,sizeof(elf64_sym),file); fprintf(elf," Name: %-30s", symname_table+(unsigned int)elf64_sym.st_name); switch(elf64_sym.st_info & 0xf) { case STT_NOTYPE: fprintf(elf," Type: %-9s", "NOTYPE"); break; case STT_OBJECT: fprintf(elf," Type: %-9s", "OBJECT"); break; case STT_FUNC: fprintf(elf," Type: %-9s", "FUNC"); break; case STT_SECTION: fprintf(elf," Type: %-9s", "SECTION"); break; case STT_FILE: fprintf(elf," Type: %-9s", "FILE"); break; case STT_LOPROC: fprintf(elf," Type: %-9s", "LOPROC"); break; case STT_HIPROC: fprintf(elf," Type: %-9s", "HIPROC"); break; default: fprintf(elf," Type: %-9s", "Unknown"); break; } switch(elf64_sym.st_info >> 4) { case STB_LOCAL: fprintf(elf," Bind: %-9s", "LOCAL"); break; case STB_GLOBAL: fprintf(elf," Bind: %-9s", "GLOBAL"); break; case STB_WEAK: fprintf(elf," Bind: %-9s", "WEAK"); break; case STB_LOPROC: fprintf(elf," Bind: %-9s", "LOPROC"); break; case STB_HIPROC: fprintf(elf," Bind: %-9s", "HIPROC"); break; default: fprintf(elf," Bind: %-9s", "Unknown"); break; } if ((unsigned short)elf64_sym.st_shndx == 0xfff1) fprintf(elf," NDX: %-4s", "ABS"); else fprintf(elf," NDX: %-4hu", (unsigned short)elf64_sym.st_shndx); fprintf(elf," Size: %-16llu", (unsigned long long)elf64_sym.st_size); fprintf(elf," Value: %016llx\n", (unsigned long long)elf64_sym.st_value); if (strcmp(symname_table+(unsigned int)elf64_sym.st_name, "main") == 0) { madr = (unsigned long long)elf64_sym.st_value; mend = madr + (unsigned long long)elf64_sym.st_size + 1; } if (strcmp(symname_table+(unsigned int)elf64_sym.st_name, "__global_pointer$") == 0) { gp = (unsigned long long)elf64_sym.st_value; } if (strcmp(symname_table+(unsigned int)elf64_sym.st_name, "atexit") == 0) { endPC = (unsigned long long)elf64_sym.st_value; } for (int i = 0; i < n_intere; i++) { if (strcmp(symname_table+(unsigned int)elf64_sym.st_name, intere[i]) == 0) { val_adr[val_n] = (unsigned long long)elf64_sym.st_value; val_size[val_n] = (unsigned long long)elf64_sym.st_size; strcpy(val_name[val_n], symname_table+(unsigned int)elf64_sym.st_name); val_n++; } } } } void ELF_Reader::print_all() { printf("code: 0x%llx 0x%llx 0x%llx\n", cadr, csize, cvadr); printf("data: 0x%llx 0x%llx 0x%llx\n", dadr, dsize, dvadr); printf("main: 0x%llx 0x%llx\n", madr, mend); printf("PC: 0x%llx 0x%llx\n", entry, endPC); printf("val: %lld\n", val_n); for (unsigned int i = 0; i < val_n; i++) printf("\t%s 0x%llx 0x%llx\n", val_name[i], val_adr[i], val_size[i]); }
#include <algorithm> #include <cstdio> #include <iostream> using namespace std; typedef long long ll; struct Wood { int length, width; Wood() {} bool operator<(const Wood& a) { if (length != a.length) return length > a.length; return width > a.width; } }; const int maxn = 5005; int n, dp[maxn] = { 0 }, ans = 0; Wood wood[maxn]; // #define DEBUG int main() { #ifdef DEBUG freopen("d:\\.in", "r", stdin); freopen("d:\\.out", "w", stdout); #endif cin >> n; for (int i = 0; i < n; ++i) cin >> wood[i].length >> wood[i].width; sort(wood, wood + n); for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) if (wood[i].width > wood[j].width) dp[i] = max(dp[i], dp[j]); ++dp[i]; ans = max(ans, dp[i]); } cout << ans; return 0; }
#ifndef VERTEXSTREAM_H #define VERTEXSTREAM_H #include <pcx/non_copyable.h> class VertexBuffer; class VertexStream : public pcx::non_copyable { public: explicit VertexStream(VertexBuffer &buffer); VertexStream(VertexStream &&v); ~VertexStream(); operator bool() const { return true; } template<typename T> VertexStream &operator<<(const T &value){ write(&value, sizeof(T)); return *this; } private: void write(const void *data, unsigned size); VertexBuffer *buffer; char *ptr; }; #endif // VERTEXSTREAM_H
#pragma once #include <string> #include <ostream> #include <system_error> #include <ErrorBase.h> class CustomError : public llvm::ErrorInfo<CustomError> { public: static char ID; CustomError(std::string file, int line); void log(std::ostream &OS) const override; std::error_code convertToErrorCode() const override; private: std::string File; int Line; };
#ifndef COOKIETEST_H #define COOKIETEST_H #include <QTest> #include <QLocale> #include "coverageobject.h" #include <Cutelyst/cookie.h> using namespace Cutelyst; class TestCookie : public CoverageObject { Q_OBJECT public: explicit TestCookie(QObject *parent = nullptr) : CoverageObject(parent) {} private Q_SLOTS: void testDefaultConstructor(); void testConstructorWithArgs(); void testSetSameSite(); void testCopy(); void testMove(); void testCompare(); void testToRawForm(); void testToRawForm_data(); }; void TestCookie::testDefaultConstructor() { Cookie c; QVERIFY(c.domain().isEmpty()); QVERIFY(!c.isHttpOnly()); QVERIFY(!c.isSecure()); QVERIFY(c.isSessionCookie()); QVERIFY(c.name().isEmpty()); QVERIFY(c.path().isEmpty()); QCOMPARE(c.sameSitePolicy(), Cookie::SameSite::Default); QVERIFY(c.value().isEmpty()); } void TestCookie::testConstructorWithArgs() { Cookie c(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); QVERIFY(c.domain().isEmpty()); QVERIFY(!c.isHttpOnly()); QVERIFY(!c.isSecure()); QVERIFY(c.isSessionCookie()); QCOMPARE(c.name(), QByteArrayLiteral("foo")); QVERIFY(c.path().isEmpty()); QCOMPARE(c.sameSitePolicy(), Cookie::SameSite::Default); QCOMPARE(c.value(), QByteArrayLiteral("bar")); } void TestCookie::testSetSameSite() { Cookie c(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c.setSameSitePolicy(Cookie::SameSite::Strict); QCOMPARE(c.sameSitePolicy(), Cookie::SameSite::Strict); } void TestCookie::testCopy() { // test copy constructor { Cookie c1(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c1.setPath(QStringLiteral("/")); c1.setSameSitePolicy(Cookie::SameSite::Strict); Cookie c2(c1); QCOMPARE(c1.name(), c2.name()); QCOMPARE(c1.value(), c2.value()); QCOMPARE(c1.path(), c2.path()); QCOMPARE(c1.sameSitePolicy(), c2.sameSitePolicy()); } // test copy assignment { Cookie c1(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c1.setPath(QStringLiteral("/")); c1.setSameSitePolicy(Cookie::SameSite::Strict); Cookie c2; c2 = c1; QCOMPARE(c1.name(), c2.name()); QCOMPARE(c1.value(), c2.value()); QCOMPARE(c1.path(), c2.path()); QCOMPARE(c1.sameSitePolicy(), c2.sameSitePolicy()); } } void TestCookie::testMove() { // test move assignment { Cookie c1(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c1.setPath(QStringLiteral("/")); c1.setSameSitePolicy(Cookie::SameSite::Strict); Cookie c2(QByteArrayLiteral("key"), QByteArrayLiteral("val")); c2.setPath(QStringLiteral("/path")); c2.setSameSitePolicy(Cookie::SameSite::Lax); c2 = std::move(c1); QCOMPARE(c2.name(), QByteArrayLiteral("foo")); QCOMPARE(c2.value(), QByteArrayLiteral("bar")); QCOMPARE(c2.path(), QStringLiteral("/")); QCOMPARE(c2.sameSitePolicy(), Cookie::SameSite::Strict); } } void TestCookie::testCompare() { Cookie c1(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c1.setPath(QStringLiteral("/")); c1.setSameSitePolicy(Cookie::SameSite::Strict); Cookie c2(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); c2.setPath(QStringLiteral("/")); c2.setSameSitePolicy(Cookie::SameSite::Strict); Cookie c3 = c1; Cookie c4(QByteArrayLiteral("key"), QByteArrayLiteral("val")); c4.setPath(QStringLiteral("/path")); c4.setSameSitePolicy(Cookie::SameSite::Lax); QVERIFY(c1 == c2); QVERIFY(c1 == c3); QVERIFY(c1 != c4); } void TestCookie::testToRawForm() { QFETCH(Cookie, cookie); QFETCH(QByteArray, result); QCOMPARE(cookie.toRawForm(), result); } void TestCookie::testToRawForm_data() { QTest::addColumn<Cookie>("cookie"); QTest::addColumn<QByteArray>("result"); Cookie c(QByteArrayLiteral("foo"), QByteArrayLiteral("bar")); QTest::newRow("1") << c << QByteArrayLiteral("foo=bar"); c.setSecure(true); QTest::newRow("2") << c << QByteArrayLiteral("foo=bar; secure"); c.setHttpOnly(true); QTest::newRow("3") << c << QByteArrayLiteral("foo=bar; secure; HttpOnly"); c.setSameSitePolicy(Cookie::SameSite::Strict); QTest::newRow("4") << c << QByteArrayLiteral("foo=bar; secure; HttpOnly; SameSite=Strict"); const auto expire = QDateTime::currentDateTimeUtc().addDays(1); c.setExpirationDate(expire); QByteArray result = QByteArrayLiteral("foo=bar; secure; HttpOnly; SameSite=Strict; expires="); result.append(QLocale::c().toString(expire, QStringLiteral("ddd, dd-MMM-yyyy hh:mm:ss 'GMT")).toLatin1()); QTest::newRow("5") << c << result; c.setExpirationDate(QDateTime()); c.setDomain(QStringLiteral("example.net")); QTest::newRow("6") << c << QByteArrayLiteral("foo=bar; secure; HttpOnly; SameSite=Strict; domain=example.net"); c.setPath(QStringLiteral("/somewhere")); QTest::newRow("7") << c << QByteArrayLiteral("foo=bar; secure; HttpOnly; SameSite=Strict; domain=example.net; path=/somewhere"); } QTEST_MAIN(TestCookie) #include "testcookie.moc" #endif
#ifndef MAXENTMPI_HPP_INCLUDED #define MAXENTMPI_HPP_INCLUDED namespace mpi = boost::mpi; using namespace std; #endif
#ifndef __DUI_TRACK_BAR_H__ #define __DUI_TRACK_BAR_H__ #include "DUIControlBase.h" DUI_BGN_NAMESPCE enum TRACK_BAR_IMAGE_INDEX { TRACK_BAR_IMAGE_BK = 0, TRACK_BAR_IMAGE_FORE, TRACK_BAR_IMAGE_COUNT }; class DUILIB_API CTrackBarUIData { public: CRefPtr<CImageList> m_pImageBK; // follow TRACK_BAR_IMAGE_INDEX CRefPtr<CImageList> m_pImageThumb; }; class IDUIButton; class DUILIB_API IDUITrackBar: public CDUIControlBase { public: virtual ~IDUITrackBar() { NULL; } virtual VOID SetRange(INT nMin, INT nMax) = 0; virtual VOID GetRange(INT& nMin, INT& nMax) const = 0; virtual VOID SetPos(INT nPos) = 0; virtual INT GetPos() const = 0; virtual VOID SetStep(INT nStep) = 0; virtual INT GetStep() const = 0; virtual IDUIButton* GetThumbButton() = 0; virtual VOID SetUIData(const CTrackBarUIData& data) = 0; virtual const CTrackBarUIData& GetUIData() const = 0; }; class DUILIB_API CDUITrackBarBase: public IDUITrackBar { public: typedef IDUITrackBar theBase; CDUITrackBarBase(); virtual ~CDUITrackBarBase(); virtual LPVOID GetInterface(const CDUIString& strName); virtual VOID SetAttribute(const CDUIString& strName, const CDUIString& strValue); virtual BOOL EstimateSize(SIZE sizeAvaiable, SIZE& sizeRet); virtual LRESULT ProcessEvent(const DUIEvent& info, BOOL& bHandled); virtual VOID SetTooltip(const CDUIString& strTooltip); virtual VOID SetControlRect(const RECT& rt); //IDUITrackBar virtual VOID SetRange(INT nMin, INT nMax); virtual VOID GetRange(INT& nMin, INT& nMax) const; virtual VOID SetPos(INT nPos); virtual INT GetPos() const; virtual VOID SetStep(INT nStep); virtual INT GetStep() const; virtual IDUIButton* GetThumbButton(); virtual VOID SetUIData(const CTrackBarUIData& data); virtual const CTrackBarUIData& GetUIData() const; protected: virtual BOOL IsVertical() const = 0; virtual VOID OnCreate(); virtual VOID OnDestroy(); virtual VOID PaintBkgnd(HDC dc); virtual VOID PaintBorder(HDC dc); INT CalculateThumbPos(POINT ptHit); VOID SetThumbPos(INT nNewPos); INT GetThumbPos(); INT GetThumbLength(); RECT GetThumbRect(); BOOL OnLButtonDown(const DUIEvent& info); BOOL OnMouseMove(const DUIEvent& info); BOOL OnLButtonUp(const DUIEvent& info); BOOL OnKeyDown(const DUIEvent& info); VOID CreateThumb(); protected: CTrackBarUIData m_uiData; INT m_nMin; INT m_nMax; INT m_nPos; BOOL m_bTracking; INT m_nStep; }; class CDUIVerticalTrackBar: public CDUITrackBarBase { public: virtual CRefPtr<IDUIControl> Clone(); protected: virtual BOOL IsVertical() const; }; class CDUIHorizontalTrackBar: public CDUITrackBarBase { public: virtual CRefPtr<IDUIControl> Clone(); protected: virtual BOOL IsVertical() const; }; DUI_END_NAMESPCE #endif //__DUI_TRACK_BAR_H__
#include "diemthi.h" DiemThi::DiemThi() : m_maMH(""), m_diem (0) { } DiemThi::~DiemThi() { } string DiemThi::maMH() const { return m_maMH; } void DiemThi::setMaMH(const string &maMH) { m_maMH = maMH; } int DiemThi::diem() const { return m_diem; } void DiemThi::setDiem(int diem) { m_diem = diem; }
#include "presenter.h" #include "baseview.h" #include "route.h" #include "model.h" #include "encodergpx.h" #include "encoderpolyline.h" #include "encoderbackup.h" #include "qcustomplot/qcustomplot.h" #include <QUndoStack> #include "commands/commandaddroutes.h" #include "commands/commandremoveroutes.h" #include "commands/commandaddpoints.h" #include "commands/commandeditpoints.h" #include "commands/commandremovepoints.h" #include <QPushButton> Presenter::Presenter(QObject *parent) : QObject(parent) { } void Presenter::setView(BaseView* view) { this->view = view; connect(this->view, SIGNAL(addEmptyRoute(QString&)), this, SLOT(addEmptyRoute(QString&))); connect(this->view, SIGNAL(importRoutePolyline(QString&, QString&)), this, SLOT(importRoutePolyline(QString&, QString&))); connect(this->view, SIGNAL(importRoutesGPX(QStringList&)), this, SLOT(importRoutesGPX(QStringList&))); connect(this->view, SIGNAL(removeRoute(int)), this, SLOT(removeRoute(int))); connect(this->view, SIGNAL(addPoint(int, QVector3D&)), this, SLOT(addPoint(int, QVector3D&))); connect(this->view, SIGNAL(editPoint(int, int, QVector3D&)), this, SLOT(editPoint(int, int, QVector3D&))); connect(this->view, SIGNAL(removePoint(int, int)), this, SLOT(removePoint(int, int))); connect(this->view, SIGNAL(showLibraries()), this, SLOT(showLibraries())); connect(this->view, SIGNAL(scanLibraries()), this, SLOT(scanLibraries())); connect(this->view, SIGNAL(saveState()), this, SLOT(saveState())); } void Presenter::setModel(Model* model) { this->model = model; } void Presenter::setUpSignals() { connect(this->view, SIGNAL(switchCurrentRoute(int)), this->model, SLOT(switchCurrentRoute(int))); connect(this->view, SIGNAL(clearCurrentRoute()), this->model, SLOT(clearCurrentRoute())); connect(this->model, SIGNAL(setPolyline(QString&)), this->view, SLOT(setPolyline(QString&))); connect(this->model, SIGNAL(selectRoute(int)), this->view, SLOT(selectRoute(int))); connect(this->model, SIGNAL(setPlotData(Route&)), this->view, SLOT(setPlotData(Route&))); } void Presenter::addEmptyRoute(QString& name) { QDateTime time(QDateTime::currentDateTime()); QVector<Route> newRoutes{Route(name, time)}; QVector<int> newPositions{model->getRoutesNumber()}; view->getUndoStack().push(new CommandAddRoutes(model, newRoutes, newPositions)); } void Presenter::importRoutesGPX(QStringList& filenames) { try { QVector<Route> newRoutes; for (QString& filename : filenames) { newRoutes.append(EncoderGPX::decode(filename)); } int currentRoutesNumber(model->getRoutesNumber()); QVector<int> newPositions; for (int i = 0; i < newRoutes.size(); ++i) { newPositions.append(currentRoutesNumber + i); } view->getUndoStack().push(new CommandAddRoutes(model, newRoutes, newPositions)); } catch (std::invalid_argument& e) { QString error(QString::fromLatin1(e.what())); view->displayError(error); } } void Presenter::importRoutePolyline(QString& name, QString& polyline) { try { Route newRoute(EncoderPolyline::decode(polyline)); newRoute.setName(name); QDateTime time(QDateTime::currentDateTime()); newRoute.setDate(time); QVector<Route> newRoutes{newRoute}; QVector<int> newPositions{model->getRoutesNumber()}; view->getUndoStack().push(new CommandAddRoutes(model, newRoutes, newPositions)); } catch (std::invalid_argument& e) { QString error(e.what()); view->displayError(error); } } void Presenter::removeRoute(int routePosition) { QVector<Route> oldRoutes{model->getRoutesViewModel().getRoutes()[routePosition]}; QVector<int> oldPositions{routePosition}; view->getUndoStack().push(new CommandRemoveRoutes(model, oldRoutes, oldPositions)); } void Presenter::addPoint(int routePosition, QVector3D& newPoint) { QVector<QVector3D> newPoints{newPoint}; QVector<int> newPositions{model->getRoutesViewModel().getRoutes()[routePosition].size()}; view->getUndoStack().push(new CommandAddPoints(model, routePosition, newPoints, newPositions)); } void Presenter::editPoint(int routePosition, int pointPosition, QVector3D& newPoint) { QVector<QVector3D> newPoints{newPoint}; QVector<QVector3D> oldPoints{model->getRoutesViewModel().getRoutes()[routePosition][pointPosition]}; QVector<int> newPositions{pointPosition}; view->getUndoStack().push(new CommandEditPoints(model, routePosition, newPoints, newPositions, oldPoints)); } void Presenter::removePoint(int routePosition, int pointPosition) { QVector<QVector3D> oldPoints{model->getRoutesViewModel().getRoutes()[routePosition][pointPosition]}; QVector<int> removePositions{pointPosition}; view->getUndoStack().push(new CommandRemovePoints(model, routePosition, oldPoints, removePositions)); } void Presenter::showLibraries() { QString libs; for (int i = 0; i < libCount; ++i) { libs += libraries[i].fileName() + QString("\n"); } view->displayMessage(libs); } void Presenter::updatePointsModel(int routePosition) { view->setTableViewPointsModel(&(model->getRoutesViewModel().getRoutes()[routePosition])); } void Presenter::saveState() { EncoderBackup::encode(model->getRoutesViewModel().getRoutes()); } void Presenter::loadState() { QVector<Route> routes = EncoderBackup::decode(); if (routes.empty()) { return; } QVector<int> positions; for (int i = 0; i < routes.size(); ++i) { positions.push_back(i); } view->getUndoStack().push(new CommandAddRoutes(model, routes, positions)); } void Presenter::scanLibraries() { if (libraries != nullptr) { delete[] libraries; libraries = nullptr; } if (buttons != nullptr) { delete[] buttons; buttons = nullptr; } QStringList filter(std::initializer_list<QString>{"*.so", "*.dll"}); QDir libDir("operations"); libCount = libDir.entryList(filter).size(); if (libCount == 0) { return; } libraries = new QLibrary[libCount]; buttons = new QPushButton*[libCount]; int pos = 0; for (QString& entry : libDir.entryList(filter)) { libraries[pos].setFileName(QString("operations/") + entry); if (libraries[pos].load()) { QPushButton* btn = new QPushButton(entry); view->addPushButtonOperation(btn); buttons[pos] = btn; connect(btn, SIGNAL(clicked(bool)), this, SLOT(chooseOperation())); ++pos; } else { --libCount; qDebug() << libraries[pos].errorString(); } } } void Presenter::libraryOperation(int number) { typedef Visitor* (*CreateInstance)(); CreateInstance createInstance = (CreateInstance) (libraries[number].resolve("createInstance")); if (createInstance) { Visitor *instance = createInstance(); if (instance) { Route currentRoute(model->getRoutesViewModel().getRoutes()[view->getSelectedRoute()]); QString msg = instance->visit(&currentRoute); delete instance; view->displayMessage(msg); } } } void Presenter::chooseOperation() { if (view->getSelectedRoute() < 0) { return; } for (int i = 0; i < libCount; ++i) { if (sender() == static_cast<QObject*>(buttons[i])) { libraryOperation(i); return; } } }
#ifndef CON_TURNO_I #define CON_TURNO_I #include "objeto_juego_i.h" #include "contexto_turno_i.h" /** * Interface para representar a aquellos objetos que tienen algo que hacer cada * cierto tiempo. Además también vamos a usar esta interface para relacionar a * los objetos con otras cosas del mundo, como el jugador u otras celdas. * Para esta relación vamos a usar la combinación de visitante y procesador. * * Ojo a la herencia virtual de Objeto_juego_I. */ namespace App_Interfaces { class Con_turno_I: public virtual Objeto_juego_I { //////////////////// //Interface pública. public: ~Con_turno_I() {} virtual void turno(App_Interfaces::Contexto_turno_I&)=0; }; } #endif
#ifndef scene_h__ #define scene_h__ #include <vector> #include "mesh.h" #include "Ray.h" #include "intersection.h" class Scene { private: std::vector<Mesh*> _objs; void _Swap(Scene& lhv, Scene& rhv); public: Intersection Intersect(const Ray& ray); Scene(const Scene& scene); Scene(Scene&& scene); Scene& operator = (const Scene scene); Scene(); ~Scene(); }; #endif
// // RenderTarget.h // cheetah // // Copyright (c) 2013 cafaxo. All rights reserved. // #ifndef cheetah_RenderTarget_h #define cheetah_RenderTarget_h #include "OpenGL.h" #include <iostream> #include <vector> class Entity; class Shader; class RenderTarget { public: RenderTarget(); void bind(); void clear(); void render(Entity &entity, Shader &shader); protected: unsigned int mId; static RenderTarget *mBoundRenderTarget; }; #endif
#include <embr/platform/lwip/dataport.h> #include <embr/dataport.hpp> #include <embr/datapump.hpp> #include <embr/observer.h> #include "esp_log.h" typedef embr::DataPump<embr::lwip::experimental::UdpDataportTransport> datapump_type; struct AppObserver { static constexpr const char* TAG = "AppObserver"; template <class TDatapump> using event = embr::DataPortEvents<TDatapump>; template <class TDatapump, class TSubject> using DataPort = embr::DataPort< TDatapump, typename TDatapump::transport_definition_t, TSubject>; //template <class TDatapump> //, class TSubject> //void on_notify(typename event<TDatapump>::receive_dequeuing e) void on_notify(typename event<datapump_type>::receive_dequeuing e) //DataPort<TDatapump, TSubject>& dataport) { ESP_LOGI(TAG, "Got here"); } }; void udp_echo_handler(void*) { static constexpr const char* TAG = "udp_echo_handler"; ESP_LOGI(TAG, "Start"); AppObserver observer1; embr::lwip::DiagnosticDataportObserver<datapump_type> observer2; auto subject = embr::layer1::make_subject( observer2, observer1); // FIX: Doesn't work for some reason //auto subject = embr::layer1::make_subject(AppObserver()); auto dataport = embr::lwip::make_udp_dataport(subject, 7); for(;;) { vTaskDelay(2); dataport.service(); } }
#include "myStack.h" int main() { myStack uno; uno.push(3); int tres = uno.top(); int size = uno.size(); uno.pop(); bool isEmpty = uno.isEmpty(); return 0; }
#include <iostream> #include <bits/stdc++.h> #include <iomanip> #define E_Type int using namespace std; struct Stack { E_Type element; Stack* next; Stack* top=NULL; }; void push(Stack* s,E_Type ele); void pop(Stack* s); void display(Stack* s); bool Empty(); int main() { Stack stk; push(&stk,5); push(&stk,5); push(&stk,5); pop(&stk); pop(&stk); pop(&stk); push(&stk,5); display(&stk); return 0; } void push(Stack* s,E_Type ele) { Stack* nw= new Stack; nw->element=ele; nw->next=s->top; s->top=nw; } void pop(Stack* s) { Stack* point=s->top; s->top=point->next; } void display(Stack* s) { if(s->top!=NULL) { Stack* current=s->top; while(current!=NULL) { cout<<current->element<<"\n"; current=current->next; } } } bool Empty(Stack* s) { if(s->top==NULL) return 1; return 0; }
#include "Streckenende.h" #include <iostream> #include "stdafx.h" #include "Kreuzung.h" using namespace std; extern double dGlobaleZeit; Streckenende::Streckenende() { } Streckenende::Streckenende(Fahrzeug * pFahrzeug, Weg * pWeg) : FahrAusnahme(pFahrzeug, pWeg) { } Streckenende::~Streckenende() { } void Streckenende::vBearbeiten() { cout << "------------------------------------------ Streckenende --------------------------------------------" << endl; createtable(); cout << *p_pFahrzeug << endl; cout << *p_pWeg << endl << endl << endl; p_pWeg->vAbgabe(p_pFahrzeug); p_pWeg->pGetZielKreuzung()->vTanken(this->p_pFahrzeug); Weg* pNeuerWeg = p_pWeg->pGetZielKreuzung()->ptZufaelligerWeg(this->p_pWeg); pNeuerWeg->vAnnahme(this->p_pFahrzeug); cout << "ZEIT :" << dGlobaleZeit << endl; cout << "KREUZUNG :" << p_pWeg->pGetZielKreuzung()->returnName()<<" "<< p_pWeg->pGetZielKreuzung()->rtFillLevel() << endl; cout << "WECHSEL :" << p_pWeg->returnName() <<"-->"<< pNeuerWeg->returnName() << endl; cout << "FAHRZEUG :" << *p_pFahrzeug << endl; }