text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/pi/pi_module.h" #include "modules/pi/ui/OpUiInfo.h" #include "modules/pi/device_api/OpPowerStatus.h" #include "modules/pi/OpSystemInfo.h" #include "modules/pi/OpTimeInfo.h" #include "modules/pi/OpScreenInfo.h" #include "modules/pi/OpLocale.h" #include "modules/pi/system/OpPlatformViewers.h" #include "modules/pi/device_api/OpTelephonyNetworkInfo.h" #include "modules/pi/device_api/OpSubscriberInfo.h" #include "modules/pi/device_api/OpAccelerometer.h" #include "modules/pi/device_api/OpCamera.h" #include "modules/pi/device_api/OpAddressBook.h" #include "modules/pi/device_api/OpCalendarService.h" #include "modules/pi/device_api/OpCalendarListenable.h" #include "modules/pi/device_api/OpDeviceStateInfo.h" PiModule::PiModule() : ui_info(NULL) ,system_info(NULL) ,time_info(NULL) ,screen_info(NULL) #ifdef PI_POWER_STATUS ,power_status_monitor(NULL) #endif #ifdef USE_PLATFORM_VIEWERS ,platform_viewers(NULL) #endif ,locale(NULL) #ifdef PI_TELEPHONYNETWORKINFO ,telephony_network_info(NULL) #endif //PI_TELEPHONYNETWORKINFO #ifdef PI_SUBSCRIBERINFO ,subscriber_info(NULL) #endif //PI_SUBSCRIBERINFO #ifdef PI_ACCELEROMETER ,accelerometer(NULL) #endif // PI_ACCELEROMETER #ifdef PI_CAMERA ,camera_manager(NULL) #endif // PI_CAMERA #ifdef PI_ADDRESSBOOK ,address_book(NULL) #endif // PI_ADDRESSBOOK #ifdef PI_CALENDAR ,calendar(NULL) ,calendar_listeners_splitter(NULL) #endif // PI_CALENDAR #ifdef PI_DEVICESTATEINFO ,device_state_info(NULL) #endif // PI_DEVICESTATEINFO { } void PiModule::InitL(const OperaInitInfo& info) { LEAVE_IF_ERROR(OpSystemInfo::Create(&system_info)); LEAVE_IF_ERROR(OpTimeInfo::Create(&time_info)); LEAVE_IF_ERROR(OpScreenInfo::Create(&screen_info)); LEAVE_IF_ERROR(OpUiInfo::Create(&ui_info)); LEAVE_IF_ERROR(OpLocale::Create(&locale)); #ifdef PI_POWER_STATUS LEAVE_IF_ERROR(OpPowerStatusMonitor::Create(&power_status_monitor)); #endif // PI_POWER_STATUS #ifdef USE_PLATFORM_VIEWERS LEAVE_IF_ERROR(OpPlatformViewers::Create(&platform_viewers)); #endif #ifdef PI_TELEPHONYNETWORKINFO LEAVE_IF_ERROR(OpTelephonyNetworkInfo::Create(&telephony_network_info)); #endif // PI_TELEPHONYNETWORKINFO #ifdef PI_SUBSCRIBERINFO LEAVE_IF_ERROR(OpSubscriberInfo::Create(&subscriber_info)); #endif // PI_SUBSCRIBERINFO #ifdef PI_ACCELEROMETER LEAVE_IF_ERROR(OpAccelerometer::Create(&accelerometer)); #endif // PI_ACCELEROMETER #ifdef PI_CAMERA LEAVE_IF_ERROR(OpCameraManager::Create(&camera_manager)); #endif // PI_CAMERA #ifdef PI_ADDRESSBOOK LEAVE_IF_ERROR(OpAddressBook::Create(&address_book, OpAddressBook::ADDRESSBOOK_DEVICE)); #endif // PI_ADDRESSBOOK #ifdef PI_CALENDAR calendar_listeners_splitter = OP_NEW_L(OpCalendarListenable, ()); LEAVE_IF_ERROR(OpCalendarService::Create(&calendar, calendar_listeners_splitter)); #endif // PI_CALENDAR #ifdef PI_DEVICESTATEINFO LEAVE_IF_ERROR(OpDeviceStateInfo::Create(&device_state_info)); #endif // PI_DEVICESTATEINFO } void PiModule::Destroy() { #ifdef PI_DEVICESTATEINFO OP_DELETE(device_state_info); device_state_info = NULL; #endif // PI_DEVICESTATEINFO #ifdef PI_CALENDAR OP_DELETE(calendar); calendar = NULL; OP_DELETE(calendar_listeners_splitter); calendar_listeners_splitter = NULL; #endif // PI_CALENDAR #ifdef PI_ADDRESSBOOK OP_DELETE(address_book); address_book = NULL; #endif // PI_ADDRESSBOOK #ifdef PI_CAMERA OP_DELETE(camera_manager); camera_manager = NULL; #endif // PI_CAMERA #ifdef PI_ACCELEROMETER OP_DELETE(accelerometer); accelerometer = NULL; #endif // PI_ACCELEROMETER #ifdef PI_SUBSCRIBERINFO OP_DELETE(subscriber_info); subscriber_info = NULL; #endif // PI_SUBSCRIBERINFO #ifdef PI_TELEPHONYNETWORKINFO OP_DELETE(telephony_network_info); telephony_network_info = NULL; #endif // PI_TELEPHONYNETWORKINFO #ifdef USE_PLATFORM_VIEWERS OP_DELETE(platform_viewers); platform_viewers = NULL; #endif OP_DELETE(locale); locale = NULL; #ifdef PI_POWER_STATUS OP_DELETE(power_status_monitor); power_status_monitor = NULL; #endif // PI_POWER_STATUS OP_DELETE(ui_info); ui_info = NULL; OP_DELETE(screen_info); screen_info = NULL; OP_DELETE(system_info); system_info = NULL; OP_DELETE(time_info); time_info = NULL; }
/* BEGIN LICENSE */ /***************************************************************************** * SKFind : the SK search engine * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: record.cpp,v 1.40.4.5 2005/03/16 13:58:24 bozo Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #include <skfind/skfind.h> #include "stream.h" #include "field.h" #include "record.h" #include "buf.h" #include "table.h" #include "lc.h" SK_REFCOUNT_IMPL(SKFixedRecordPool) SK_REFCOUNT_IMPL_CREATOR(SKFixedRecordPool)(PRUint32 iPoolSize, PRUint32 iRecordSize) { return new SKFixedRecordPool(iPoolSize, iRecordSize); } SKFixedRecordPool::SKFixedRecordPool(PRUint32 iPoolSize, PRUint32 iRecordSize) : m_iPoolSize(iPoolSize), m_iRecordSize(iRecordSize) { m_pRecordBuffers = NULL; m_pRawRecords = NULL; m_ppRecords = NULL; m_iRecordPointer = 0; } SKFixedRecordPool::~SKFixedRecordPool() { SK_ASSERT(m_iRecordPointer == 0); if(m_pRecordBuffers) PR_Free(m_pRecordBuffers); if(m_pRawRecords) delete[] m_pRawRecords; if(m_ppRecords) delete[] m_ppRecords; } SKERR SKFixedRecordPool::Init() { m_pRecordBuffers = PR_Malloc(m_iPoolSize * m_iRecordSize); if(!m_pRecordBuffers) return err_memory; m_pRawRecords = new SKRecord[m_iPoolSize]; if(!m_pRawRecords) return err_memory; m_ppRecords = new SKRecord*[m_iPoolSize]; if(!m_ppRecords) return err_memory; for(PRUint32 i = 0; i < m_iPoolSize; ++i) { m_pRawRecords[i].SetPool(this); m_ppRecords[i] = m_pRawRecords + i; } return noErr; } SKERR SKFixedRecordPool::Terminate() { for(PRUint32 i = 0; i < m_iPoolSize; ++i) m_pRawRecords[i].SetPool(NULL); return noErr; } SKERR SKFixedRecordPool::GetRecord(SKRecord **ppRecord, void *pBuffer, PRBool bVolatileBuffer) { if(m_iRecordPointer >= m_iPoolSize) return err_notfound; *ppRecord = m_ppRecords[m_iRecordPointer++]; SKERR err; if(bVolatileBuffer) { void *pRecordBuffer = (char *)m_pRecordBuffers + (*ppRecord - m_pRawRecords) * m_iRecordSize; memcpy(pRecordBuffer, pBuffer, m_iRecordSize); err = (*ppRecord)->SetBuffer(pRecordBuffer); } else { err = (*ppRecord)->SetBuffer(pBuffer); } if(err != noErr) { m_iRecordPointer--; *ppRecord = NULL; return err; } if(*ppRecord) (*ppRecord)->AddRef(); return noErr; } SKERR SKFixedRecordPool::ReleaseRecord(SKRecord *pRecord) { SK_ASSERT( (pRecord >= m_pRawRecords) && (pRecord < m_pRawRecords + m_iPoolSize)); m_ppRecords[--m_iRecordPointer] = pRecord; return noErr; } SK_REFCOUNT_IMPL(SKRecordPool); SK_REFCOUNT_IMPL_CREATOR(SKRecordPool)(PRUint32 iPoolSize, PRUint32 iRecordSize) { return new SKRecordPool(iPoolSize, iRecordSize); } SKRecordPool::SKRecordPool(PRUint32 iPoolSize, PRUint32 iRecordSize) : m_iPoolSize(iPoolSize), m_iRecordSize(iRecordSize) { m_iPoolsCount = 0; m_ppPools = NULL; } SKRecordPool::~SKRecordPool() { if(m_ppPools) { for(PRUint32 i = 0; i < m_iPoolsCount; ++i) { if(m_ppPools[i]) { m_ppPools[i]->Terminate(); m_ppPools[i]->Release(); } } PR_Free(m_ppPools); } } SKERR SKRecordPool::GetRecord(SKRecord **ppRecord, void *pBuffer, PRBool bVolatileBuffer) { SKERR err; for(PRUint32 i = 0; i < m_iPoolsCount; ++i) { err = m_ppPools[i]->GetRecord(ppRecord, pBuffer, bVolatileBuffer); // If succeeded then return if(err == noErr) return noErr; } // All the pools are full, create a new one SKFixedRecordPool * pPool = sk_CreateInstance(SKFixedRecordPool)(m_iPoolSize, m_iRecordSize); if(!pPool) return err_memory; err = pPool->Init(); if(err != noErr) return err; m_ppPools = (SKFixedRecordPool **) PR_Realloc(m_ppPools, (m_iPoolsCount + 1) * sizeof(SKFixedRecordPool *)); SK_ASSERT(NULL != m_ppPools); m_ppPools[m_iPoolsCount++] = pPool; return m_ppPools[m_iPoolsCount - 1]->GetRecord(ppRecord, pBuffer, bVolatileBuffer); } SK_REFCOUNT_IMPL_DEFAULT(SKRecord) SKRecord::SKRecord() { m_pBuffer = NULL; m_lId = (PRUint32)-1; #ifdef FIELD_CACHE m_lFieldCount = 0; m_ppFieldCache = NULL; #endif m_lWarnCounter = 1; } SKRecord::~SKRecord() { #ifdef FIELD_CACHE if(m_ppFieldCache) { skPtr<SKIFldCollection> pFldCol; SKERR err = m_pTable->GetFldCollection(pFldCol.already_AddRefed()); SK_ASSERT(err == noErr); SK_ASSERT(NULL != pFldCol); skPtr<SKField> pField; for(PRUint32 i = 0; i < m_lFieldCount; ++i) { if(m_ppFieldCache[i]) { err=pFldCol->GetField(i,(SKIField**)pField.already_AddRefed()); SK_ASSERT(err == noErr); FieldType eType = pField->GetType(); if(eType == SKFT_DATA) ((SKBinary*)m_ppFieldCache[i])->Release(); else SK_ASSERT(NULL != PR_FALSE); } } delete[] m_ppFieldCache; } #endif } void SKRecord::OnRefPostWarn() { m_pPool->ReleaseRecord(this); m_pFragment = NULL; m_pTable = NULL; } SKERR SKRecord::GetUNumFieldValue(SKIField* pIField, PRUint32 *plValue) { if(!m_pTable || !m_pBuffer || !pIField) return SKError(err_rec_invalid,"[SKRecord::GetUNumFieldValue] " "Invalid record"); return ((SKField*)pIField)->GetUNumFieldValue(m_pBuffer, plValue); } SKERR SKRecord::GetSNumFieldValue(SKIField* pIField, PRInt32 *plValue) { if(!m_pTable || !m_pBuffer || !pIField) return SKError(err_rec_invalid,"[SKRecord::GetSNumFieldValue] " "Invalid record"); return ((SKField*)pIField)->GetSNumFieldValue(m_pBuffer, plValue); } SKERR SKRecord::GetDataFieldValue(SKIField* pIField, SKBinary** ppBinary) { SKERR err; *ppBinary = NULL; if(!m_pTable || !m_pBuffer) return SKError(err_rec_invalid,"[SKRecord::GetDataFieldValue] " "Invalid record"); if(!pIField) return SKError(err_rec_invalid,"[SKRecord::GetDataFieldValue] " "Invalid field"); PRBool bCheckType; err = pIField->IsData(&bCheckType); SK_ASSERT(err == noErr); if(!bCheckType) return SKError(err_rec_invalid,"[SKRecord::GetDataFieldValue] " "Not called with a data field"); #ifdef FIELD_CACHE if(m_ppFieldCache[((SKField*)pIField)->GetPosition()]) { SK_ASSERT(((SKField*)pIField)->GetType() == SKFT_DATA); *ppBinary = (SKBinary*) m_ppFieldCache[((SKField*)pIField)->GetPosition()]; (*ppBinary)->AddRef(); return noErr; } #endif if(m_lId != (PRUint32)-1) { PRUint32 lCount; m_pTable->GetCount(&lCount); if(m_lId == lCount-1) { err = ((SKField*)pIField) ->GetDataFieldValue(m_pBuffer, ppBinary, (const void*) -1); } else { skPtr<SKIRecord> next; m_pTable->GetRecord(m_lId+1, next.already_AddRefed()); err = ((SKField*)pIField)-> GetDataFieldValue(m_pBuffer, ppBinary, ((SKRecord*)(SKIRecord*)next)-> GetSharedBuffer()); } } else { err = ((SKField*)pIField)->GetDataFieldValue(m_pBuffer,ppBinary); } if(*ppBinary) { #ifdef FIELD_CACHE (*ppBinary)->AddRef(); m_ppFieldCache[((SKField*)pIField)->GetPosition()] = *ppBinary; #endif } return err; } SKERR SKRecord::GetStreamFieldValue(SKIField* pIField, SKIStream** ppStream) { SKERR err; *ppStream = NULL; if(!m_pTable || !m_pBuffer) return SKError(err_rec_invalid,"[SKRecord::GetStreamFieldValue] " "Invalid record"); if(m_lId != (PRUint32)-1) { PRUint32 lCount; m_pTable->GetCount(&lCount); if(m_lId == lCount-1) { err = ((SKField*)pIField) ->GetStreamFieldValue(m_pBuffer, ppStream, (const void*) -1); } else { skPtr<SKIRecord> next; m_pTable->GetRecord(m_lId+1, next.already_AddRefed()); err = ((SKField*)pIField)-> GetStreamFieldValue(m_pBuffer, ppStream, ((SKRecord*)(SKIRecord*)next)-> GetSharedBuffer()); } } else { err = ((SKField*)pIField)->GetStreamFieldValue(m_pBuffer, ppStream); } return err; } SKERR SKRecord::GetLinkFieldCount(SKIField* pIField, PRUint32 *piCount) { SKERR err = noErr; if(!m_pTable || !m_pBuffer) return SKError(err_rec_invalid,"[SKRecord::GetLinkFieldCount] " "Invalid record"); // get offset skPtr<SKField> pOffsetField; ((SKField*)pIField)->GetOffsetField(pOffsetField.already_AddRefed()); SK_ASSERT(NULL != pOffsetField); PRUint32 lOffset = 0; ((SKField*) pOffsetField)->GetUNumFieldValue(m_pBuffer, &lOffset); // is there a length ? skPtr<SKField> pCountField; ((SKField*)pIField)->GetCountField(pCountField.already_AddRefed()); PRUint32 lCount = 0; if(pCountField) { pCountField->GetUNumFieldValue(m_pBuffer, &lCount); } else { // if we do not know the id of the record, we can not get the data. if(m_lId == (PRUint32)-1) { err = SKError(err_rec_invalid, "[SKRecord::GetDataFieldValue] " "Not count for data and record detached from table."); } // is it the last record ? PRUint32 lTableCount = 0; m_pTable->GetCount(&lTableCount); if(m_lId == lTableCount - 1) { // read all the end of the file PRUint32 iLinCount = 0; skPtr<SKIRecordSet> pLinkRS; err = pIField->GetLinkSubRecordSet(pLinkRS.already_AddRefed()); if(err != noErr) { return SKError(err, "[SKRecord::GetLinkFieldCount] " "LIN not initialized."); } err = pLinkRS->GetCount(&iLinCount); if(err != noErr) return err; lCount = iLinCount - lOffset; } else { // stop where next record begins. PRUint32 lNextOffset; skPtr<SKIRecord> next; m_pTable->GetRecord(m_lId+1, next.already_AddRefed()); pOffsetField->GetUNumFieldValue( ((SKRecord*)(SKIRecord*)next)->GetSharedBuffer(), &lNextOffset); lCount = lNextOffset - lOffset; } } *piCount = lCount; return noErr; }; SKERR SKRecord::GetLinkFieldValue(SKIField* pIField, SKIRecordSet** ppRecordSet) { SKERR err = noErr; *ppRecordSet = NULL; if(!m_pTable || !m_pBuffer) return SKError(err_rec_invalid,"[SKRecord::GetLinkFieldValue] " "Invalid record"); // get file skPtr<SKIRecordSet> pLinkRS; err = pIField->GetLinkSubRecordSet(pLinkRS.already_AddRefed()); if(err != noErr) { return SKError(err, "[SKRecord::GetLinkFieldValue] " "LIN not initialized."); } // get offset skPtr<SKField> pOffsetField; ((SKField*)pIField)->GetOffsetField(pOffsetField.already_AddRefed()); SK_ASSERT(NULL != pOffsetField); PRUint32 lOffset = 0; ((SKField*) pOffsetField)->GetUNumFieldValue(m_pBuffer, &lOffset); // get count PRUint32 lCount = 0; err = GetLinkFieldCount(pIField, &lCount); return pLinkRS->GetSubRecordSet(lOffset, lCount, ppRecordSet); } SKERR SKRecord::GetFldCollection(SKIFldCollection** fldcol) { SK_ASSERT(NULL != m_pTable); return m_pTable->GetFldCollection(fldcol); } SKERR SKRecord::SetPool(SKFixedRecordPool *pPool) { m_pPool = pPool; return noErr; } SKERR SKRecord::SetBuffer(void *pBuffer) { m_pBuffer = pBuffer; SK_ASSERT(NULL != m_pBuffer); return noErr; } SKERR SKRecord::SetFragment(SKPageFileFragment *pFragment) { m_pFragment = pFragment; return noErr; } SKERR SKRecord::GetTable(SKIRecordSet** ppIRecordSet) const { *ppIRecordSet = m_pTable; if(*ppIRecordSet) (*ppIRecordSet)->AddRef(); return (*ppIRecordSet == NULL); } SKERR SKRecord::SetTable(SKIRecordSet* pTable) { if(!pTable) return err_tbl_invalid; if(pTable == m_pTable) return noErr; #ifdef FIELD_CACHE skPtr<SKIFldCollection> pFldCol; SKERR err; if(m_ppFieldCache) { err = m_pTable->GetFldCollection(pFldCol.already_AddRefed()); if(err != noErr) return err_tbl_invalid; SK_ASSERT(NULL != pFldCol); skPtr<SKField> pField; for(PRUint32 i = 0; i < m_lFieldCount; ++i) { if(m_ppFieldCache[i]) { err=pFldCol->GetField(i,(SKIField**)pField.already_AddRefed()); SK_ASSERT(err == noErr); FieldType eType = pField->GetType(); if(eType == SKFT_DATA) ((SKBinary*)m_ppFieldCache[i])->Release(); else if(eType == SKFT_LINK) ((SKIRecordSet*)m_ppFieldCache[i])->Release(); else SK_ASSERT(PR_FALSE); } } delete[] m_ppFieldCache; m_ppFieldCache = NULL; } #endif m_pTable = pTable; #ifdef FIELD_CACHE err = m_pTable->GetFldCollection(pFldCol.already_AddRefed()); if(err != noErr) return err_tbl_invalid; SK_ASSERT(NULL != pFldCol); err = pFldCol->GetFieldCount(&m_lFieldCount); if(err != noErr) return err_tbl_invalid; m_ppFieldCache = new void*[m_lFieldCount]; for(PRUint32 i = 0; i < m_lFieldCount; ++i) m_ppFieldCache[i] = NULL; #endif return pTable ? noErr : err_tbl_invalid; } SKRecordSet::SKRecordSet() { m_pRecordCache = NULL; m_lCacheCount = 0; m_lIncrement = 5; m_lDecrement = -1; } SKRecordSet::~SKRecordSet() { if(m_pRecordCache) { for(PRUint32 i = 0; i < m_lCacheCount; ++i) if(m_pRecordCache[i]) delete m_pRecordCache[i]; delete[] m_pRecordCache; } } void SKRecordSet::Terminate() { m_lWarnCounter = -1; if(m_pRecordCache) { delete[] m_pRecordCache; m_pRecordCache = NULL; } m_lCacheCount = 0; m_lIncrement = 5; m_lDecrement = -1; } SKERR SKRecordSet::ConfigureItem(char* szSection, char* szToken, char* szValue) { if(!szToken) return err_invalid; if(!strcmp(szToken, "SIZE")) { if(m_pRecordCache) { delete[] m_pRecordCache; m_pRecordCache = NULL; } PRInt32 lCacheSize = atol(szValue); if(lCacheSize < 0) return SKError(err_rec_invalid, "[SKRecordSet::Configure] " "Cache size not valid (%d)", lCacheSize); if(lCacheSize) { m_pRecordCache = new SKRecordCacheItem[lCacheSize]; for(PRInt32 i = 1; i < lCacheSize; i++) { m_pRecordCache[i - 1].m_pNext = m_pRecordCache + i; m_pRecordCache[i].m_pPrev = m_pRecordCache + i - 1; } m_pFirstItem = m_pInsertItem = m_pRecordCache; m_pLastItem = m_pRecordCache + lCacheSize - 1; } return noErr; } else if(!strcmp(szToken, "SCOREINCREMENT")) m_lIncrement = atol(szValue); else if(!strcmp(szToken, "SCOREDECREMENT")) m_lDecrement = atol(szValue); else return err_not_handled; return noErr; } SKERR SKRecordSet::GetCachedRecord(PRUint32 lId, SKIRecord** ppIRecord) { *ppIRecord = NULL; if(m_pRecordCache) { SKRecordCacheItem* pItem = m_pFirstItem; m_pInsertItem = NULL; while(pItem && (SKIRecord*)*(skPtr<SKIRecord>*)pItem) { PRUint32 l; SKERR err = (*pItem)->GetId(&l); SK_ASSERT(err == noErr); if(err != noErr) return err; if(l == lId) { // This is the result *ppIRecord = *pItem; // Move up this item pItem->m_lScore += m_lIncrement; SKRecordCacheItem* pUpItem = pItem; while( pUpItem->m_pPrev && (pUpItem->m_pPrev->m_lScore <= pItem->m_lScore)) { pUpItem = pUpItem->m_pPrev; } if(pUpItem != pItem) { SKRecordCacheItem* pTmpItem = pItem->m_pPrev; pItem->m_pPrev->m_pNext = pItem->m_pNext; if(pItem->m_pNext) pItem->m_pNext->m_pPrev = pItem->m_pPrev; pItem->m_pPrev = pUpItem->m_pPrev; pItem->m_pNext = pUpItem; if(pItem->m_pPrev) pItem->m_pPrev->m_pNext = pItem; pUpItem->m_pPrev = pItem; if(m_pFirstItem == pUpItem) m_pFirstItem = pItem; if(!pUpItem->m_pNext) m_pLastItem = pUpItem; pItem = pTmpItem; } pItem = pItem->m_pNext; break; } else { // Release obsolete data if((pItem->m_lScore += m_lDecrement) <= 0) { pItem->m_lScore = 0; if(--m_lCacheCount > 0) --m_lWarnCounter; else m_lWarnCounter = -1; *pItem = NULL; } if( (pItem->m_lScore <= m_lIncrement) && ( !pItem->m_pPrev || ( pItem->m_pPrev && (pItem->m_pPrev->m_lScore > m_lIncrement)))) { m_pInsertItem = pItem; } } pItem = pItem->m_pNext; } while(pItem && (SKIRecord*)*(skPtr<SKIRecord>*)pItem) { // Release obsolete data if((pItem->m_lScore += m_lDecrement) <= 0) { pItem->m_lScore = 0; if(--m_lCacheCount > 0) --m_lWarnCounter; else m_lWarnCounter = -1; *pItem = NULL; } if( (pItem->m_lScore <= m_lIncrement) && ( !pItem->m_pPrev || ( pItem->m_pPrev && (pItem->m_pPrev->m_lScore > m_lIncrement)))) { m_pInsertItem = pItem; } pItem = pItem->m_pNext; } if(!m_pInsertItem && pItem) m_pInsertItem = pItem; } if(*ppIRecord) (*ppIRecord)->AddRef(); return (*ppIRecord == NULL); } void SKRecordSet::InsertRecordInCache(SKIRecord* pIRecord) { SK_ASSERT(NULL != pIRecord); if(m_pRecordCache && m_pInsertItem) { SK_ASSERT(!m_pLastItem->m_pNext); SKRecordCacheItem* pNextLastItem = m_pLastItem; // Detach the last item if(m_pInsertItem != m_pLastItem) { SK_ASSERT(NULL != m_pLastItem->m_pPrev); m_pLastItem->m_pPrev->m_pNext = NULL; pNextLastItem = pNextLastItem->m_pPrev; } // Init the item if(!*m_pLastItem) ++m_lCacheCount; m_lWarnCounter = m_lCacheCount; *m_pLastItem = pIRecord; m_pLastItem->m_lScore = m_lIncrement; if(m_pInsertItem != m_pLastItem) { // Link it m_pLastItem->m_pPrev = m_pInsertItem->m_pPrev; m_pLastItem->m_pNext = m_pInsertItem; // Back-link it if(m_pLastItem->m_pPrev) m_pLastItem->m_pPrev->m_pNext = m_pLastItem; if(m_pLastItem->m_pNext) m_pLastItem->m_pNext->m_pPrev = m_pLastItem; // Update the first item if(m_pFirstItem == m_pInsertItem) m_pFirstItem = m_pLastItem; // Update the insert item m_pInsertItem = m_pLastItem; // Update the last item m_pLastItem = pNextLastItem; } } } void SKRecordSet::OnRefPreWarn() { if(m_lReferenceCounter == (PRInt32)(1 + m_lCacheCount)) Terminate(); }
#pragma once #include "Event.h" class userInputEvent : public Event { private: char key; GameObject a; GameObject b; public: userInputEvent(char key); userInputEvent(GameObject a, GameObject b); char getKeyPress(); GameObject getObjA(); GameObject getObjB(); eventType getType(); };
#ifndef MODEL_H_ #define MODEL_H_ #include <SDL.h> class Model { public: Model(SDL_Surface *s, int x, int y); Model(); ~Model(); void setSurface(SDL_Surface *s); void setX(int x); void setY(int y); void setColorKey(int rgb); SDL_Surface *getSurface(); int getX(); int getY(); private: int x,y; SDL_Surface *surface; public: bool operator==(Model& m); }; #endif
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e8 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back // 昇順sort #define sorti(x) sort(x.begin(), x.end()) // 降順sort #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) int main() { int n,m; cin >> n >> m; vector<vector<int> > cost(n+1, vector<int>(n+1, 10000)); for (int i = 0; i < m; ++i) { int a,b; cin >> a >> b; cost[a][b] = 1; cost[b][a] = 1; } for (int i = 0; i <= n; ++i) { cost[i][i] = 0; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { for (int k = 1; k <= n; ++k) { cost[j][k] = min(cost[j][k], cost[j][i] + cost[i][k]); } } } for (int i = 1; i <= n; ++i) { int ans = 0; for (int j = 1; j <= n; ++j) { if (i == j) continue; if (cost[i][j] == 2) ans += 1; } cout << ans << endl; } }
// Copyright 2020 Fuji-Iot authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "fuji_ac_protocol_handler.h" #include "gtest/gtest.h" namespace fuji_iot { // Those tests were created using original wired-controller connected to // AC unit and capturing communication on the wire. AC unit state modification // was done with IR controller and then with wired-controller. class FujiAcProtocolHandlerTest : public testing::Test { protected: void ExpectResponse(std::array<uint8_t, 8> mf, std::array<uint8_t, 8> resp) { auto r = handler_->HandleMasterFrame(FujiMasterFrame(mf)); EXPECT_EQ(r.has_value(), true); EXPECT_EQ(r.value().BuildFrame(), resp); } void ExpectNull(std::array<uint8_t, 8> mf) { auto r = handler_->HandleMasterFrame(FujiMasterFrame(mf)); EXPECT_EQ(r.has_value(), false); } void SetUp() override { state_ = new FujiAcState(); handler_ = std::unique_ptr<FujiAcProtocolHandler>( new FujiAcProtocolHandler(std::unique_ptr<FujiAcState>(state_))); } std::unique_ptr<FujiAcProtocolHandler> handler_; FujiAcState *state_; }; // This communication was captured immediately after power-on (by circuit // breaker) of the AC Unit. It excercises login sequence. TEST_F(FujiAcProtocolHandlerTest, Startup) { ExpectNull({0x00, 0x81, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x00, 0x20}, {0x20, 0x81, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}); ExpectResponse({0x00, 0xa0, 0x20, 0x1f, 0x1f, 0x05, 0x01, 0x00}, {0x20, 0xa1, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); } // This communication was captured after controller was already registered, but // was temporarily disconnected and connected to main unit again. TEST_F(FujiAcProtocolHandlerTest, TestReconnect) { ExpectNull({0x00, 0x81, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}); ExpectResponse({0x00, 0xa0, 0x20, 0x1f, 0x1f, 0x05, 0x01, 0x00}, {0x20, 0xa1, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); } // This communication was captured when AC unit was turned on with a remote (IR) // controller. TEST_F(FujiAcProtocolHandlerTest, RemoteTurnOnTurnOff) { handler_->login_read_ = false; ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x12, 0x00, 0x2f, 0x00}); EXPECT_EQ(false, state_->Enabled()); EXPECT_EQ(18, state_->Temperature()); ExpectNull({0x00, 0x80, 0x00, 0x47, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x47, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x47, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(true, state_->Enabled()); EXPECT_EQ(22, state_->Temperature()); ExpectNull({0x00, 0x80, 0x00, 0x46, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x46, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x46, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(false, state_->Enabled()); } // This communication was captured when AC unit state was modified in various // ways using (IR) controller. TEST_F(FujiAcProtocolHandlerTest, TestGolden) { handler_->login_read_ = false; ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x47, 0x16, 0x00, 0x2f, 0x00}); // Set fan to high ExpectNull({0x00, 0x80, 0x00, 0x37, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x37, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x37, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x37, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x37, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(fan_t::HIGH, state_->Fan()); // Set fan to high ExpectNull({0x00, 0x80, 0x00, 0x27, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x27, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x27, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x27, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x27, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(fan_t::MEDIUM, state_->Fan()); // Set fan to low ExpectNull({0x00, 0x80, 0x00, 0x17, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x17, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x17, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x17, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x17, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(fan_t::LOW, state_->Fan()); // Set fan to auto ExpectNull({0x00, 0x80, 0x00, 0x07, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(fan_t::AUTO, state_->Fan()); // Set temp to 18 ExpectNull({0x00, 0x80, 0x00, 0x07, 0x12, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x12, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x12, 0x00, 0x2f, 0x00}); EXPECT_EQ(18, state_->Temperature()); // Set temp to 22 ExpectNull({0x00, 0x80, 0x00, 0x07, 0x16, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); EXPECT_EQ(22, state_->Temperature()); // Set temp to 25 ExpectNull({0x00, 0x80, 0x00, 0x07, 0x19, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x19, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x19, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x19, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x19, 0x00, 0x2f, 0x00}); EXPECT_EQ(25, state_->Temperature()); // Set temp to 30 ExpectNull({0x00, 0x80, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(30, state_->Temperature()); // Set mode to dry ExpectNull({0x00, 0x80, 0x00, 0x05, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x05, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x05, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x05, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x05, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(mode_t::DRY, state_->Mode()); // Set mode to fan ExpectNull({0x00, 0x80, 0x00, 0x03, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); EXPECT_EQ(mode_t::FAN, state_->Mode()); // Set mode to heat ExpectNull({0x00, 0x80, 0x00, 0x09, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x09, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x09, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x09, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x09, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(mode_t::HEAT, state_->Mode()); // Set mode to auto ExpectNull({0x00, 0x80, 0x00, 0x0b, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x0b, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x0b, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x0b, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x0b, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(mode_t::AUTO, state_->Mode()); // Set mode to cool ExpectNull({0x00, 0x80, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(mode_t::COOL, state_->Mode()); // Enable econ ExpectNull({0x00, 0x80, 0x00, 0x07, 0x9e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x9e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x9e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x9e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x9e, 0x00, 0x2f, 0x00}); EXPECT_EQ(true, state_->Economy()); // Disable econ ExpectNull({0x00, 0x80, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(false, state_->Economy()); // Enable swing ExpectNull({0x00, 0x80, 0x00, 0x07, 0x1e, 0x44, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0x44, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x04, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0xa4, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x04, 0x2f, 0x00}); EXPECT_EQ(true, state_->Swing()); // Disable swing ExpectNull({0x00, 0x80, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x1e, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x1e, 0x00, 0x2f, 0x00}); EXPECT_EQ(false, state_->Swing()); // Set temp to 23 ExpectNull({0x00, 0x80, 0x00, 0x07, 0x17, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); EXPECT_EQ(23, state_->Temperature()); // Single blow direction ExpectNull({0x00, 0x80, 0x00, 0x07, 0x17, 0x42, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); // Again ExpectNull({0x00, 0x80, 0x00, 0x07, 0x17, 0x42, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); // Again ExpectNull({0x00, 0x80, 0x00, 0x07, 0x17, 0x42, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); // Turning off ExpectNull({0x00, 0x80, 0x00, 0x06, 0x17, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x06, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x06, 0x17, 0x00, 0x2f, 0x00}); EXPECT_EQ(false, state_->Enabled()); } // This communication was captured when AC unit was turned on using wired // controller. TEST_F(FujiAcProtocolHandlerTest, TurnOn) { handler_->login_read_ = false; ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x06, 0x17, 0x00, 0x2f, 0x00}); state_->SetEnabled(true); ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); EXPECT_EQ(true, state_->Enabled()); } // This communication was captured when AC unit state was modified using wired // controller. TEST_F(FujiAcProtocolHandlerTest, WiredControlGolden) { handler_->login_read_ = false; ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x06, 0x17, 0x00, 0x2f, 0x00}); state_->SetEnabled(true); ExpectResponse({0x00, 0xa0, 0x00, 0x06, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x17, 0x00, 0x2f, 0x00}); // set temp 18 state_->SetTemperature(18); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x17, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x12, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x12, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x12, 0x00, 0x2f, 0x00}); // set temp 22 state_->SetTemperature(22); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // set fan max state_->SetFan(fan_t::MAX); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x47, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x47, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x47, 0x16, 0x00, 0x2f, 0x00}); // set fan high state_->SetFan(fan_t::HIGH); ExpectResponse({0x00, 0xa0, 0x00, 0x47, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x37, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x37, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x37, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x37, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x37, 0x16, 0x00, 0x2f, 0x00}); // set fan medium state_->SetFan(fan_t::MEDIUM); ExpectResponse({0x00, 0xa0, 0x00, 0x37, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x27, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x27, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x27, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x27, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x27, 0x16, 0x00, 0x2f, 0x00}); // set fan low state_->SetFan(fan_t::LOW); ExpectResponse({0x00, 0xa0, 0x00, 0x27, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x17, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x17, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x17, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x17, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x17, 0x16, 0x00, 0x2f, 0x00}); // set fan auto state_->SetFan(fan_t::AUTO); ExpectResponse({0x00, 0xa0, 0x00, 0x17, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // set mode dry and temp to 26 state_->SetMode(mode_t::DRY); state_->SetTemperature(26); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x05, 0x1a, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x05, 0x1a, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x05, 0x1a, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x05, 0x1a, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x05, 0x1a, 0x00, 0x2f, 0x00}); // set mode heat and temp to 21 state_->SetMode(mode_t::HEAT); state_->SetTemperature(21); ExpectResponse({0x00, 0xa0, 0x00, 0x05, 0x1a, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x09, 0x15, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x09, 0x15, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x09, 0x15, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x09, 0x15, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x09, 0x15, 0x00, 0x2f, 0x00}); // set mode fan state_->SetMode(mode_t::FAN); ExpectResponse({0x00, 0xa0, 0x00, 0x09, 0x15, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x03, 0x00, 0x00, 0x2f, 0x00}); ExpectNull({0x00, 0x80, 0x00, 0x03, 0x12, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); // set auto and temp to 24 state_->SetMode(mode_t::AUTO); state_->SetTemperature(24); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x0b, 0x18, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x0b, 0x18, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x0b, 0x18, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x0b, 0x18, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x0b, 0x18, 0x00, 0x2f, 0x00}); // set mode fan state_->SetMode(mode_t::FAN); ExpectResponse({0x00, 0xa0, 0x00, 0x0b, 0x18, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x03, 0x00, 0x00, 0x2f, 0x00}); ExpectNull({0x00, 0x80, 0x00, 0x03, 0x12, 0x40, 0x01, 0x20}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0x40, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x03, 0x00, 0x00, 0x2f, 0x00}); // set mode cool state_->SetMode(mode_t::COOL); state_->SetTemperature(22); ExpectResponse({0x00, 0xa0, 0x00, 0x03, 0x12, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // set economy on state_->SetEconomy(true); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x96, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x96, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x96, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x96, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x96, 0x00, 0x2f, 0x00}); // set economy off state_->SetEconomy(false); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x96, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // set swing on state_->SetSwing(true); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x04, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x04, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x04, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa4, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x04, 0x2f, 0x00}); // set swing off state_->SetSwing(false); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa4, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // swing step state_->SetSwingStep(true); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x02, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // swing step state_->SetSwingStep(true); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x02, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); // set swing on state_->SetSwing(true); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x04, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x04, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x04, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa4, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x04, 0x2f, 0x00}); // set swing off state_->SetSwing(false); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa4, 0x01, 0x20}, {0x20, 0x81, 0x08, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0x00, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); ExpectResponse({0x00, 0xa0, 0x00, 0x07, 0x16, 0xa0, 0x01, 0x20}, {0x20, 0x81, 0x00, 0x07, 0x16, 0x00, 0x2f, 0x00}); } } // namespace fuji_iot
#include <iostream> using namespace std; //Nhap Mang void Input(int *&a,int &n)//boi vi con tro cung la 1 bien va muon no thay doi gia thi phai refenfer { do { cout<<"\n Nhap vao n:\t"; cin>>n; if(n<=0) { cout<<"\n N khong hop le!"; } } while(n<=0); ///CAP-PHAT-bO -nHO //NOTE: ->chung ta co the tao tao 1 con tro de truy mang a[] bang cach gian tiep nhung o day da khai bao con tro //chu khong khai bao tham so a[] a=new int[n]; for(int i=0; i<n; i++) { cout<<"\n NHap vao a["<<i<<"]:\t"; cin>>*(a+i);//<=>a[i](c++)<=>&a[i](C)<=>*(a++) } } void Export(int *a,int n) { for(int i=0; i<n; i++) { cout<<*(a++)<<" "; } } /*Cach-Thao-Tac-KIEM-Tra*/ //Mảng có phải là mảng toàn chẵn int Text_Chan(int *a,int n) { for(int i=0; i<n; i++) { if(*(a+i)%2!=0) { return 0; } } return 1; } //Mảng có phải là mảng toàn số nguyên tố bool Text_NgTo(int x) { if(x<2) { return false; } else { for(int i=2; i<x; i++) { if(x%i==0) { return false; } } } return true; } int Mang_nguyento(int *a,int n) { for(int i=0;i<n;i++) { if(Text_NgTo(a[i])==false) { return 0; } } return 1; } //Mảng có phải là mảng tăng dần int Text_Tangdan(int *a,int n) { for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(a[i]<=a[j]) { return 0; } } } return 1; } /*Các thao tác tính toán*/ //Có bao nhiêu số chia hết cho 4 nhưng không chia hết cho 5 int count_chia(int *a,int n) { int dem=0; for(int i=0;i<n;i++) { if(*(a+i)%4==0&&a[i]%5!=0) { dem++; } } return dem; } //Tổng các số nguyên tố có trong mảng int sum_NgTo(int *a,int n) { int tong=0; for(int i=0;i<n;i++) { if(Text_NgTo(a[i])) { tong+=a[i]; } } return tong; } /*Các thao tác tìm kiếm*/ //Vị trí cuối cùng của phần tử x trong mảng void position_Last(int *a,int n,int &x) { cout<<"\n Nhap vao x can tim:\t"; cin>>x; int position=-1;//khong de 0 duoc vi no co 0 a[0]!con i thi gan roi nen ko lo for(int i=0;i<n;i++) { if(*(a++)==x) { position=i;//vi Tri ne! } } if(position!=-1) cout<<"\n VI tri cuoi x = a["<<position<<"]!"; else cout<<"\n Khong Ton Tai cAi x Do!!hi"; } //Vị trí số nguyên tố đầu tiên trong mảng nếu có int search_NgToFis(int *a,int n) { for(int i=0;i<n;i++) { if(Text_NgTo(a[i])) { return i;//Tra ve vi tri dau tien } } return 0; } //Tìm số nhỏ nhất trong mảng void Tim_Min(int *a,int n) { int Min=a[0]; for(int i=0;i<n;i++) { if(*(a+i)<Min) { Min=a[i]; } } cout<<"\n So nho nhat = "<<Min; } //Tìm số dương nhỏ nhất trong mảng void Tim_Minduong(int *a,int n) { int Min_duong=0; bool check=false; for(int i=0;i<n;i++) { if(*(a+i)>=0) { Min_duong=a[i]; check=true; } } if(check==false) { cout<<"\n Khong Ton tai so duong Trong mang nay!"; return;//ngung->vi no o trong ham nen dc su dung nhu vay } else { for(int i=0;i<n;i++) { if(a[i]<Min_duong&&a[i]>=0) { Min_duong=a[i]; } } } cout<<"\n So duong Nho nhat trong mang = "<<Min_duong; } int main() { //cap phat ngoai ham int main() dung refencen hoac con tro cap 2 int *a=NULL;//khong tro vao dau ca! int n=0; Input(a,n); Export(a,n); if(Text_Chan(a,n)!=1) { cout<<"\n Mang ko Toan chan!"; } else { cout<<"\n mANG chan!"; } if(Mang_nguyento(a,n)==1) { cout<<"\n Mang nguyen to!"; } else { cout<<"\n Mang kHONG tOAN nguyen to!"; } if(Text_Tangdan(a,n)==1) { cout<<"\n Mang Tang dan!"; } else { cout<<"\n Mang khong tang dan!"; } //Thao Tac Tinh Toan cout<<"\n SO luong so chia het cho 4 ,khong chia het 5 = "<<count_chia(a,n); cout<<"\n Tong cac so nguyen to trong mang = "<<sum_NgTo(a,n); int x=0; position_Last(a,n,x); int Tim_=search_NgToFis(a,n); if(Tim_==0) { cout<<"\n Mang Khong co so nguyen to!"; } else { cout<<"\n SO nguyen to dau tien tai a["<<Tim_<<"] !"; } Tim_Min(a,n); Tim_Minduong(a,n); //Xoa mang con tro delete[] a; return 0; }
#ifndef __RequestDissolveRoom_H__ #define __RequestDissolveRoom_H__ #include "BaseProcess.h" class RequestDissolveRoom : public BaseProcess { public: RequestDissolveRoom(); ~RequestDissolveRoom(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); }; #endif // !__RequestDissolveRoom_H__
#include <cstdio> #include<vector> using namespace std ; const int N = 10100 ; int chainHead[N], chainId[N], pos[N], cost[N], par[N][14]; vector < int > g[N], costs[N], index[N] ; int sz[N], dep[N], End[N], cur, chainNo; int tree[N << 2] ; void fresh(int n){ for(int i = 0 ; i <= n ; ++i){ g[i].clear() ; costs[i].clear() ; index[i].clear() ; chainHead[i] = -1 ; for(int j = 0 ; j < 14 ; ++j) par[i][j] = -1 ; } } void dfs(int s, int p = 0){ par[s][0] = p ; sz[s] = 1 ; dep[s] = 1 + dep[p] ; for(int i = 1 ; i < 14 ; ++i) par[s][i] = par[par[s][i - 1]][i - 1] ; for(int i = 0 ; i < g[s].size() ; ++i){ if(g[s][i] == p)continue; End[index[s][i]] = g[s][i] ; dfs(g[s][i], s) ; sz[s] += sz[g[s][i]] ; } } void HLD(int s, int p, int c){ if(chainHead[chainNo] == -1){ chainHead[chainNo] = s ; } chainId[s] = chainNo ; pos[s] = ++cur ; cost[cur] = c ; int mx = -1, id = -1, cst = 0 ; for(int i = 0 ; i < g[s].size() ; ++i){ if(g[s][i] == p)continue ; if(sz[g[s][i]] > mx){ mx = sz[g[s][i]] ; id = g[s][i] ; cst = costs[s][i] ; } } if(id != -1){ HLD(id, s, cst) ; } for(int i = 0 ; i < g[s].size() ; ++i){ if(g[s][i] == p or g[s][i] == id)continue ; ++chainNo ; HLD(g[s][i], s, costs[s][i]) ; } } void build(int i, int b, int e){ if(b == e){ tree[i] = cost[b] ; return ; } int mid = (b + e) >> 1 ; build(i << 1, b, mid) ; build(i << 1 | 1, mid + 1, e) ; tree[i] = tree[i << 1] > tree[i << 1 | 1] ? tree[i << 1] : tree[i << 1 | 1] ; } int lca_query(int a, int b){ if(dep[a] < dep[b])swap(a, b) ; int d = dep[a] - dep[b] ; for(int i = 13 ; i >= 0 ; --i) if(d & (1 << i)) a = par[a][i] ; if(a == b)return a ; for(int i = 13 ; i >= 0 ; --i) if(par[a][i] != par[b][i]) a = par[a][i], b = par[b][i] ; return par[a][0] ; } int query(int i, int b, int e, int l, int r){ if(e < l or b > r)return 0 ; if(l <= b and e <= r)return tree[i] ; int mid = (b + e) >> 1 ; int x = query(i << 1, b, mid, l, r) ; int y = query(i << 1 | 1, mid + 1, e, l, r) ; return x >= y ? x : y ; } int query_up(int u, int v){ if(u == v)return 0; int uchain, vchain = chainId[v], res = -1 ; while(true){ uchain = chainId[u] ; if(uchain == vchain){ if(u != v){ int x = query(1, 1, cur, pos[v] + 1, pos[u]) ; if(res < x)res = x ; } break ; } int x = query(1, 1, cur, pos[chainHead[uchain]], pos[u]) ; if(res < x)res = x ; u = chainHead[uchain] ; u = par[u][0] ; } return res ; } void update(int i, int b, int e, int p, int v){ if(p > e or p < b)return ; if(p == e and b == p){ tree[i] = v ; return ; } int mid = (b + e) >> 1 ; update(i << 1, b, mid, p, v) ; update(i << 1 | 1, mid + 1, e, p, v) ; tree[i] = (tree[i << 1] > tree[i << 1 | 1]) ? tree[i << 1] : tree[i << 1 | 1] ; } int answer(int a, int b){ int lca = lca_query(a, b) ; int res = query_up(a, lca) ; int tmp = query_up(b, lca) ; if(res < tmp)res = tmp ; return res ; } void modify(int a, int b){ int u = End[a] ; update(1, 1, cur, pos[u], b) ; } int main(){ int tc ; scanf("%d",&tc) ; while(tc--){ int n ; scanf("%d",&n) ; fresh(n) ; int a, b, c ; for(int i = 1 ; i < n ; ++i){ scanf("%d %d %d",&a, &b, &c) ; g[a].push_back(b) ; costs[a].push_back(c) ; index[a].push_back(i) ; g[b].push_back(a) ; costs[b].push_back(c) ; index[b].push_back(i) ; } cur = chainNo = 0 ; dfs(1) ; HLD(1, -1, -1) ; build(1, 1, cur) ; while(true){ char s[10] ; scanf("%s",s) ; if(s[0] == 'D')break ; scanf("%d %d",&a, &b) ; if(s[0] == 'Q'){ printf("%d\n",answer(a, b)) ; } else{ modify(a, b) ; } } } return 0 ; }
#include <bits/stdc++.h> using namespace std; #define f first #define s second #define pb push_back #define rep(i, begin, end) \ for (__typeof(end) i = (begin) - ((begin) > (end)); \ i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define db(x) cout << '>' << #x << ':' << x << endl; #define sz(x) ((int)(x).size()) #define newl cout << "\n" #define ll long long int #define vi vector<int> #define vll vector<long long> #define vvll vector<vll> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; const int mxN = 1e3 + 5; const int inf = 1e9; vvll isfloor(mxN, vll(mxN, 0)); vvll vis(mxN, vll(mxN, 0)), par(mxN, vll(mxN, 0)); vll dx = {-1, 0, 1, 0}; vll dy = {0, -1, 0, 1}; /* void dfs(ll x, ll y) { vis[x][y] = 1; rep(i, 0, 4) { ll u = x+dx[i]; ll v = y+dy[i]; if(u < 0 || u >= n || v < 0|| v >= m || !isfloor[u][v] || vis[u][v]) continue; dfs(u, v); } } */ int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif cin >> n >> m; ll sx, sy, ex, ey; rep(i, 0, n) { string str; cin >> str; rep(j, 0, m) { char ch = str[j]; if (ch == '#') { } else { if (ch == 'A') { sx = i, sy = j; } else if (ch == 'B') { ex = i, ey = j; } isfloor[i][j] = 1; } } } par[sx][sy] = -1; queue<array<ll, 2>> pq; pq.push({sx, sy}); string dir = "ULDR"; while (!pq.empty()) { auto top = pq.front(); auto x = top[0], y= top[1]; pq.pop(); vis[x][y] = 1; if (x == ex && y == ey) { // backtrack to find string; string ans = ""; int k = par[x][y]; while(k != -1) { x -= dx[k]; y -= dy[k]; ans += (dir[k]); k = par[x][y]; } reverse(ans.begin(), ans.end()); cout << "YES"; newl; cout<<sz(ans); newl; cout<<ans; return 0; } rep(i, 0, 4) { ll u = x + dx[i]; ll v = y + dy[i]; if (u < 0 || u >= n || v < 0 || v >= m || !isfloor[u][v] || vis[u][v]) continue; vis[u][v] = 1; par[u][v] = i; pq.push({u, v}); } } cout << "NO"; return 0; } // cses labyrinth
#pragma once #include "..\Common\Pch.h" #include "..\Graphic\Direct3D.h" #include "..\RenderResource\InputLayout.h" class SkyPlane : public InputLayout { public: SkyPlane(); ~SkyPlane(); void Initialize(); virtual void Update(FLOAT delta); void SetBuffer(); private: struct BufferData { FLOAT Translation; FLOAT Scale; FLOAT Brightness; FLOAT Pad; }; vector<IL_PosTex> mVertexData; vector<UINT> mIndexData; ID3D11Buffer* mBuffer; FLOAT mTranslation; virtual void InitializeData(); virtual void InitializeBuffer(); };
#pragma once #include "Quiz_fwd.h" #include "QuizSession_fwd.h" #include "QuestionStates.h" namespace qp { class CQuizSession : boost::noncopyable { public: CQuizSession(CConstQuizPtr const& quiz, const CQuestionStates & questionStates); ~CQuizSession(); IQuestionStatePtr GetCurrentQuestionState()const; void GotoNextQuestion(); const CQuestionStates & GetQuestionStates()const; private: CQuestionStates m_questionStates; size_t m_currentQuestionIndex; }; }
#include <unordered_map> #include <iostream> void test0() { std::unordered_map<int, int> m{{1,1}, {2,2}, {3,3}}; for (auto& p : m) { std::cout << p.first << " " << p.second << std::endl; m.erase(p.first); } } int main() { test0(); return 0; }
#include <iostream> #include "Election.hh" using namespace std; /* Contructeurs */ Election::Election(std::vector<Personnage>& objet) { for(int i(0);i<Personnage::nbPerso ;i++) { objet[i].voter(); } } std:: string Election:: method()const { return "ok"; } /* Destructeur */ Election::~Election() { // } /* affichage chaîne de daractère */
#include "Truck.h" Truck::Truck() { weight = 30000; max_speed = 90; fuel_consumption = 27; passengers_number = 2; max_luggage = 0; max_volume = 50; carrying = 5000; } int Truck::count_comfort() { return 0; } std::string Truck::vehicle_name() { return truck; } void Truck::print(UserInterface* ui) { ui->vehicle_weight_ans(); std::cout << get_weight() << "\n"; ui->vehicle_max_speed_ans(); std::cout << get_max_speed() << "\n"; ui->vehicle_fuel_consumption_ans(); std::cout << get_fuel_consumption() << "\n";; ui->truck_carrying_ans(); std::cout << get_carrying() << "\n"; ui->volume_ans(); std::cout << get_max_volume() << "\n"; ui->passengers_ans(); std::cout << get_passengers_number() << "\n"; } double Truck::get_weight() const { return weight; } void Truck::set_weight(const double weight) { this->weight = weight; } double Truck::get_max_speed() const { return max_speed; } void Truck::set_max_speed(const double max_speed) { this->max_speed = max_speed; } double Truck::get_fuel_consumption() const { return fuel_consumption; } void Truck::set_fuel_consumption(const double fuel_consumption) { this->fuel_consumption = fuel_consumption; } int Truck::get_passengers_number() const { return passengers_number; } void Truck::set_passengers_number(const int passengers_number) { this->passengers_number = passengers_number; } double Truck::get_max_luggage() const { return max_luggage; } void Truck::set_max_luggage(const double max_luggage) { this->max_luggage = max_luggage; } double Truck::get_max_volume() const { return max_volume; } void Truck::set_max_volume(const double max_volume) { this->max_volume = max_volume; } double Truck::get_carrying() const { return carrying; } void Truck::set_carrying(const double carrying) { this->carrying = carrying; }
#include <string> #include "format.h" using std::string; // TODO: Complete this helper function // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS // REMOVE: [[maybe_unused]] once you define the function string Format::ElapsedTime(long seconds) { char buffer[10]; int HH = (int)(seconds/3600); int MM = ((int)(seconds/60))%60; int SS = (int)(seconds%60); sprintf(buffer, "%.2d:%.2d:%.2d", HH, MM, SS); return buffer; }
// Created on: 1994-08-31 // Created by: Jacques GOUSSARD // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Draft_FaceInfo_HeaderFile #define _Draft_FaceInfo_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <TopoDS_Face.hxx> class Geom_Surface; class Geom_Curve; class Draft_FaceInfo { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Draft_FaceInfo(); Standard_EXPORT Draft_FaceInfo(const Handle(Geom_Surface)& S, const Standard_Boolean HasNewGeometry); Standard_EXPORT void RootFace (const TopoDS_Face& F); Standard_EXPORT Standard_Boolean NewGeometry() const; Standard_EXPORT void Add (const TopoDS_Face& F); Standard_EXPORT const TopoDS_Face& FirstFace() const; Standard_EXPORT const TopoDS_Face& SecondFace() const; Standard_EXPORT const Handle(Geom_Surface)& Geometry() const; Standard_EXPORT Handle(Geom_Surface)& ChangeGeometry(); Standard_EXPORT const TopoDS_Face& RootFace() const; Standard_EXPORT Handle(Geom_Curve)& ChangeCurve(); Standard_EXPORT const Handle(Geom_Curve)& Curve() const; protected: private: Standard_Boolean myNewGeom; Handle(Geom_Surface) myGeom; TopoDS_Face myRootFace; TopoDS_Face myF1; TopoDS_Face myF2; Handle(Geom_Curve) myCurv; }; #endif // _Draft_FaceInfo_HeaderFile
#include "GameSeaquenceController.h" #include "SeaquenceController.h" #include "Ending.h" #include "Title.h" #include "State.h" #include "Ready.h" #include "GameOver.h" #include <sstream> GameSeaquenceController::GameSeaquenceController() :mState(0), mStageID(0), mNextSeaquence(NEXT_NONE), mGameSeaquence(0) { //Readyからスタート mGameSeaquence = new Ready(); mLife = 2; } GameSeaquenceController::~GameSeaquenceController() { Common::Delete(mState); Common::Delete(mGameSeaquence); } //各ゲームのシーケンスUpdateを動かして、シーケンスを取得、取得したシーケンスが次のシーケンスなら遷移処理 Boot* GameSeaquenceController::Update(GrandController*){ Boot* next = this; Boot* nextGameSeaquence = mGameSeaquence->Update(this); //遷移判定 if (nextGameSeaquence != mGameSeaquence){ GameSeaquence* casted = dynamic_cast<GameSeaquence*>(nextGameSeaquence); if (casted){ Common::Delete(mGameSeaquence); mGameSeaquence = casted; } else{ next = nextGameSeaquence; } casted = 0; } return next; } bool GameSeaquenceController::HasFinalStageCleard()const{ return(mStageID >= FINALSTAGE); } State* GameSeaquenceController::GetState(){ return mState; } void GameSeaquenceController::DrawStateGame()const{ mState->Draw(); } void GameSeaquenceController::StartLoading(){ //TODO:読み込みが重いのでリセットとかにするといい Common::Delete(mState); //ゲーム情報管理クラスを作る mState = new State(mStageID); } void GameSeaquenceController::GotoNextStage(){ ++mStageID; } int GameSeaquenceController::LifeNumber(){ return mLife; } void GameSeaquenceController::ReduceLife(){ --mLife; }
#ifndef INC_3PC_DEFINE_H #define INC_3PC_DEFINE_H #include <map> #define ROUND_TIME 10000 #define MIN_SLEEP_TIME 6000 #define MAX_SLEEP_TIME 7000 #define MIN_SLEEP_TIME_COORDINATOR 4000 #define MAX_SLEEP_TIME_COORDINATOR 5000 #define COORDINATOR_ID 0 #define MPI_CRASH_TAG 100 enum State : unsigned char { Q, W, A, P ,C }; const std::map<State, std::string> stateString = {{State::Q, "Q"}, {State::W, "W"}, {State::A, "A"}, {State::P, "P"}, {State::C, "C"}}; inline std::ostream& operator<< (std::ostream& os, State messageType) { return os << stateString.at(messageType); } inline std::string& operator+ (std::string& str, State messageType) { return str.append(stateString.at(messageType)); } namespace std { template<> struct hash<State> { inline int operator()(const State& state) const { return static_cast<std::underlying_type<State>::type>(state); } }; } enum class MessageType : unsigned char { PING, PONG, CRASH }; const std::map<MessageType, std::string> messageTypeString = {{MessageType::PING, "PING"}, {MessageType::PONG, "PONG"}, {MessageType::CRASH, "CRASH"}}; inline std::ostream& operator<< (std::ostream& os, MessageType messageType) { return os << messageTypeString.at(messageType); } inline std::string& operator+ (std::string& str, MessageType messageType) { return str.append(messageTypeString.at(messageType)); } namespace std { template<> struct hash<MessageType> { inline int operator()(const MessageType& messageType) const { return static_cast<std::underlying_type<MessageType>::type>(messageType); } }; } #endif //INC_3PC_DEFINE_H
#include "PiSBus.h" #include <unistd.h> #include <thread> int main(int argc, char *argv[]) { std::string port = argv[2]; PiSBus sbus(port); sbus.Begin(); std::thread write_to_ch(sbus.Write()); std::thread read_ch(sbus.Read()); return 0; }
// // Persona.cpp // Tarea3Ejercicio3 // // Created by Daniel on 07/10/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Persona.h" Persona::Persona(int i){ std::cout<<"Nombre: "; std::cin>>nombre; std::cout<<"Apellido: "; std::cin>>apellido; std::cout<<"Edad: "; std::cin>>edad; } std::ostream & operator <<(std::ostream & os, Persona p){ os << p.nombre <<" "<<p.apellido << " " << p.edad; return os; }
/*Tests for cc_shared::ScopedArray.*/ #include "cc/shared/scoped_array.h" #include "gtest/gtest.h" #include "cc/shared/count_destructors.h" namespace cc_shared { namespace { CountDestructors* test_template(int array_size, int* destructor_count, bool do_release) { CountDestructors* result = NULL; ScopedArray<CountDestructors> scoped_buffer( new(std::nothrow) CountDestructors [array_size]); RT_ASSERT(scoped_buffer.get()); RT_ASSERT_EQ(&(scoped_buffer[0]), scoped_buffer.get()); for (int i = 0; i < array_size; ++i) { scoped_buffer[i].set_counter(destructor_count); } if (do_release) { result = scoped_buffer.release(); } return result; } } // namespace TEST(ScopedArrayTest, test_destructor) { static const int kSize = 2; int destructor_count = 0; CountDestructors* result = NULL; { result = test_template(kSize, &destructor_count, false); } ASSERT_EQ(NULL, result); // Ensure every object in the scoped array had the destructor invoked // automatically. ASSERT_EQ(kSize, destructor_count); } TEST(ScopedArrayTest, test_release) { static const int kSize = 2; int destructor_count = 0; CountDestructors* result = NULL; { result = test_template(kSize, &destructor_count, true); } ASSERT_TRUE(NULL != result); ASSERT_EQ(0, destructor_count); delete [] result; // Ensure every object in the scoped array had the destructor invoked by the // explicit call. ASSERT_EQ(kSize, destructor_count); } } // cc_shared
#ifndef ACTIVITE_H #define ACTIVITE_H #include <QString> #include "timing.h" using namespace TIME; class Activite { //Ajout de statut aux activités ? /*! \class Activité * \brief Classe permettant de stocker des activités traditionnelles */ private: QString titre; /*!< Titre de l'activit*/ Duree duree; /*!< Durée de l'activité*/ public: //! Constructeur à partir de string et duree //! \param s QString& //! \param d Duree*/ Activite(const QString& s, const Duree d): titre(s), duree(d){}; //! Accesseur au titre de l'activité QString getTitre()const{return titre;}; //! Accesseur à la durée de l'activité Duree getDuree()const {return duree;}; }; #endif // ACTIVITE_H
/* Initial author: Convery (tcn@ayria.se) Started: 2019-08-04 License: MIT LAN Matchmaking-broadcasts over UDP. */ #pragma once #include <Stdinclude.hpp> namespace Matchmaking { struct Server_t { uint64_t SessionID; uint64_t Lastmessage; std::string Hostname; struct { uint32_t Terminated : 1; uint32_t Publicgame : 1; uint32_t Fullserver : 1; } Hostflags; nlohmann::json Gamedata{}; template<typename T> void Set(std::string &&Property, T Value) { Gamedata[Property] = Value; } template<typename T> T Get(std::string &&Property, T Defaultvalue) { return Gamedata.value(Property, Defaultvalue); } }; // Fetches the local server, or creates a new one. std::shared_ptr<Server_t> Localserver(); // A list of all currently active servers on the net. std::vector<std::shared_ptr<Server_t>> Externalservers(); // Listen for new broadcasted messages. std::thread Startlistening(uint32_t GameID); // Notify about our properties changing. void Broadcastupdate(); }
#ifndef _SHOTGUN_H #define _SHOTGUN_H #include "WeaponInfo.h" class Shotgun : public CWeaponInfo { public: Shotgun(GenericEntity::OBJECT_TYPE _bulletType); virtual ~Shotgun(); // Initialise this instance to default values void Init(void); //render weapon void Render(); // Discharge this weapon void Discharge(Vector3 position, Vector3 target); // Get mesh void Reload(); Mesh* GetMesh(); private: // generate bullet(num of bullet,dir) void generateBullet(Vector3 position, Vector3 target, const int numBullet = 1, const float angle = 10.f); }; #endif
/* * @lc app=leetcode.cn id=145 lang=cpp * * [145] 二叉树的后序遍历 */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<vector> #include<iostream> using namespace std; class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> path; dfs(root, path); return path; } void dfs(TreeNode* root, vector<int> &path) { if(root==NULL) return; dfs(root->left, path); dfs(root->right, path); path.push_back(root->val); } }; // @lc code=end
#ifndef SMITHERS #define SMITHERS #include "player.h" #include "game.h" #include "messages.h" #include <zmq.hpp> #include <json/json.h> #include <string> #include <vector> namespace smithers{ typedef std::vector<Player>::iterator players_it_t; typedef std::vector<Player>::const_iterator players_cit_t; class Smithers{ public: Smithers(); void await_registered_players(int max_players, int max_chips ); void play_game(); void play_tournament(); void publish_to_all(const std::string& message); void publish_to_all(const Json::Value& json); void print_players(); std::string create_new_game_message(); // Json::Value create_results_message(const std::vector<Result_t>& results); private: void play_betting_round(int first_to_play, int min_raise, int last_bet); Json::Value listen_and_pull_from_queue(const std::string& player_name); enum MoveType process_move(const Json::Value& move, Player&, int& min_raise, int& last_bet); std::vector<Player> m_players; int assign_seats(int dealer_seat); void reset_and_move_dealer_to_next_player(); int get_pot_value_for_game(); void transfer_round_bets_to_game_bets(); std::vector<Result_t> award_winnings(const std::vector<ScoredFiveCardsPair_t>& scored_hands); zmq::context_t m_zmq_context; zmq::socket_t m_publisher; }; } #endif
// Created on: 1993-11-18 // Created by: Yves FRICAUD // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _MAT2d_Circuit_HeaderFile #define _MAT2d_Circuit_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <MAT2d_DataMapOfIntegerConnexion.hxx> #include <MAT2d_DataMapOfBiIntSequenceOfInteger.hxx> #include <TColStd_SequenceOfInteger.hxx> #include <GeomAbs_JoinType.hxx> #include <Standard_Transient.hxx> #include <MAT2d_SequenceOfSequenceOfGeometry.hxx> #include <TColStd_SequenceOfBoolean.hxx> #include <Standard_Integer.hxx> #include <MAT2d_SequenceOfConnexion.hxx> class Geom2d_Geometry; class MAT2d_Connexion; class MAT2d_BiInt; class MAT2d_MiniPath; class MAT2d_Circuit; DEFINE_STANDARD_HANDLE(MAT2d_Circuit, Standard_Transient) //! Constructs a circuit on a set of lines. //! EquiCircuit gives a Circuit passing by all the lines //! in a set and all the connexions of the minipath associated. class MAT2d_Circuit : public Standard_Transient { public: Standard_EXPORT MAT2d_Circuit(const GeomAbs_JoinType aJoinType = GeomAbs_Arc, const Standard_Boolean IsOpenResult = Standard_False); Standard_EXPORT void Perform (MAT2d_SequenceOfSequenceOfGeometry& aFigure, const TColStd_SequenceOfBoolean& IsClosed, const Standard_Integer IndRefLine, const Standard_Boolean Trigo); //! Returns the Number of Items . Standard_EXPORT Standard_Integer NumberOfItems() const; //! Returns the item at position <Index> in <me>. Standard_EXPORT Handle(Geom2d_Geometry) Value (const Standard_Integer Index) const; //! Returns the number of items on the line <IndexLine>. Standard_EXPORT Standard_Integer LineLength (const Standard_Integer IndexLine) const; //! Returns the set of index of the items in <me>corresponding //! to the curve <IndCurve> on the line <IndLine> from the //! initial figure. Standard_EXPORT const TColStd_SequenceOfInteger& RefToEqui (const Standard_Integer IndLine, const Standard_Integer IndCurve) const; //! Returns the Connexion on the item <Index> in me. Standard_EXPORT Handle(MAT2d_Connexion) Connexion (const Standard_Integer Index) const; //! Returns <True> is there is a connexion on the item <Index> //! in <me>. Standard_EXPORT Standard_Boolean ConnexionOn (const Standard_Integer Index) const; DEFINE_STANDARD_RTTIEXT(MAT2d_Circuit,Standard_Transient) protected: private: Standard_EXPORT Standard_Boolean IsSharpCorner (const Handle(Geom2d_Geometry)& Geom1, const Handle(Geom2d_Geometry)& Geom2, const Standard_Real Direction) const; Standard_EXPORT Standard_Boolean PassByLast (const Handle(MAT2d_Connexion)& C1, const Handle(MAT2d_Connexion)& C2) const; Standard_EXPORT Standard_Real Side (const Handle(MAT2d_Connexion)& C, const TColGeom2d_SequenceOfGeometry& Line) const; Standard_EXPORT void UpDateLink (const Standard_Integer IFirst, const Standard_Integer ILine, const Standard_Integer ICurveFirst, const Standard_Integer ICurveLast); Standard_EXPORT void SortRefToEqui (const MAT2d_BiInt& aBiInt); Standard_EXPORT void InitOpen (TColGeom2d_SequenceOfGeometry& Line) const; Standard_EXPORT void InsertCorner (TColGeom2d_SequenceOfGeometry& Line) const; Standard_EXPORT void DoubleLine (TColGeom2d_SequenceOfGeometry& Line, MAT2d_SequenceOfConnexion& Connexions, const Handle(MAT2d_Connexion)& Father, const Standard_Real Side) const; Standard_EXPORT void ConstructCircuit (const MAT2d_SequenceOfSequenceOfGeometry& aFigure, const Standard_Integer IndRefLine, const MAT2d_MiniPath& aPath); Standard_Real direction; TColGeom2d_SequenceOfGeometry geomElements; MAT2d_DataMapOfIntegerConnexion connexionMap; MAT2d_DataMapOfBiIntSequenceOfInteger linkRefEqui; TColStd_SequenceOfInteger linesLength; GeomAbs_JoinType myJoinType; Standard_Boolean myIsOpenResult; }; #endif // _MAT2d_Circuit_HeaderFile
#include<bits/stdc++.h> #define FAST1 ios_base::sync_with_stdio(false); #define FAST2 cin.tie(NULL); using namespace std; #define pb push_back #define FOR(a, b) for (int i = (int) a; i < (int) b; i++) typedef long long ll; typedef pair<int, int> pii; int main() { FAST1; FAST2; int test_cases; cin>>test_cases; while(test_cases--){ int num; cin>>num; int priyamrendra[num]; double ans=0.0; for(int i=0;i<num;++i){ cin>>priyamrendra[i]; } sort(priyamrendra,priyamrendra+num,greater<int>()); int sum=0; for(int i=1;i<num;++i){ sum+=priyamrendra[i]; } ans+=(double)sum/(num-1); ans+=(double)priyamrendra[0]; cout<<fixed<<setprecision(9)<<ans<<endl; } return 0; }
#include <iostream> #include <bits/stdc++.h> #include <stack> using namespace std; /* Sample Input: 3 {[()]} {[(])} {{[[(())]]}} */ // Takes a string and checks if all the opening brackets have a corresponding closing bracket. Prints TRUE if the // brackets properly line up and FALSE if not. void check_line(string line) { const string f = "NO\n"; const string t = "YES\n"; stack< char > brackets; char it; for (int i = 0; i < line.size(); i++) { it = line[i]; if ((it == '[') || (it == '(') || (it == '{')) { brackets.push(it); } else { if (brackets.empty()) { cout << f; return; } if ((brackets.top() == '(') && (it == ')')) { brackets.pop(); } else if ((brackets.top() == '{') && (it == '}')) { brackets.pop(); } else if ((brackets.top() == '[') && (it == ']')) { brackets.pop(); } else { cout << f; return; } } } if (brackets.empty()) { cout << t; } else { cout << f; } } int main() { int t; cin >> t; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int t_itr = 0; t_itr < t; t_itr++) { string expression; getline(cin, expression); check_line(expression); } return 0; }
/** Program: wordTree.h Date: 01/18/2014 */ #ifndef __WORDTREE_H__ #define __WORDTREE_H__ #include <string> using namespace std; struct TNode { string word; // char* word; int count; TNode* left; TNode* right; }; class WordTree { public: WordTree (); ~WordTree (); bool isEmpty (); void insert (string word); void insert (TNode* node); TNode* getHead (); private: TNode *head; }; #endif
#ifndef STAGEDIALOG_H #define STAGEDIALOG_H #include <QDialog> namespace Ui { class stageDialog; } class stageDialog : public QDialog { Q_OBJECT public: explicit stageDialog(QWidget *parent = nullptr); ~stageDialog(); private: Ui::stageDialog *ui; }; #endif // STAGEDIALOG_H
#include <systemc.h> #include <fstream> #include <controller.h> #include <tester.h> using namespace std; int sc_main(int argc, char *argv[]) { sc_clock clk("clock", 10, SC_NS); sc_signal<bool> s_reset_n; sc_signal< sc_uint<2> > s_addr_in_1, s_addr_in_2, s_addr_out; sc_signal< sc_uint<3> > s_opcode; sc_signal<bool> s_sel_const; sc_signal< sc_bv<2> > s_sel_in_1, s_sel_in_2; sc_signal< sc_bv<3> > s_sel_op; sc_signal< sc_bv<4> > s_we_n; Controller module_ctrl("controller1"); module_ctrl.clk(clk); module_ctrl.reset_n(s_reset_n); module_ctrl.addr_in_1(s_addr_in_1); module_ctrl.addr_in_2(s_addr_in_2); module_ctrl.addr_out(s_addr_out); module_ctrl.opcode(s_opcode); module_ctrl.sel_const(s_sel_const); module_ctrl.sel_in_1(s_sel_in_1); module_ctrl.sel_in_2(s_sel_in_2); module_ctrl.sel_op(s_sel_op); module_ctrl.we_n(s_we_n); tester testbench("testbench1"); testbench.clk(clk); testbench.reset_n(s_reset_n); testbench.addr_in_1(s_addr_in_1); testbench.addr_in_2(s_addr_in_2); testbench.addr_out(s_addr_out); testbench.opcode(s_opcode); sc_trace_file *trace_file = sc_create_vcd_trace_file("test"); sc_trace(trace_file, clk, "clock"); sc_trace(trace_file, s_reset_n, "reset_n"); sc_trace(trace_file, s_addr_in_1, "addr_in_1"); sc_trace(trace_file, s_addr_in_2, "addr_in_2"); sc_trace(trace_file, s_addr_out, "addr_out"); sc_trace(trace_file, s_opcode, "opcode"); sc_trace(trace_file, s_sel_const, "sel_const"); sc_trace(trace_file, s_sel_in_1, "sel_in_1"); sc_trace(trace_file, s_sel_in_2, "sel_in_2"); sc_trace(trace_file, s_sel_op, "sel_op"); sc_trace(trace_file, s_we_n, "we_n"); sc_start(); return 0; }
#ifndef COMMON_INCLUDE_H #define COMMON_INCLUDE_H // ros #include <ros/ros.h> #include <sensor_msgs/Image.h> #include <geometry_msgs/PointStamped.h> #include <geometry_msgs/PoseStamped.h> #include <std_msgs/Empty.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/CameraInfo.h> // cv #include <cv_bridge/cv_bridge.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> //pcl #include <pcl_ros/point_cloud.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl_ros/point_cloud.h> //tf #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> // Eigen #include <Eigen/Core> #include <Eigen/Dense> //others #include <vector> #include <string> #include <iostream> #include <random> #include <boost/random/mersenne_twister.hpp> #include <boost/random/normal_distribution.hpp> #include <cmath> #endif
#include <iostream> #include <string> using namespace std; struct Person { string name; string address; int phone; }; int main() { Person person; cout << "Enter name: "; cin >> person.name; cout << "Enter address: "; cin >> person.address; cout << "Enter phone: "; cin >> person.phone; cout << "Person " << person.name << " lives at " << person.address << ". His/her phone number is: " << person.phone << endl; return 0; }
#include "JsonData.h" #include "EVWork.h" using namespace evwork; #define DEFAULT_PACKET_LIMIT 1024*1024*16 #define DEF_PRINT_INTERVAL 10 CJsonData::CJsonData() : m_uProc(0) , m_uPacketLimit(DEFAULT_PACKET_LIMIT) , m_uBytes64(0) { __initTimerPrint(); } CJsonData::~CJsonData() { __destroyTimerPrint(); } void CJsonData::setPacketLimit(uint32_t uLimit) { m_uPacketLimit = uLimit; } int CJsonData::onData(IConn* pConn, const char* pData, size_t uSize) { std::string strPeerIp = ""; uint16_t uPeerPort = 0; pConn->getPeerInfo(strPeerIp, uPeerPort); int nProcessed = 0; while (uSize > 0) { // 接收的数据没包头长,返回0 if (uSize < HEADER_SIZE) break; // 取报文长度 // 协议格式: 协议头 + 协议数据,其中协议头用4字节表明协议数据的长度 uint32_t uPktLen = Header::peekLen(pData); if ( m_uPacketLimit != (uint32_t)-1 && uPktLen > (m_uPacketLimit - HEADER_SIZE) ) { LOG(Warn, "[CJsonData::%s] from:%s:%u packet pktlen:%u > limit:%u", __FUNCTION__, strPeerIp.c_str(), uPeerPort, uPktLen + HEADER_SIZE, m_uPacketLimit); return -1; } // 接收的数据没达到包头指明的长度,返回0 if (uSize < HEADER_SIZE + uPktLen) break; { std::string strPacket(pData+HEADER_SIZE, uPktLen); Jpacket packet; if (packet.parse(strPacket) < 0) { LOG(Warn, "[CJsonData::%s] from:%s:%u recv a invalid packet, not json format", __FUNCTION__, strPeerIp.c_str(), uPeerPort); return -1; } // 匹配协议号进行处理 __requestDispatch(packet, pConn); } // 有可能客户端一次发送的了多条协议的数据,还需要继续处理下条协议 pData += (uPktLen + HEADER_SIZE); uSize -= (uPktLen + HEADER_SIZE); nProcessed += (int)(uPktLen + HEADER_SIZE); // 用于打印单位时间内CJsonData对象进行了多少次处理、处理了多少字节数据 // CJsonData构造函数中调用__initTimerPrint()设置定时器 m_uProc++; m_uBytes64 += (uPktLen + HEADER_SIZE); } return nProcessed; } void CJsonData::__requestDispatch(Jpacket& packet, IConn* pConn) { if (getAppContext()) { getAppContext()->RequestDispatch(packet, pConn); } } void CJsonData::__initTimerPrint() { m_evTimerPrint.data = this; ev_timer_init(&m_evTimerPrint, CJsonData::__cbTimerPrint, DEF_PRINT_INTERVAL, DEF_PRINT_INTERVAL); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerPrint); } void CJsonData::__destroyTimerPrint() { ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerPrint); } void CJsonData::__cbTimerPrint(struct ev_loop *loop, struct ev_timer *w, int revents) { CJsonData* pThis = (CJsonData*)w->data; LOG(Info, "[CJsonData::%s] proc:%u bytes:%llu", __FUNCTION__, pThis->m_uProc, pThis->m_uBytes64); // 重置统计值 pThis->m_uProc = 0; pThis->m_uBytes64 = 0; }
// Created on: 2015-08-10 // Created by: Ilya SEVRIKOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef StdPrs_BRepTextBuilder_Header #define StdPrs_BRepTextBuilder_Header #include <Font_BRepFont.hxx> #include <Font_TextFormatter.hxx> #include <gp_Ax3.hxx> //! Represents class for applying text formatting. class StdPrs_BRepTextBuilder { public: //! Render text as BRep shape. //! @param theFormatter formatter which defines aligned text //! @param thePenLoc start position and orientation on the baseline //! @return result shape with pen transformation applied as shape location Standard_EXPORT TopoDS_Shape Perform (StdPrs_BRepFont& theFont, const Handle(Font_TextFormatter)& theFormatter, const gp_Ax3& thePenLoc = gp_Ax3()); //! Render text as BRep shape. //! @param theString text in UTF-8 encoding //! @param thePenLoc start position and orientation on the baseline //! @param theHAlign horizontal alignment of the text //! @param theVAlign vertical alignment of the text //! @return result shape with pen transformation applied as shape location Standard_EXPORT TopoDS_Shape Perform (StdPrs_BRepFont& theFont, const NCollection_String& theString, const gp_Ax3& thePenLoc = gp_Ax3(), const Graphic3d_HorizontalTextAlignment theHAlign = Graphic3d_HTA_LEFT, const Graphic3d_VerticalTextAlignment theVAlign = Graphic3d_VTA_BOTTOM); protected: BRep_Builder myBuilder; }; #endif // StdPrs_BRepTextBuilder_Header
// Poker.h #ifndef POKER_H_ #define POKER_H_ #include <iostream> #include "Card.h" #include "Player.h" using namespace std; #endif /* POKER_H_ */
// Siva Sankar Kannan - 267605 - siva.kannan@student.tut.fi #include "fileread.h" #include "splitter.h" #include <iostream> #include <string> #include <vector> #include <fstream> #include <map> #include <algorithm> #include <utility> using namespace std; /*--------------------------------------------------------------------------------------*/ map <string, map<string, vector<product>>> read(const string& file_name) { // read the file and store the parsed data in a suitable datastructure // initialize necessary variables size_t char_check = 0; bool product_updated; string temp_string; product temp_struct; vector <product> temp_vector; map <string, vector <product>> temp_map; map <string, map<string, vector <product>>> read_map; ifstream file; vector <string> readvector; Splitter temp; string line; // try to open the file using try and catch not working // file.exceptions(ifstream::eofbit | ifstream::failbit | ifstream::badbit ); // try { // file.open(file_name); // } catch (exception const& e) { // cout << "\nError: The input file cannot be read."; // exit(0); // } // open the file file.open(file_name); /*----------------------------------------------------------------------------------*/ if (file.is_open()) { while (getline(file, line)) { readvector.push_back(line); // make sure the temp variables are all reset temp.reset(); temp_map.clear(); temp_struct = {}; product_updated = false; temp.set_string_to_split(line); temp.split(); readvector = temp.fields(); // check the read vector to make sure that it meets the format prescribed. /*---------------------------------------------------------------------------*/ size_t s = count(line.begin(), line.end(), ';'); size_t w = line.find(' '); // check if the read line has exactly 3 semicolons if (s != 3) { cout << "Error: the input file can not be read"; exit(0); } // check if the read line has any empty field if (temp.has_empty()) { cout << "Error: the input file can not be read"; exit(0); } // check if the read line has any white space character if (w != string::npos) { cout << "Error: the input file can not be read"; exit(0); } // check if we have an entry already and then enter the details. /*---------------------------------------------------------------------------*/ // check chains and add chain entries, if there are no // entries then make a new entry with an empty value auto chain_check = read_map.find(readvector[0]); if (chain_check == read_map.end()) { read_map[readvector[0]] = temp_map; } /*---------------------------------------------------------------------------*/ // check store in chain, if the store entry does not exist, // add the store entry with an empty vector as value auto store_check = read_map.at(readvector[0]).find(readvector[1]); if (store_check == read_map.at(readvector[0]).end()) { read_map.at(readvector[0])[readvector[1]] = temp_vector; } temp_struct.name = readvector[2]; // check if the last field is a double /*---------------------------------------------------------------------------*/ try { temp_struct.price = stod(readvector[3], &char_check); temp_string = readvector[3].substr(char_check); // check if the field has only floating point characters if (!temp_string.empty()) { cout << "Error: the input file can not be read"; exit(0); } } catch (const invalid_argument& e) { // exception is thrown when the last field does not start with // a floating point character cout << "Error: the input file can not be read"; exit(0); } /*---------------------------------------------------------------------------*/ // add product if new, else update price for (auto& prod : read_map.at(readvector[0]).at(readvector[1])) { if (prod.name == temp_struct.name) { prod.price = temp_struct.price; product_updated = true; } } // if the product does not exist, make a new entry with the given price if (!product_updated) read_map.at(readvector[0]).at(readvector[1]).push_back(temp_struct); } file.close(); } else { cout << "\nError: the input file can not be read"; exit(0); } return read_map; }
#include "SuperHero.h" class SuperHero : Person { SuperHero() { } ~SuperHero() { } void doFly() { printf("superhero is flying"); } void doInvisible() { printf("superhero is INvisible"); } };
// // Created by 钟奇龙 on 2019-04-15. // #include <iostream> using namespace std; class Node{ public: int data; Node* next; Node(int x):data(x),next(NULL){ } }; Node* listPartition(Node *head,int pivot){ Node *sH = NULL; Node *sT = NULL; Node *eH = NULL; Node *eT = NULL; Node *bH = NULL; Node *bT = NULL; while(head){ Node *next = head->next; if(head->data == pivot){ if(!eH){ eH = head; } else{ eT->next = head; } eT = head; }else if(head->data > pivot){ if(bH){ bH = head; }else{ bT->next = head; } bT = head; }else{ if(sH){ sH = head; }else{ sT->next = head; } sT = head; } } if(sT){ sT->next = eH; eT = eT == NULL ? sT:eT; } if(eT){ eT->next = bH; } return sH == NULL ? sH : eH == NULL ? bH:eH; }
#include "pyramid.h" #include "ui_pyramid.h" #include "image.h" #include <QPixmap> #include <QStandardPaths> #include <algorithm> Pyramid::Pyramid(QWidget *parent) : QMainWindow(parent), ui(new Ui::Pyramid) { ui->setupUi(this); } Pyramid::~Pyramid() { delete ui; } void Pyramid::onImageOpen() { const QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation), tr("Images (*.png *.jpg)")); if(!filename.isEmpty()) { QImage newImage(filename); if(newImage.isNull()) QMessageBox::information(this, QGuiApplication::applicationDisplayName(),tr("Cannot open the file")); else { images.push_back(std::make_unique<Image>(filename)); QString currentImageFileName(images.back()->getName()); ui->fileNameList->clear(); std::sort(images.begin(), images.end(), [](const std::unique_ptr<Image> &a, const std::unique_ptr<Image> &b) { return a->getImageDiagonal() < b->getImageDiagonal(); }); for(const auto &a: images) ui->fileNameList->addItem(a->getName()); ui->fileNameList->setCurrentIndex(ui->fileNameList->findText(currentImageFileName)); ui->layerList->setEnabled(true); ui->fileNameList->setEnabled(true); ui->scaleFactorSpinbox->setEnabled(true); ui->layerAddingButton->setEnabled(true); ui->layerList->setCurrentIndex(0); } } } void Pyramid::displayImageLayer(int layerNumber) { ui->imageLabel->setPixmap(QPixmap::fromImage(currentImage->getPyramidLayer(layerNumber))); ui->imageLabel->resize(currentImage->getSize()); ui->scrollAreaWidgetContents->resize(currentImage->getSize()); } void Pyramid::onLayerListIndexChanged(int index) { if(index > -1) displayImageLayer(index); } void Pyramid::onFileListIndexChanged(QString fileName) { if(ui->fileNameList->currentIndex() != -1) { currentImage = std::find_if(images.begin(), images.end(), [fileName](const std::unique_ptr<Image> &a) { return fileName == a->getName(); })->get(); displayImageLayer(0); ui->layerList->clear(); for(int i = 0; i < currentImage->getLayersNumber(); i++) ui->layerList->addItem(QString::number(i)); ui->layerList->setCurrentIndex(0); } } void Pyramid::onButtonAddingLayer() { currentImage->addCustomPyramidLayer(ui->scaleFactorSpinbox->value()); ui->layerList->addItem(QString::number(currentImage->getLayersNumber() - 1)); ui->layerList->setCurrentIndex(currentImage->getLayersNumber() - 1); }
#include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; double a; cin >> n >> a; double l = 0; double r = a; double b = 0; while (r - l > 0.005 / n) { double mid = l + (r - l) / 2; double v1 = a; double v2 = mid; for (int i = 2; i < n; i++) { double v3 = 2 * v2 - v1 + 2; if (v3 <= 0) { l = mid; break; } v1 = v2; v2 = v3; } if (l != mid) { r = mid; b = v2; } } printf("%.2f", b); return 0; }
// Created on: 1996-02-15 // Created by: Christian CAILLET // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Interface_STAT_HeaderFile #define _Interface_STAT_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Real.hxx> #include <TColStd_HSequenceOfAsciiString.hxx> #include <TColStd_HSequenceOfReal.hxx> #include <TColStd_HSequenceOfInteger.hxx> #include <Standard_Integer.hxx> class TCollection_HAsciiString; //! This class manages statistics to be queried asynchronously. //! Way of use : //! An operator describes a STAT form then fills it according to //! its progression. This produces a state of advancement of the //! process. This state can then be queried asynchronously : //! typically it is summarised as a percentage. There are also //! an identification of the current state, and information on //! processed volume. //! //! A STAT form can be described once for all (as static). //! It describes the stream of the process (see later), in terms //! of phases, cycles, steps, with estimated weights. But it //! brings no current data. //! //! One STAT at a time is active for filling and querying. It is //! used to control phasing, weighting ... Specific data for //! execution are given when running on active STAT : counts of //! items ... Data for query are then recorded and can be accessed //! at any time, asynchronously. //! //! A STAT is organised as follows : //! - it can be split into PHASES (by default, there is none, and //! all process takes place in one "default" phase) //! - each phase is identified by a name and is attached a weight //! -> the sum of the weights is used to compute relative weights //! - for each phase, or for the unique default phase if none : //! -- the process works on a list of ITEMS //! -- by default, all the items are processed in once //! -- but this list can be split into CYCLES, each one takes //! a sub-list : the weight of each cycle is related to its //! count of items //! -- a cycle can be split into STEPS, by default there are none //! then one "default step" is considered //! -- each step is attached a weight //! -> the sum of the weights of steps is used to compute relative //! weights of the steps in each cycle //! -> all the cycles of a phase have the same organisation //! //! Hence, when defining the STAT form, the phases have to be //! described. If no weight is precisely known, give 1. for all... //! No phase description will give only one "default" phase //! For each phase, a typical cycle can be described by its steps. //! Here too, for no weight precisely known, give 1. for all... //! //! For executing, activate a STAT to begin count. Give counts of //! items and cycles for the first phase (for the unique default //! one if no phasing is described) //! Else, give count of items and cycles for each new phase. //! Class methods allow also to set next cycle (given count of //! items), next step in cycle (if more then one), next item in //! step. class Interface_STAT { public: DEFINE_STANDARD_ALLOC //! Creates a STAT form. At start, one default phase is defined, //! with one default step. Then, it suffises to start with a //! count of items (and cycles if several) then record items, //! to have a queryable report. Standard_EXPORT Interface_STAT(const Standard_CString title = ""); //! used when starting Standard_EXPORT Interface_STAT(const Interface_STAT& other); //! Assignment Interface_STAT& operator= (const Interface_STAT& theOther) { theOther.Internals (thetitle, thetotal, thephnam, thephw, thephdeb,thephfin, thestw); return *this; } //! Returns fields in once, without copying them, used for copy //! when starting Standard_EXPORT void Internals (Handle(TCollection_HAsciiString)& tit, Standard_Real& total, Handle(TColStd_HSequenceOfAsciiString)& phn, Handle(TColStd_HSequenceOfReal)& phw, Handle(TColStd_HSequenceOfInteger)& phdeb, Handle(TColStd_HSequenceOfInteger)& phfin, Handle(TColStd_HSequenceOfReal)& stw) const; //! Adds a new phase to the description. //! The first one after Create replaces the default unique one Standard_EXPORT void AddPhase (const Standard_Real weight, const Standard_CString name = ""); //! Adds a new step for the last added phase, the default unique //! one if no AddPhase has already been added //! Warning : AddStep before the first AddPhase are cancelled Standard_EXPORT void AddStep (const Standard_Real weight = 1); //! Returns global description (cumulated weights of all phases, //! count of phases,1 for default, and title) Standard_EXPORT void Description (Standard_Integer& nbphases, Standard_Real& total, Standard_CString& title) const; //! Returns description of a phase, given its rank //! (n0 for first step, count of steps, default gives one; //! weight, name) Standard_EXPORT void Phase (const Standard_Integer num, Standard_Integer& n0step, Standard_Integer& nbstep, Standard_Real& weight, Standard_CString& name) const; //! Returns weight of a Step, related to the cumul given for the //! phase. //! <num> is given by <n0step> + i, i between 1 and <nbsteps> //! (default gives n0step < 0 then weight is one) Standard_EXPORT Standard_Real Step (const Standard_Integer num) const; //! Starts a STAT on its first phase (or its default one) //! <items> gives the total count of items, <cycles> the count of //! cycles //! If <cycles> is more than one, the first Cycle must then be //! started by NextCycle (NextStep/NextItem are ignored). //! If it is one, NextItem/NextStep can then be called Standard_EXPORT void Start (const Standard_Integer items, const Standard_Integer cycles = 1) const; //! Starts a default STAT, with no phase, no step, ready to just //! count items. //! <items> gives the total count of items //! Hence, NextItem is available to directly count Standard_EXPORT static void StartCount (const Standard_Integer items, const Standard_CString title = ""); //! Commands to resume the preceding phase and start a new one //! <items> and <cycles> as for Start, but for this new phase //! Ignored if count of phases is already passed //! If <cycles> is more than one, the first Cycle must then be //! started by NextCycle (NextStep/NextItem are ignored). //! If it is one, NextItem/NextStep can then be called Standard_EXPORT static void NextPhase (const Standard_Integer items, const Standard_Integer cycles = 1); //! Changes the parameters of the phase to start //! To be used before first counting (i.e. just after NextPhase) //! Can be used by an operator which has to reajust counts on run Standard_EXPORT static void SetPhase (const Standard_Integer items, const Standard_Integer cycles = 1); //! Commands to resume the preceding cycle and start a new one, //! with a count of items //! Ignored if count of cycles is already passed //! Then, first step is started (or default one) //! NextItem can be called for the first step, or NextStep to pass //! to the next one Standard_EXPORT static void NextCycle (const Standard_Integer items); //! Commands to resume the preceding step of the cycle //! Ignored if count of steps is already passed //! NextItem can be called for this step, NextStep passes to next Standard_EXPORT static void NextStep(); //! Commands to add an item in the current step of the current //! cycle of the current phase //! By default, one item per call, can be overpassed //! Ignored if count of items of this cycle is already passed Standard_EXPORT static void NextItem (const Standard_Integer nbitems = 1); //! Commands to declare the process ended (hence, advancement is //! forced to 100 %) Standard_EXPORT static void End(); //! Returns an identification of the STAT : //! <phase> True (D) : the name of the current phase //! <phase> False : the title of the current STAT Standard_EXPORT static Standard_CString Where (const Standard_Boolean phase = Standard_True); //! Returns the advancement as a percentage : //! <phase> True : inside the current phase //! <phase> False (D) : relative to the whole process Standard_EXPORT static Standard_Integer Percent (const Standard_Boolean phase = Standard_False); protected: private: Handle(TCollection_HAsciiString) thetitle; Standard_Real thetotal; Handle(TColStd_HSequenceOfAsciiString) thephnam; Handle(TColStd_HSequenceOfReal) thephw; Handle(TColStd_HSequenceOfInteger) thephdeb; Handle(TColStd_HSequenceOfInteger) thephfin; Handle(TColStd_HSequenceOfReal) thestw; }; #endif // _Interface_STAT_HeaderFile
#pragma once #include "linear_functional.hpp" namespace Time { template <typename WaveletBasis> class LinearForm { public: using ScalingBasis = typename FunctionTrait<WaveletBasis>::Scaling; LinearForm(std::unique_ptr<LinearFunctional<ScalingBasis>> functional) : functional_(std::move(functional)) {} template <typename I> void Apply(I *root); protected: std::unique_ptr<LinearFunctional<ScalingBasis>> functional_; std::vector<SparseIndices<WaveletBasis>> lvl_ind_out_; SparseIndices<WaveletBasis> empty_ind_out_; std::pair<SparseVector<ScalingBasis>, SparseVector<WaveletBasis>> ApplyRecur( size_t l, const SparseIndices<ScalingBasis> &Pi_out); std::pair<SparseIndices<ScalingBasis>, SparseIndices<ScalingBasis>> ConstructPiOut(const SparseIndices<ScalingBasis> &Pi_out); }; } // namespace Time #include "linear_form.ipp"
/** * @file AbstractManager.h * @brief 包含抽象类AbstractManager的定义 */ #ifndef ABSTRACTMANAGER_H #define ABSTRACTMANAGER_H #include <OgreCamera.h> #include <OgreSceneManager.h> #include <QObject> /**      *  @class AbstractManager Manager\AbstractManager.h   *  @brief 一个由其他管理器继承的管理器抽象类.   *   */ class AbstractManager : public QObject { Q_OBJECT ///<引入宏Q_OBJECT public: AbstractManager(QObject *parent = 0) : scenemgr_(NULL) {} ///<构造函数 virtual ~AbstractManager() {} ///<析构函数 virtual void Initialize(Ogre::SceneManager *scenemgr) {scenemgr_ = scenemgr;} ///<初始化函数 virtual void Update(double timesincelastframe) {} ///<更新函数 virtual void Update(Ogre::Camera *camera) {} ///<更新函数 public: Ogre::SceneManager *scenemgr_; ///<场景管理器指针 }; #endif
#include <stdio.h> // o pragma once serve para indicar o cabeçalho de pré // compilação. Não sei se entendi muito bem a sua funcionalidade // e talvez seja interessante marcar como DÚVIDA #pragma once // DÚVIDAAAA!!!!!!! // Vamos criar a classe Universidade, para associá-la // aos objetos do tipo Pessoa que criamos class Universidade { private: char nome[30]; public: Universidade(char* n=""); void setNome(char* n); char* getNome(); };
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- // // Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Patricia Aas // #ifndef __SERVER_CONTAINER_H__ #define __SERVER_CONTAINER_H__ #include "adjunct/desktop_util/handlers/DownloadManager.h" class ServerContainer : public DownloadManager::Container { public: // ------------------------- // Public member functions: // ------------------------- ServerContainer() : DownloadManager::Container() {} ServerContainer(OpString * server_name, OpBitmap * server_icon); ServerContainer(OpString * server_name, Image &server_icon); void Init(OpString * server_name, OpBitmap * server_icon); void Init(OpString * server_name, Image &server_icon); void Empty(); virtual ContainerType GetType() { return CONTAINER_TYPE_SERVER; } private: // ------------------------ // Private member functions: // ------------------------- // ------------------------- // Private member variables: // ------------------------- }; #endif //__SERVER_CONTAINER_H__
#include <chuffed/mip/mip.h> #include <chuffed/vars/int-var.h> #include <map> #include <sstream> // When set, branch variable (first_fail) and value (indomain_median, // indomain_split, indomain_reverse_split) specifications will count domain // sizes by the number of active values rather than the bounds (max-min). // (There is not too much penalty if INT_DOMAIN_LIST enabled in int-var.h). #define INT_BRANCH_HOLES 0 using namespace std; map<int, IntVar*> ic_map; extern std::map<IntVar*, std::string> intVarString; IntVar::IntVar(int _min, int _max) : var_id(engine.vars.size()), min(_min), max(_max), min0(_min), max0(_max), shadow_val(0), in_scip(false), all_in_scip(true), should_be_learnable(true), should_be_decidable(true), vals(nullptr), preferred_val(PV_MIN), activity(0), in_queue(false), sbps_value_selection(false), last_solution_value(-1) #ifdef HAS_VAR_IMPACT , impact(0.042), impact_count(0) #endif { assert(min_limit <= min && min <= max && max <= max_limit); engine.vars.push(this); changes = EVENT_C | EVENT_L | EVENT_U; if (isFixed()) { changes |= EVENT_F; } } // Allocate enough memory to specialise IntVar later using the same memory block IntVar* newIntVar(int min, int max) { size_t size = sizeof(IntVar); if (sizeof(IntVarEL) > size) { size = sizeof(IntVarEL); } if (sizeof(IntVarLL) > size) { size = sizeof(IntVarLL); } if (sizeof(IntVarSL) > size) { size = sizeof(IntVarSL); } void* mem = malloc(size); auto* var = new (mem) IntVar(min, max); return var; } IntVar* getConstant(int v) { auto it = ic_map.find(v); if (it != ic_map.end()) { return it->second; } IntVar* var = newIntVar(v, v); std::stringstream ss; ss << "constant_" << v; intVarString[var] = ss.str(); var->specialiseToEL(); ic_map.insert(pair<int, IntVar*>(v, var)); return var; } void IntVar::specialiseToEL() { switch (getType()) { case INT_VAR_EL: case INT_VAR_SL: return; case INT_VAR: new (this) IntVarEL(*((IntVar*)this)); break; default: NEVER; } } void IntVar::specialiseToLL() { switch (getType()) { case INT_VAR_EL: case INT_VAR_SL: return; case INT_VAR: new (this) IntVarLL(*((IntVar*)this)); break; default: NEVER; } } void IntVar::specialiseToSL(vec<int>& values) { if (getType() == INT_VAR_EL) { return; } if (getType() == INT_VAR_SL) { return; } assert(getType() == INT_VAR); vec<int> v = values; std::sort((int*)v, (int*)v + v.size()); int i; int j; for (i = j = 0; i < v.size(); i++) { if (i == 0 || v[i] != v[i - 1]) { v[j++] = v[i]; } } v.resize(j); if (min < v[0]) { min = v[0]; } if (max > v[v.size() - 1]) { max = v[v.size() - 1]; } // determine whether it is sparse or dense if (v.last() - v[0] >= v.size() * mylog2(v.size())) { // fprintf(stderr, "SL\n"); new (this) IntVarSL(*((IntVar*)this), v); } else { new (this) IntVarEL(*((IntVar*)this)); if (!allowSet(v)) { TL_FAIL(); } } } void IntVar::initVals(bool optional) { if (vals != nullptr) { return; } if (min == min_limit || max == max_limit) { if (optional) { return; } CHUFFED_ERROR("Cannot initialise vals in unbounded IntVar\n"); } vals = (Tchar*)malloc((max - min + 2) * sizeof(Tchar)); if (vals == nullptr) { perror("malloc()"); exit(1); } memset(vals, 1, max - min + 2); vals -= min; if (vals == nullptr) { vals++; // Hack to make vals != NULL whenever it's allocated } #if INT_DOMAIN_LIST vals_list = (Tint*)malloc(2 * (max - min) * sizeof(Tint)); if (!vals_list) { perror("malloc()"); exit(1); } vals_list -= 2 * min + 1; for (int i = min; i < max; ++i) { vals_list[2 * i + 1].v = i + 1; // forward link vals_list[2 * i + 2].v = i; // backward link from next value } vals_count.v = max + 1 - min; #endif } void IntVar::attach(Propagator* p, int pos, int eflags) { if (isFixed()) { p->wakeup(pos, eflags); } else { pinfo.push(PropInfo(p, pos, eflags)); } } void IntVar::wakePropagators() { for (int i = pinfo.size(); (i--) != 0;) { PropInfo& pi = pinfo[i]; if ((pi.eflags & changes) == 0) { continue; } if (pi.p->satisfied != 0) { continue; } if (pi.p == engine.last_prop) { continue; } pi.p->wakeup(pi.pos, changes); } clearPropState(); } int IntVar::simplifyWatches() { int i; int j; for (i = j = 0; i < pinfo.size(); i++) { if (pinfo[i].p->satisfied == 0) { pinfo[j++] = pinfo[i]; } } pinfo.resize(j); return j; } //----- // Branching stuff double IntVar::getScore(VarBranch vb) { switch (vb) { case VAR_MIN_MIN: return -min; case VAR_MIN_MAX: return min; case VAR_MAX_MIN: return -max; case VAR_MAX_MAX: return max; #if INT_BRANCH_HOLES // note slight inconsistency, if INT_BRANCH_HOLES=0 then we // use the domain size-1, same behaviour but more efficient? case VAR_SIZE_MIN: return vals ? -size() : min - (max + 1); case VAR_SIZE_MAX: return vals ? size() : max + 1 - min; #else case VAR_SIZE_MIN: return min - max; case VAR_SIZE_MAX: return max - min; #endif case VAR_DEGREE_MIN: return -pinfo.size(); case VAR_DEGREE_MAX: return pinfo.size(); case VAR_REDUCED_COST: return mip->getRC(this); case VAR_ACTIVITY: return activity; case VAR_REGRET_MIN_MAX: return isFixed() ? 0 : (vals != nullptr ? *++begin() - *begin() : 1); #ifdef HAS_VAR_IMPACT case VAR_IMPACT: return isFixed() ? 0 : impact; #endif default: NOT_SUPPORTED; } } DecInfo* IntVar::branch() { // vec<int> possible; // std::uniform_int_distribution<int> rnd_pos(0, possible.size() - 1); // for (int i = min; i <= max; i++) if (indomain(i)) possible.push(i); // return new DecInfo(this, possible[rnd_pos(engine.rnd)], 1); // Solution-based phase saving if (sbps_value_selection) { // Check if we can branch on last solution value if (indomain(last_solution_value)) { return new DecInfo(this, last_solution_value, 1); } } switch (preferred_val) { case PV_MIN: return new DecInfo(this, min, 1); case PV_MAX: return new DecInfo(this, max, 1); #if INT_BRANCH_HOLES // note slight inconsistency, if INT_BRANCH_HOLES=0 then we // round down rather than up (vice versa for PV_SPLIT_MAX), // should probably revisit this and make them consistent case PV_SPLIT_MIN: { if (!vals) return new DecInfo(this, min + (max - min) / 2, 3); int values = (size() - 1) / 2; iterator j = begin(); for (int i = 0; i < values; ++i) ++j; return new DecInfo(this, *j, 3); } case PV_SPLIT_MAX: { if (!vals) return new DecInfo(this, min + (max - min - 1) / 2, 2); int values = size() / 2; iterator j = begin(); for (int i = 0; i < values; ++i) ++j; return new DecInfo(this, *j, 2); } case PV_MEDIAN: { if (!vals) return new DecInfo(this, min + (max - min) / 2, 1); int values = (size() - 1) / 2; iterator j = begin(); for (int i = 0; i < values; ++i) ++j; return new DecInfo(this, *j, 1); } #else case PV_SPLIT_MIN: return new DecInfo(this, min + (max - min - 1) / 2, 3); case PV_SPLIT_MAX: return new DecInfo(this, min + (max - min) / 2, 2); case PV_MEDIAN: if (vals == nullptr) { CHUFFED_ERROR("Median value selection is not supported this variable.\n"); } else { int values = (size() - 1) / 2; iterator j = begin(); for (int i = 0; i < values; ++i) { ++j; } return new DecInfo(this, *j, 1); } #endif default: NEVER; } } //----- // Domain change stuff #if !INT_DOMAIN_LIST inline void IntVar::updateMin() { int v = min; if (vals[v] == 0) { while (vals[v] == 0) { v++; } min = v; changes |= EVENT_C | EVENT_L; } } inline void IntVar::updateMax() { int v = max; if (vals[v] == 0) { while (vals[v] == 0) { v--; } max = v; changes |= EVENT_C | EVENT_U; } } #endif inline void IntVar::updateFixed() { if (isFixed()) { changes |= EVENT_F; } } bool IntVar::setMin(int64_t v, Reason r, bool channel) { assert(setMinNotR(v)); if (v > max) { return false; } #if INT_DOMAIN_LIST if (vals) { int i; int j = vals_count; for (i = min; i < v; i = vals_list[2 * i + 1]) --j; min = i; vals_count = j; } else min = v; changes |= EVENT_C | EVENT_L; #else min = v; changes |= EVENT_C | EVENT_L; if (vals != nullptr) { updateMin(); } #endif updateFixed(); pushInQueue(); return true; } bool IntVar::setMax(int64_t v, Reason r, bool channel) { assert(setMaxNotR(v)); if (v < min) { return false; } #if INT_DOMAIN_LIST if (vals) { int i; int j = vals_count; for (i = max; i > v; i = vals_list[2 * i]) --j; max = i; vals_count = j; } else max = v; changes |= EVENT_C | EVENT_U; #else max = v; changes |= EVENT_C | EVENT_U; if (vals != nullptr) { updateMax(); } #endif updateFixed(); pushInQueue(); return true; } bool IntVar::setVal(int64_t v, Reason r, bool channel) { assert(setValNotR(v)); if (!indomain(v)) { return false; } if (min < v) { min = v; changes |= EVENT_C | EVENT_L | EVENT_F; } if (max > v) { max = v; changes |= EVENT_C | EVENT_U | EVENT_F; } #if INT_DOMAIN_LIST if (vals) vals_count = 1; #endif pushInQueue(); return true; } bool IntVar::remVal(int64_t v, Reason r, bool channel) { assert(remValNotR(v)); if (isFixed()) { return false; } if (vals == nullptr) { if (!engine.finished_init) { NEVER; } return true; } #if INT_DOMAIN_LIST if (v == min) { min = vals_list[2 * min + 1]; changes |= EVENT_C | EVENT_L; } else if (v == max) { max = vals_list[2 * max]; changes |= EVENT_C | EVENT_U; } else { vals[v] = 0; vals_list[vals_list[2 * v] * 2 + 1] = vals_list[2 * v + 1]; vals_list[vals_list[2 * v + 1] * 2] = vals_list[2 * v]; changes |= EVENT_C; } --vals_count; #else vals[v] = 0; changes |= EVENT_C; updateMin(); updateMax(); #endif updateFixed(); pushInQueue(); return true; } // Assumes v is sorted bool IntVar::allowSet(vec<int>& v, Reason r, bool channel) { initVals(); if ((vals == nullptr) && !engine.finished_init) { NOT_SUPPORTED; } int i = 0; int m = min; while (i < v.size() && v[i] < m) { i++; } for (; i < v.size(); i++) { for (; m < v[i]; m++) { if (m > max) { return true; } if (remValNotR(m)) { if (!remVal(m, r, channel)) { return false; } } } m = v[i] + 1; } for (; m <= max; m++) { if (remValNotR(m)) { if (!remVal(m, r, channel)) { return false; } } } return true; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "11479" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int kase; scanf("%d",&kase); int Case = 1; long long tri[5]; while( kase-- ){ scanf("%lld %lld %lld",&tri[0],&tri[1],&tri[2]); sort(&tri[0],&tri[3]); printf("Case %d: ",Case++ ); if( tri[0]+tri[1] > tri[2] ){ if( tri[0] == tri[1] && tri[1] == tri[2] ) printf("Equilateral\n"); else if( tri[0] == tri[1] || tri[1] == tri[2] ) printf("Isosceles\n"); else printf("Scalene\n"); } else printf("Invalid\n"); } return 0; }
#include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int main(const int argc, const char* const argv[]){ int rc = 0; if (argc < 1){ cerr << "Error: Unable to compute standard deviations over data set because of insufficient data" << endl; return -1; } for (int i = 1; i < argc-1; i++){ float num = atof(argv[i]); if (num > 150){ cout << "Warning: invalid voltage reading: " << num << " ignored in calculation" << endl; rc = 1; } else if (num < 0){ cout << "Warning invalid voltage reading: " << num << " ignored in calculation" << endl; rc = 1; } } int valid = 0; for (int i = 1; i < argc-1; i++){ float num = atof(argv[i]); if((num > 0)&&(num < 150)){ valid++; } } if(valid == 0){ cerr << "Error: Unable to compute standard deviations over data set because there are no valid readings" << endl; return -1; } for (int i = 1; i < argc-1 ; i++){ if(atof(argv[argc - 1]) >= 0){ cerr << "Error: Unable to compute standard deviations over data set because there is no negative terminator" << endl; return -1; } } //Note that you MUST have a counter for your number of objects in your array. In this case, our counter will be the int value count. int count = 0; float sum; for (int i = 1; i < argc-1; i++){ float num = atof(argv[i]); if((num > 0)&&(num < 150)){ count++; sum += num; } } float avg = sum / count; float diff; float square; float total; for (int i =1; i < argc-1; i++){ float num = atof(argv[i]); if((num > 0)&&(num < 150)){ diff = num - avg; square = (diff*diff); total += square; } } float bpsd = (total/count); float psd = sqrt(bpsd); float element = (count-1); float bssd = (total/(element)); float ssd = sqrt(bssd); cout << "Number of voltage readings: " << count << endl; cout << "Population standard deviation: " << psd << endl; if ((element == 0)&&(total == 0)){ cout << "Sample standard deviation: undefined" << endl; } else if(element == 0){ cout << "Sample standard deviation: infinity" << endl; } else{ cout << "Sample standard deviation: " << ssd << endl; } return rc; }
#include<iostream> using namespace std; void swap(int *p, int *q){ int temp = *p; *p = *q; *q = temp; } void displayArray(int arr[], int size){ for(int i=0; i<size; i++){ cout << arr[i] << " "; } cout << endl; } void selectionSort(int arr[], int size){ int minIndex, i, j; for(i=0; i<size; i++){ minIndex = i; for(j=i+1; j<size; j++){ if(arr[j] < arr[minIndex]) minIndex = j; } swap(&arr[minIndex], &arr[i]); } } void insertionSort(int arr[], int size){ int key, i, j; for(i=1; i<size; i++){ key = arr[i]; j = i-1; while(j>=0 && arr[j]>key){ arr[j+1] = arr[j]; j--; } arr[j=1] = key; } } int main(){ int size; cout << "Enter the size of the Array: "; cin >> size; int arr[size]; cout << "Enter the array Elements: " << endl; for(int i=0; i<size; i++){ cin >> arr[i]; } cout << "Array After selection Sort: " << endl; selectionSort(arr, size); displayArray(arr, size); return 0; }
// iterative class Solution { public: vector<string> findItinerary(vector<pair<string, string>> tickets) { unordered_map<string, multiset<string>> ngb; for(auto ticket: tickets){ ngb[ticket.first].insert(ticket.second); } vector<string> res; stack<string> path; path.push("JFK"); while(!path.empty()){ string start = path.top(); if(ngb[start].empty()){ path.pop(); res.push_back(start); }else{ path.push(*ngb[start].begin()); ngb[start].erase(ngb[start].begin()); } } reverse(res.begin(),res.end()); return res; } }; //recursive class Solution { public: void dfs(const string& start, unordered_map<string, multiset<string>>& ngb, vector<string>& path){ while(!ngb[start].empty()){ string end = *(ngb[start].begin()); ngb[start].erase(ngb[start].begin()); dfs(end, ngb, path); } path.push_back(start); } vector<string> findItinerary(vector<pair<string, string>> tickets) { unordered_map<string, multiset<string>> ngb; for(auto ticket: tickets){ ngb[ticket.first].insert(ticket.second); } vector<string> path; string start = "JFK"; dfs(start, ngb, path); reverse(path.begin(), path.end()); return path; } };
#include "MoveComponent.h" #include "Actor.h" #include <iostream> MoveComponent::MoveComponent(class Actor* owner, int updateOrder) :Component(owner, updateOrder), mAngularSpeed(0.0f), mForwardSpeed(0.0f), mMass(0.0f), mVelocity(Vector2(0.0f, 0.0f)) { } void MoveComponent::Update(float deltaTime) { if (!Math::NearZero(mAngularSpeed)) { float rot = mOwner->GetRotation(); rot += mAngularSpeed * deltaTime; mOwner->SetRotation(rot); } if (!Math::NearZero(mForwardSpeed)) { Vector2 pos = mOwner->GetPosition(); pos += mOwner->GetForward() * mForwardSpeed * deltaTime; if (pos.x < 0.0f) { pos.x = 1022.0f; } else if (pos.x > 1024.0f) { pos.x = 2.0f; } if (pos.y < 0.0f) { pos.y = 766.0f; } else if (pos.y > 768.0f) { pos.y = 2.0f; } mOwner->SetPosition(pos); } Vector2 sumOfForce = Vector2(0.0f, 0.0f); // Calculate constant force for (auto iter = mForces.begin(); iter != mForces.end(); ++iter) { sumOfForce += *iter; } // Calculate impulse force for (auto iter = mImpulses.begin(); iter != mImpulses.end(); ++iter) { sumOfForce += *iter; } mImpulses.clear(); std::cout << "the sum of force is: " << sumOfForce.x << sumOfForce.y << std::endl; if (mMass > 0.0f) { // Euler Integration Vector2 acceleration = Vector2(sumOfForce.x / mMass, sumOfForce.y / mMass) ; // Update velocity mVelocity += acceleration * deltaTime; // Update position Vector2 pos = mOwner->GetPosition(); pos += mVelocity * deltaTime; if (pos.x < 0.0f) { pos.x = 1022.0f; } else if (pos.x > 1024.0f) { pos.x = 2.0f; } if (pos.y < 0.0f) { pos.y = 766.0f; } else if (pos.y > 768.0f) { pos.y = 2.0f; } mOwner->SetPosition(pos); } }
#include "RenderTextSample.h" #include "EverydayTools/Delegate.h" #include "EverydayTools/Array/ArrayViewVector.h" #include "EverydayTools/Exception/CheckedCast.h" #include "Keng/Base/Serialization/SerializeMandatory.h" #include "Keng/Base/Serialization/openarchivejson.h" #include "Keng/Core/IApplication.h" #include "Keng/Core/SystemEvent.h" #include "Keng/FileSystem/OpenFileParameters.h" #include "Keng/FileSystem/ReadFileToBuffer.h" #include "Keng/Graphics/IDevice.h" #include "Keng/Graphics/Resource/Font/IFont.h" #include "Keng/Graphics/Resource/Font/GlyphInfo.h" #include "Keng/Graphics/Resource/Font/GlyphParameters.h" #include "Keng/Graphics/Resource/ITexture.h" #include "Keng/Graphics/Resource/IEffect.h" #include "Keng/GraphicsCommon/DepthStencilClearFlags.h" #include "Keng/GPU/DeviceBufferMapper.h" #include "Keng/GPU/PipelineInput/ISampler.h" #include "Keng/GPU/RenderTarget/IWindowRenderTarget.h" #include "Keng/GPU/RenderTarget/ITextureRenderTarget.h" #include "Keng/GPU/RenderTarget/IDepthStencil.h" #include "Keng/GPU/ScopedAnnotation.h" #include "Keng/GraphicsCommon/DepthStencilParameters.h" #include "Keng/GraphicsCommon/ViewportParameters.h" #include "Keng/GraphicsCommon/WindowRenderTargetParameters.h" #include "Keng/GraphicsCommon/SamplerParameters.h" #include "Keng/GraphicsCommon/DeviceTextureParameters.h" #include "Keng/GraphicsCommon/TextureRenderTargetParameters.h" #include "Keng/WindowSystem/IWindow.h" namespace render_text_sample { namespace { struct CB { edt::geom::Matrix<float, 4, 4> transform; }; template<typename T> edt::geom::Matrix<T, 4, 4> MakeIdentityMatrix() { edt::geom::Matrix<T, 4, 4> m{}; m.At(0, 0) = T(1); m.At(1, 1) = T(1); m.At(2, 2) = T(1); m.At(3, 3) = T(1); return m; } template<typename T> edt::geom::Matrix<T, 4, 4> MakeTranslationMatrix(edt::geom::Vector<T, 3> vec) { auto m = MakeIdentityMatrix<T>(); m.At(3, 0) = vec.Elem(0); m.At(3, 1) = vec.Elem(1); m.At(3, 2) = vec.Elem(2); return m; } } RenderTextSample::RenderTextSample() = default; RenderTextSample::~RenderTextSample() = default; bool RenderTextSample::Update() { using namespace keng; using namespace graphics; return CallAndRethrowM + [&] { return Annotate(m_annotation, L"Frame", [&] { auto api_device = GetSystem<graphics::IGraphicsSystem>().GetDevice()->GetApiDevice(); float clearColor[4]{ 0.0f, 0.2f, 0.4f, 1.0f }; static float angle = 0.f; constexpr float delta_angle = 0.0003f; angle += delta_angle; Annotate(m_annotation, L"Draw", [&] { Annotate(m_annotation, L"Clear", [&] { m_windowRT->Clear(clearColor); m_depthStencil->Clear(DepthStencilClearFlags::ClearDepth | DepthStencilClearFlags::ClearStencil, 1.0f, 0); m_windowRT->AssignToPipeline(m_depthStencil); }); Annotate(m_annotation, L"Draw quad", [&] { Annotate(m_annotation, L"Edit constant buffer", [&] { gpu::DeviceBufferMapper mapper; m_constantBuffer->MakeMapper(mapper); auto cbView = mapper.GetTypedView<CB>(); edt::geom::Vector<float, 3> t{}; t.rx() = std::sin(angle); t.ry() = std::sin(angle); cbView[0].transform = MakeTranslationMatrix(t); }); Annotate(m_annotation, L"Assign buffers", [&] { m_containerQuad.AssignToPipeline(0, GetSystem<graphics::IGraphicsSystem>()); gpu::ConstantBufferAssignParameters cbAssignParams{}; cbAssignParams.slot = 0; cbAssignParams.stride = sizeof(CB); cbAssignParams.shaderType = ShaderType::Vertex; m_constantBuffer->AssignToPipeline(cbAssignParams); }); Annotate(m_annotation, L"Setup effect", [&] { m_texturedEffect->AssignToPipeline(); m_containerSampler->AssignToPipeline(ShaderType::Fragment, 0); m_containerTexture->GetApiTexture()->AssignToPipeline(ShaderType::Fragment, 0); }); api_device->Draw(m_containerQuad.GetVerticesCount(), 0); }); m_depthStencil->Clear(DepthStencilClearFlags::ClearDepth | DepthStencilClearFlags::ClearStencil, 1.0f, 0); Annotate(m_annotation, L"Draw text", [&] { Annotate(m_annotation, L"Edit constant buffer", [&] { gpu::DeviceBufferMapper mapper; m_constantBuffer->MakeMapper(mapper); auto cbView = mapper.GetTypedView<CB>(); cbView[0].transform = MakeIdentityMatrix<float>(); }); Annotate(m_annotation, L"Assign buffers", [&] { m_textQuads.AssignToPipeline(0, GetSystem<graphics::IGraphicsSystem>()); gpu::ConstantBufferAssignParameters cbAssignParams{}; cbAssignParams.slot = 0; cbAssignParams.stride = sizeof(CB); cbAssignParams.shaderType = ShaderType::Vertex; m_constantBuffer->AssignToPipeline(cbAssignParams); }); Annotate(m_annotation, L"Setup effect", [&] { m_textEffect->AssignToPipeline(); m_textSampler->AssignToPipeline(ShaderType::Fragment, 0); m_atlasTexture->GetApiTexture()->AssignToPipeline(ShaderType::Fragment, 0); }); api_device->Draw(m_textQuads.GetVerticesCount(), 0); }); }); m_windowRT->Present(); return true; }); }; } void RenderTextSample::Initialize(const keng::core::IApplicationPtr& app) { using namespace keng; using namespace graphics; using namespace resource; using namespace window_system; CallAndRethrowM + [&] { StoreDependencies(*app); auto device = GetSystem<graphics::IGraphicsSystem>().GetDevice(); auto api_device = device->GetApiDevice(); m_annotation = api_device->CreateAnnotation(); auto window = GetSystem<window_system::IWindowSystem>().GetWindow(); size_t w, h; window->GetClientSize(&w, &h); {// Initialize viewport ViewportParameters v{}; v.Position.rx() = 0.f; v.Position.ry() = 0.f; v.Size.rx() = edt::CheckedCast<float>(w); v.Size.ry() = edt::CheckedCast<float>(h); api_device->SetViewport(v); } {// Create window render target WindowRenderTargetParameters window_rt_params; window_rt_params.swapChain.format = FragmentFormat::R8_G8_B8_A8_UNORM; window_rt_params.swapChain.buffers = 2; m_windowRT = api_device->CreateWindowRenderTarget(window_rt_params, *window); } {// Create depth stencil DepthStencilParameters depthStencilParams{}; DeviceTextureParameters dsTextureParams{}; dsTextureParams.format = FragmentFormat::R24_G8_TYPELESS; dsTextureParams.width = w; dsTextureParams.height = h; dsTextureParams.bindFlags = DeviceBufferBindFlags::ShaderResource | DeviceBufferBindFlags::DepthStencil; depthStencilParams.format = FragmentFormat::D24_UNORM_S8_UINT; auto depthStencilTexture = GetSystem<graphics::IGraphicsSystem>().CreateTexture(dsTextureParams)->GetApiTexture(); m_depthStencil = api_device->CreateDepthStencil(depthStencilParams, *depthStencilTexture); } m_containerTexture = std::static_pointer_cast<ITexture>(GetSystem<resource::IResourceSystem>().GetResource("Assets/Textures/container.json", device)); m_font = std::static_pointer_cast<IFont>(GetSystem<resource::IResourceSystem>().GetResource("Assets/Fonts/OpenSans.json")); {// Read and compile shaders std::string_view effectName = "Assets/Effects/Textured.json"; m_texturedEffect = std::static_pointer_cast<IEffect>(GetSystem<resource::IResourceSystem>().GetResource(effectName.data(), device)); m_texturedEffect->InitDefaultInputLayout(); } {// Read and compile shaders std::string_view effectName = "Assets/Effects/Text.json"; m_textEffect = std::static_pointer_cast<IEffect>(GetSystem<resource::IResourceSystem>().GetResource(effectName.data(), device)); m_textEffect->InitDefaultInputLayout(); } {// Create container vertex buffer Vertex vertices[4]; // POSITION //// TEXTURE COORDS /**/ ///////////////////////////////////////////////////////////////////// vertices[0].pos.rx() = -0.50f; /**/ vertices[0].tex.rx() = 0.0f; /**/ vertices[0].pos.ry() = -0.50f; /**/ vertices[0].tex.ry() = 1.0f; /**/ vertices[0].pos.rz() = +0.00f; /**/ /**/ vertices[0].pos.rw() = +1.00f; /**/ /**/ ///////////////////////////////////////////////////////////////////// vertices[1].pos.rx() = -0.50f; /**/ vertices[1].tex.rx() = 0.0f; /**/ vertices[1].pos.ry() = +0.50f; /**/ vertices[1].tex.ry() = 0.0f; /**/ vertices[1].pos.rz() = +0.00f; /**/ /**/ vertices[1].pos.rw() = +1.00f; /**/ /**/ ///////////////////////////////////////////////////////////////////// vertices[2].pos.rx() = +0.50f; /**/ vertices[2].tex.rx() = 1.0f; /**/ vertices[2].pos.ry() = -0.50f; /**/ vertices[2].tex.ry() = 1.0f; /**/ vertices[2].pos.rz() = +0.00f; /**/ /**/ vertices[2].pos.rw() = +1.00f; /**/ /**/ ///////////////////////////////////////////////////////////////////// vertices[3].pos.rx() = +0.50f; /**/ vertices[3].tex.rx() = 1.0f; /**/ vertices[3].pos.ry() = +0.50f; /**/ vertices[3].tex.ry() = 0.0f; /**/ vertices[3].pos.rz() = +0.00f; /**/ /**/ vertices[3].pos.rw() = +1.00f; /**/ /**/ ///////////////////////////////////////////////////////////////////// PrimitiveBufferParameters params; params.usage = DeviceBufferUsage::Dynamic; params.bindFlags = DeviceBufferBindFlags::VertexBuffer; params.accessFlags = CpuAccessFlags::Write; params.topology = PrimitiveTopology::TriangleStrip; m_containerQuad.Initialize(GetSystem<graphics::IGraphicsSystem>(), params, edt::MakeArrayView(vertices)); } {// Create text vertex buffer GlyphParameters glyphParams{}; glyphParams.size = 20; glyphParams.dpiX = 300; glyphParams.dpiY = 300; std::vector<uint32_t> unicodes; for (char letter : "The quick brown fox jumps over the lazy dog") { unicodes.push_back(letter); } std::vector<Vertex> vertices; vertices.reserve(unicodes.size()); {// Generate triangles per symbol int currentX = - static_cast<int>(w); int currentY = 0; auto onRequest = [&](const AtlasGlyphInfo& info) { m_atlasTexture = info.texture; auto x0 = edt::CheckedCast<float>(currentX) + info.horizontalBearingX; auto x1 = x0 + info.width; auto y0 = edt::CheckedCast<float>(currentY) - edt::CheckedCast<float>(info.height - info.horizontalBearingY); auto y1 = y0 + info.height; auto tx0 = edt::CheckedCast<float>(info.x); auto tx1 = tx0 + info.width; auto ty0 = edt::CheckedCast<float>(info.y); auto ty1 = ty0 + info.height; Vertex q[4]; q[0].pos.rx() = x0; q[0].pos.ry() = y0; q[0].tex.rx() = tx0; q[0].tex.ry() = ty1; q[1].pos.rx() = x1; q[1].pos.ry() = y0; q[1].tex.rx() = tx1; q[1].tex.ry() = ty1; q[2].pos.rx() = x1; q[2].pos.ry() = y1; q[2].tex.rx() = tx1; q[2].tex.ry() = ty0; q[3].pos.rx() = x0; q[3].pos.ry() = y1; q[3].tex.rx() = tx0; q[3].tex.ry() = ty0; {// Normalize coordinates // Atlas size shortcuts auto aw = info.texture->GetApiTexture()->GetWidth(); auto ah = info.texture->GetApiTexture()->GetHeight(); for (auto& v : q) { v.pos.rx() /= w; v.pos.ry() /= h; v.pos.rz() = 1.0f; v.pos.rw() = 1.0f; v.tex.rx() /= aw; v.tex.ry() /= ah; } } vertices.push_back(q[1]); vertices.push_back(q[0]); vertices.push_back(q[3]); vertices.push_back(q[2]); vertices.push_back(q[1]); vertices.push_back(q[3]); currentX += edt::CheckedCast<int>(info.advanceX); }; edt::Delegate<void(const AtlasGlyphInfo&)> delegate; delegate.Bind(onRequest); m_font->RequestGlyphsInfo(edt::MakeArrayView(unicodes), *device, glyphParams, delegate); } PrimitiveBufferParameters params; params.usage = DeviceBufferUsage::Dynamic; params.bindFlags = DeviceBufferBindFlags::VertexBuffer; params.accessFlags = CpuAccessFlags::Write; params.topology = PrimitiveTopology::TriangleList; m_textQuads.Initialize(GetSystem<graphics::IGraphicsSystem>(), params, edt::MakeArrayView(vertices)); } {// Create common constant buffer CB constantBufferInitData; edt::geom::Vector<float, 3> t {}; constantBufferInitData.transform = MakeTranslationMatrix(t); DeviceBufferParameters params{}; params.size = sizeof(constantBufferInitData); params.usage = DeviceBufferUsage::Dynamic; params.bindFlags = DeviceBufferBindFlags::ConstantBuffer; params.accessFlags = CpuAccessFlags::Write; m_constantBuffer = api_device->CreateDeviceBuffer(params, edt::DenseArrayView<uint8_t>((uint8_t*)&constantBufferInitData, sizeof(constantBufferInitData))); } {// Create container sampler SamplerParameters samplerParams{}; samplerParams.addressU = TextureAddressMode::Clamp; samplerParams.addressV = TextureAddressMode::Clamp; samplerParams.addressW = TextureAddressMode::Clamp; samplerParams.filter = FilteringMode::Anisotropic; m_containerSampler = api_device->CreateSampler(samplerParams); } {// Create text sampler SamplerParameters samplerParams{}; samplerParams.addressU = TextureAddressMode::Clamp; samplerParams.addressV = TextureAddressMode::Clamp; samplerParams.addressW = TextureAddressMode::Clamp; samplerParams.filter = FilteringMode::Bilinear; m_textSampler = api_device->CreateSampler(samplerParams); } LoadParameters(app); }; } class SystemParams { public: void serialize(yasli::Archive& ar) { ar(vSync, "vSync"); } bool vSync = false; }; void RenderTextSample::OnSystemEvent(const keng::core::IApplicationPtr& app, const keng::core::SystemEvent& e) { return CallAndRethrowM + [&] { switch (e) { case keng::core::SystemEvent::Initialize: Initialize(app); break; case keng::core::SystemEvent::Update: Update(); break; } }; } void RenderTextSample::LoadParameters(const keng::core::IApplicationPtr& app) { CallAndRethrowM + [&] { using namespace keng; using namespace filesystem; SystemParams params; try { filesystem::OpenFileParameters fileParams; fileParams.accessFlags = FileAccessFlags::Read; std::string filename = "Configs/"; filename += GetSystemName(); filename += ".json"; auto buffer = ReadFileToBuffer(GetSystem<IFileSystem>(), filename.data()); yasli::JSONIArchive ar; OpenArchiveJSON(edt::DenseArrayView<uint8_t>(buffer.first.get(), buffer.second), ar); SerializeMandatory(ar, params, ""); } catch (...) {} app->SetVSync(params.vSync); }; } }
#include<cstdio> #include<iostream> #include<string> using namespace std; int main(){ char puzzle[5][5]; int i,j,count=1; while(gets(puzzle[0])){ int flag=0; if(puzzle[0][0]=='Z') break; for(i=1;i<5;i++) gets(puzzle[i]); if(count>1) cout<<endl; // for(i=0;i<5;i++) // for(j=0;j<4;j++){ // cout<<puzzle[i][j]<<" "; // if(j==3){ // cout<<puzzle[i][j+1]<<endl; // } // } printf("Puzzle #%d:\n",count); char op; while(cin>>op){ if(op=='0'){ break; } int x,y; int i,j; for(i=0;i<5;i++) for(j=0;j<5;j++){ if(puzzle[i][j]==' '){ x=i; y=j; } } // printf("%d %d\n",x,y); switch(op){ case 'A': if(x==0){ flag=1; break; } else{ char t; t=puzzle[x-1][y]; puzzle[x-1][y]=' '; puzzle[x][y]=t; break; } case 'B': if(x==4){ flag=1; break; } else{ char t; t=puzzle[x+1][y]; puzzle[x+1][y]=' '; puzzle[x][y]=t; break; } case 'L': if(y==0){ flag=1; break; } else{ char t; t=puzzle[x][y-1]; puzzle[x][y-1]=' '; puzzle[x][y]=t; break; } case 'R': if(y==4){ flag=1; break; } else{ char t; t=puzzle[x][y+1]; puzzle[x][y+1]=' '; puzzle[x][y]=t; break; } // if(flag){ // cout<<"This puzzle has no final configuration."<<endl; // break; // } } if(flag){ cout<<"This puzzle has no final configuration."<<endl; getchar(); break; } // break; } if(flag); else{ for(i=0;i<5;i++) for(j=0;j<4;j++){ cout<<puzzle[i][j]<<" "; if(j==3){ cout<<puzzle[i][j+1]<<endl; } } } getchar(); count++; } return 0; }
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <iomanip> using namespace std; struct poly { int exp; double coe; }; int main() { int k, l; cin >> k; poly* a = new poly[k]; for (int i = 0; i < k; i++) cin >> a[i].exp >> a[i].coe; cin >> l; poly* b = new poly[l]; for (int i = 0; i < l; i++) cin >> b[i].exp >> b[i].coe; int i = 0, j = 0; int length = k < l ? k : l; vector<poly*> v; for (i = 0, j = 0; i < length && j < length;) { poly* p = new poly; if (a[i].exp == b[j].exp) { p->exp = a[i].exp; p->coe = a[i].coe + b[j].coe; if (p->coe != 0) { v.push_back(p); } ++i; ++j; } else if (a[i].exp > b[j].exp) { v.push_back(&a[i]); ++i; } else { v.push_back(&b[j]); ++j; } } for (i; i < k; i++) v.push_back(&a[i]); for (j; j < l; j++) v.push_back(&b[j]); cout << v.size(); for (int i = 0; i < v.size(); i++) { cout << ' ' << v[i]->exp << ' '; cout << fixed << setprecision(1) << v[i]->coe; } cout << endl; return 0; }
//#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> #include <vector> #include <cstdlib> #include <string> using namespace std; class Student{ public: string firstName; // krstne meno string lastName; // priezvisko Student() : firstName(""), lastName("") {} Student(string firstName, string lastName) : firstName(firstName), lastName(lastName) {} // DOPLNIT operator < friend bool operator< (const Student & a, const Student & b) { if((a.lastName)<(b.lastName)) { return true; } else if ((a.lastName)>(b.lastName)) { return false; } else { if((a.firstName)<(b.firstName)) { return true; } else if ((a.firstName)>(b.firstName)) { return false; } } } // DOPLNIT operator << friend ostream& operator<<(ostream& os, const Student & a) { os << (a.firstName) << " " << (a.lastName); return os; } }; // struktura, ktora predstavuje uzol v binarnom vyhladavacom strome struct Node{ Student student; // datova cast uzlu Node * left; // lavy potomok Node * right; // pravy potomok Node(Student student){ this->student = student; this->left = 0; this->right = 0; } }; class Tree{ public: //odtialto to treba prerobit: Node * root; Tree() { Student studentik("Jakub", "Komorny"); Node root(studentik); } // pridanie studenta do stromu bool addStudent(Student student, Node * temp) { Node novystudent(student); if(temp==NULL) { temp = root; } if((novystudent.student) < (temp->student)) { if(temp->left == NULL) { *(temp->left) = novystudent; return true; } else { addStudent(student, temp->left); return false; } } if((novystudent.student.lastName) > (novystudent.student.lastName)) { if(temp->right == NULL) { *(temp->right) = novystudent; return true; } else { addStudent(student, temp->right); return false; } } return false; // <- ZMENIT (docasny return kvoli kompilacii) } //potadeto // vypis vsetkych studentov v strome (abecedne usporiadany) void print(Node * temp) { if(temp==NULL) { temp = root; } if(temp->left != NULL) { print(temp->left); } cout<<temp->student.firstName << " " <<temp->student.lastName << endl; if(temp->right != NULL) { print(temp->right); } } // vypis studentov v uzloch so zadanou hlbkou void printDepth(int hlbka, Node * temp){ if(temp==NULL) { temp = root; } if(temp->left != NULL) { printDepth(hlbka-1, temp->left); } if(hlbka==0) { cout<<temp->student.firstName << " " <<temp->student.lastName << endl; } if(temp->right != NULL) { printDepth(hlbka-1, temp->right); } } }; // usporiadanie prvkov vektora (PODLA ZADANIA ZMENIT DEKLARACIU) template<typename ElementType> void sort(vector<ElementType> & data) { int n = data.size(); int i, j; ElementType tmp; for (i=1; i<n; i++) { j=i; tmp=data[i]; while (j>0 && tmp<data[j-1]) { data[j]=data[j-1]; j--; } data[j]=tmp; } } /*------------------------------------------------------------------------------ Dalej nasleduju testovacie funkcie a main -----------------------------------------------------------------------------*/ // Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test1() { cout << "-------------------------------"<< endl; cout << "Test1: operator<" << endl; cout << "-------------------------------"<< endl; Student s1("Jan", "Bystricky"); Student s2("Jan", "Sikovny"); Student s3("Peter", "Sikovny"); // cout << (s1 < s2 ? "OK" : "ERR") << " "; // cout << (s2 < s1 ? "ERR" : "OK") << " "; // cout << (s2 < s3 ? "OK" : "ERR") << " "; // cout << (s3 < s2 ? "ERR" : "OK") << " "; cout << endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test2() { cout << "-------------------------------"<< endl; cout << "Test2: operator<<" << endl; cout << "-------------------------------"<< endl; Student s1("Jan", "Bystricky"); // cout << s1 << endl; cout << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test3a1() { cout << "-------------------------------"<< endl; cout << "Test3a1: sort int" << endl; cout << "-------------------------------"<< endl; int data[] = {10, 5, 2, 1, 12, 15, 80, 0, -1, 4}; vector<int> v(data, data+10); sort(v); for(int i = 0; i < 10; i++) { cout << v[i] <<", "; } cout<< endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test3a2() { cout << "-------------------------------"<< endl; cout << "Test3a2: sort int (pole dlzky 1)" << endl; cout << "-------------------------------"<< endl; int data[] = {10}; vector<int> v(data, data+1); sort(v); for(int i = 0; i < 1; i++) { cout << v[i] <<", "; } cout<< endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test3a3() { cout << "-------------------------------"<< endl; cout << "Test3a3: sort int (pole dlzky 0)" << endl; cout << "-------------------------------"<< endl; vector<int> v; sort(v); cout << endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test3b() { cout << "-------------------------------"<< endl; cout << "Test3b: sort Student" << endl; cout << "-------------------------------"<< endl; vector<Student> v; v.push_back(Student("Bb","Da")); v.push_back(Student("A" ,"Aa")); v.push_back(Student("C" ,"Cc")); v.push_back(Student("B" ,"Bb")); v.push_back(Student("Cc","Da")); v.push_back(Student("D" ,"Db")); v.push_back(Student("Aa","Da")); v.push_back(Student("Ab","Ee")); v.push_back(Student("B" ,"Ba")); v.push_back(Student("Aa","Ee")); // sort(v); // for(int i = 0; i < 10; i++) { // cout << v[i] <<", "; // } cout<< endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) Tree * testCreateTree(){ const static int pocet = 8; string mena[]= {"Andrej", "Peter", "Igor", "Emil", "Petra", "Marek", "Jana", "Juraj"}; string priezviska[]= {"Maly", "Maly", "Stredny", "Vysoky", "Vysoka", "Chladny", "Dvorska", "Balogh"}; Tree * bst = new Tree(); for (int i=0; i<pocet; i++) bst->addStudent(Student(mena[i], priezviska[i]), NULL); return bst; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test4(){ cout << "-------------------------------"<< endl; cout << "Test4: Testovanie navratovej hodnoty funkcie addStudent()" << endl; cout << "-------------------------------"<< endl; Tree tree; cout << tree.addStudent(Student("Andrej", "Maly"), NULL) << " "; cout << tree.addStudent(Student("Peter" , "Maly"), NULL) << " "; cout << tree.addStudent(Student("Igor" , "Stredny"), NULL) << " "; cout << tree.addStudent(Student("Igor" , "Stredny"), NULL) << " "; cout << tree.addStudent(Student("Rudolf", "Strassman"), NULL) << " "; cout << endl << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test5(){ cout << "-------------------------------"<< endl; cout << "Test5: Vypis vsetkych studentov v strome" << endl; cout << "-------------------------------"<< endl; Tree * bst =testCreateTree(); bst->print(NULL); cout << endl; } //Testovacia funkcia (neupravovat! mozete len odkomentovat zakomentovane riadky) void test6(int hlbka){ cout << "-------------------------------"<< endl; cout << "Test6: Vypis studentov v hlbke " << hlbka << endl; cout << "-------------------------------"<< endl; Tree * bst =testCreateTree(); bst->printDepth(hlbka, NULL); cout << endl; } int main(){ test1(); //operator < test2(); //operator << test3a1(); //sort vektora int-ov test3a2(); test3a3(); test3b(); //sort vektora studentov testCreateTree(); //vytvorenie binarneho vyhladavacieho stromu test4(); //navratova hodnota addStudent test5(); //vypis vsetkych studentov v strome (abecedne usporiadani) test6(1); //vypis vsetkych studentov v danej hlbke - volanie funkcie printDepth() test6(2); test6(3); test6(8); system("pause"); }
// Copyright 2017 The WCT(Wisdom City Times) Authors. All rights reserved #include "chrome/browser/ui/views/tabs/popup_thumbnail.h" PopupThumbnail::PopupThumbnail(Type type, Browser* browser) : type_(type), browser_(browser) {} PopupThumbnail::~PopupThumbnail() {}
// // Created by jeremyelkayam on 9/30/20. // #include "end_screen.hpp" EndScreen::EndScreen(TextLoader &a_text_loader, ResourceManager &a_resource_manager, InputManager &an_input_manager, vector<postmortem_info> dead_players_info, game_options game_opts) : Screen(a_text_loader, a_resource_manager, an_input_manager), min_screen_time(a_text_loader.get_float("IDS_MIN_SCREEN_TIME")), opts(game_opts){ screen_over = false; play_again = false; time_so_far = 0; sf::Text loss_text; resource_manager.setup_text(loss_text, a_text_loader.get_float("IDS_VIEW_X")/2, a_text_loader.get_float("IDS_VIEW_X")/10, a_text_loader.get_string("IDS_LOSS_TEXT"), CENTER); screen_texts.emplace_back(loss_text); for(unsigned long i = 0 ; i < dead_players_info.size() ; ++i){ screen_texts.emplace_back(sf::Text()); //Let's get the number of digits BEFORE the decimal point unsigned long whole_digits = std::to_string((int)dead_players_info.at(i).age).length(); string time_trunc = std::to_string(dead_players_info.at(i).age); time_trunc.resize(whole_digits + 2); resource_manager.setup_text(screen_texts.back(), a_text_loader.get_float("IDS_VIEW_X")/2, a_text_loader.get_float("IDS_VIEW_Y") * (i+1) / (dead_players_info.size() + 2) , "Player "+std::to_string(i+1)+" lasted " + time_trunc + " seconds\nand killed "+ std::to_string(dead_players_info.at(i).num_kills)+" enemies.", CENTER); } screen_texts.emplace_back(sf::Text()); resource_manager.setup_text(screen_texts.back(), a_text_loader.get_float("IDS_VIEW_X")/2, a_text_loader.get_float("IDS_VIEW_Y") * (dead_players_info.size()+1) / (dead_players_info.size() + 2) , "Press 1 to play again with\n same options.\n\nPress 2 to return to main menu.", CENTER); end_game_sound.setBuffer(a_resource_manager.get_sound_buffer("IDS_PATH_LOSE_MUSIC")); end_game_sound.play(); } void EndScreen::draw(sf::RenderWindow &window, ColorGrid &color_grid) { for(const auto &text : screen_texts) { window.draw(text); } } bool EndScreen::go_to_next() { return screen_over; } unique_ptr<Screen> EndScreen::next_screen(){ assert(go_to_next()); end_game_sound.stop(); if(play_again) return unique_ptr<Screen>(new PlayingScreen(text_loader, resource_manager, input_manager, opts)); return unique_ptr<Screen>(new MainMenuScreen(text_loader, resource_manager, input_manager)); } void EndScreen::handle_event(sf::Event &evt) { if(time_so_far > 2.f) { //if the mouse was clicked or a key was pressed, we can move on. play_again = evt.key.code == sf::Keyboard::Num1; screen_over = (evt.key.code == sf::Keyboard::Num1 || evt.key.code == sf::Keyboard::Num2); } } void EndScreen::update(float s_elapsed) { time_so_far += s_elapsed; }
#include <iostream> #include <cstring> using namespace std; int minlen(char *str[],int n); int main() { char str[5][31]; int n; cin>>n; for(int i=0;i<n;i++){ cin>>str[i];} cout<<minlen(str,n); return 0; } int minlen(char *str[],int n){ int tmp,min(31); for(int i=0;i<n;i++){ tmp=strlen(str[i]); if(tmp<min)min=tmp;} return min; }
#include "speed_controller.h" SpeedController::SpeedController(GPSSensor *gps_sensor, DroneBalancer *balancer) { this->gps_sensor = gps_sensor; this->balancer = balancer; }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/credential_provider/gaiacp/scoped_user_profile.h" #include <Windows.h> #include <dpapi.h> #include <security.h> #include <userenv.h> #include <atlconv.h> #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "base/win/registry.h" #include "chrome/credential_provider/gaiacp/gcp_strings.h" #include "chrome/credential_provider/gaiacp/gcp_utils.h" #include "chrome/credential_provider/gaiacp/logging.h" #include "chrome/credential_provider/gaiacp/reg_utils.h" namespace credential_provider { namespace { // Registry key under HKCU to write account info into. #if defined(GOOGLE_CHROME_BUILD) const wchar_t kRegAccountsPath[] = L"Software\\Google\\Accounts"; #else const wchar_t kRegAccountsPath[] = L"Software\\Chromium\\Accounts"; #endif // defined(GOOGLE_CHROME_BUILD) std::string GetEncryptedRefreshToken( base::win::ScopedHandle::Handle logon_handle, const base::DictionaryValue& properties) { std::string refresh_token = GetDictStringUTF8(&properties, kKeyRefreshToken); if (refresh_token.empty()) { LOGFN(ERROR) << "Refresh token is empty"; return std::string(); } if (!::ImpersonateLoggedOnUser(logon_handle)) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "ImpersonateLoggedOnUser hr=" << putHR(hr); return std::string(); } // Don't include null character in ciphertext. DATA_BLOB plaintext; plaintext.pbData = reinterpret_cast<BYTE*>(const_cast<char*>(refresh_token.c_str())); plaintext.cbData = static_cast<DWORD>(refresh_token.length()); DATA_BLOB ciphertext; BOOL success = ::CryptProtectData(&plaintext, L"Gaia refresh token", nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &ciphertext); HRESULT hr = success ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); ::RevertToSelf(); if (!success) { LOGFN(ERROR) << "CryptProtectData hr=" << putHR(hr); return std::string(); } // NOTE: return value is binary data, not null-terminate string. std::string encrypted_data(reinterpret_cast<char*>(ciphertext.pbData), ciphertext.cbData); ::LocalFree(ciphertext.pbData); return encrypted_data; } } // namespace // static ScopedUserProfile::CreatorCallback* ScopedUserProfile::GetCreatorFunctionStorage() { static CreatorCallback creator_for_testing; return &creator_for_testing; } // static std::unique_ptr<ScopedUserProfile> ScopedUserProfile::Create( const base::string16& sid, const base::string16& username, const base::string16& password) { if (!GetCreatorFunctionStorage()->is_null()) return GetCreatorFunctionStorage()->Run(sid, username, password); std::unique_ptr<ScopedUserProfile> scoped( new ScopedUserProfile(sid, username, password)); return scoped->IsValid() ? std::move(scoped) : nullptr; } ScopedUserProfile::ScopedUserProfile(const base::string16& sid, const base::string16& username, const base::string16& password) { LOGFN(INFO); // Load the user's profile so that their regsitry hive is available. base::win::ScopedHandle::Handle handle; if (!::LogonUserW(username.c_str(), L".", password.c_str(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &handle)) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "LogonUserW hr=" << putHR(hr); return; } token_.Set(handle); if (!WaitForProfileCreation(sid)) token_.Close(); } ScopedUserProfile::~ScopedUserProfile() {} bool ScopedUserProfile::IsValid() { return token_.IsValid(); } HRESULT ScopedUserProfile::SaveAccountInfo( const base::DictionaryValue& properties) { LOGFN(INFO); base::string16 sid = GetDictString(&properties, kKeySID); if (sid.empty()) { LOGFN(ERROR) << "SID is empty"; return E_INVALIDARG; } base::string16 id = GetDictString(&properties, kKeyId); if (id.empty()) { LOGFN(ERROR) << "Id is empty"; return E_INVALIDARG; } base::string16 email = GetDictString(&properties, kKeyEmail); if (email.empty()) { LOGFN(ERROR) << "Email is empty"; return E_INVALIDARG; } base::string16 token_handle = GetDictString(&properties, kKeyTokenHandle); if (token_handle.empty()) { LOGFN(ERROR) << "Token handle is empty"; return E_INVALIDARG; } // Save token handle. This handle will be used later to determine if the // the user has changed their password since the account was created. HRESULT hr = SetUserProperty(sid.c_str(), kUserTokenHandle, token_handle.c_str()); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(th) hr=" << putHR(hr); return hr; } hr = SetUserProperty(sid.c_str(), kUserEmail, email.c_str()); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(email) hr=" << putHR(hr); return hr; } // Write account information to the user's hive. // NOTE: regular users cannot access the registry entry of other users, // but administrators and SYSTEM can. { wchar_t key_name[128]; swprintf_s(key_name, base::size(key_name), L"%s\\%s\\%s", sid.c_str(), kRegAccountsPath, id.c_str()); LOGFN(INFO) << "HKU\\" << key_name; base::win::RegKey key; LONG sts = key.Create(HKEY_USERS, key_name, KEY_READ | KEY_WRITE); if (sts != ERROR_SUCCESS) { HRESULT hr = HRESULT_FROM_WIN32(sts); LOGFN(ERROR) << "key.Create(" << id << ") hr=" << putHR(hr); return hr; } sts = key.WriteValue(base::ASCIIToUTF16(kKeyEmail).c_str(), email.c_str()); if (sts != ERROR_SUCCESS) { HRESULT hr = HRESULT_FROM_WIN32(sts); LOGFN(ERROR) << "key.WriteValue(" << sid << ", email) hr=" << putHR(hr); return hr; } // NOTE: |encrypted_data| is binary data, not null-terminate string. std::string encrypted_data = GetEncryptedRefreshToken(token_.Get(), properties); if (encrypted_data.empty()) { LOGFN(ERROR) << "GetEncryptedRefreshToken returned empty string"; return E_UNEXPECTED; } sts = key.WriteValue( base::ASCIIToUTF16(kKeyRefreshToken).c_str(), encrypted_data.c_str(), static_cast<ULONG>(encrypted_data.length()), REG_BINARY); if (sts != ERROR_SUCCESS) { HRESULT hr = HRESULT_FROM_WIN32(sts); LOGFN(ERROR) << "key.WriteValue(" << sid << ", RT) hr=" << putHR(hr); return hr; } } return S_OK; } ScopedUserProfile::ScopedUserProfile() {} bool ScopedUserProfile::WaitForProfileCreation(const base::string16& sid) { LOGFN(INFO); wchar_t profile_dir[MAX_PATH]; bool created = false; for (int i = 0; i < 10; ++i) { Sleep(1000); DWORD length = base::size(profile_dir); if (::GetUserProfileDirectoryW(token_.Get(), profile_dir, &length)) { LOGFN(INFO) << "GetUserProfileDirectoryW " << i << " " << profile_dir; created = true; break; } else { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(INFO) << "GetUserProfileDirectoryW hr=" << putHR(hr); } } if (!created) LOGFN(INFO) << "Profile not created yet???"; created = false; // Write account information to the user's hive. // NOTE: regular users cannot access the registry entry of other users, // but administrators and SYSTEM can. base::win::RegKey key; wchar_t key_name[128]; swprintf_s(key_name, base::size(key_name), L"%s\\%s", sid.c_str(), kRegAccountsPath); LOGFN(INFO) << "HKU\\" << key_name; for (int i = 0; i < 10; ++i) { Sleep(1000); LONG sts = key.Create(HKEY_USERS, key_name, KEY_READ | KEY_WRITE); if (sts == ERROR_SUCCESS) { LOGFN(INFO) << "Registry hive created " << i; created = true; break; } } if (!created) LOGFN(ERROR) << "Profile not created really???"; return created; } } // namespace credential_provider
#include<iostream> #include<vector> using namespace std; class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { //简化版:lower_bound和upper_bound算法 vector<int> res{-1,-1}; if(nums.empty()) return res; int low=0, mid, high=nums.size()-1; while(low<high) { mid=(low+high)/2; if(nums[mid]<target) low=mid+1; else high=mid; } if(nums[low]==target) res[0]=low; else return res; low=0,high=nums.size(); while(low<high) { mid=(low+high)/2; if(nums[mid]<=target) low=mid+1; else high=mid; } res[1]=low-1; return res; } }; class Solution1 { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res; int low, mid, high, pos1, pos2; low = 0; high = nums.size() - 1; //基本思想:折半查找,思路很简单,细节是魔鬼。 while (low <= high) { mid = (low + high) / 2; //当nums[mid]=target,则在[low,mid]区间折半查找找到左半部分等于target的临界下标,在[mid,high]区间折半查找找到右半部分等于target的临界下标 if (nums[mid] == target) { pos1 = mid; pos2 = mid; //在[low,pos1]区间折半查找找到左半部分等于target的临界下标low while (nums[low] != target) { mid = (low + pos1) / 2; if (nums[mid] < target) { low = mid + 1; } else if (nums[mid] == target) { pos1 = mid; low++; } } //在[pos2, high]区间折半查找找到右半部分等于target的临界下标high while (nums[high] != target) { mid = (pos2 + high) / 2; if (nums[mid] > target) { high = mid - 1; } else if (nums[mid] == target) { pos2 = mid; high--; } } res.push_back(low); res.push_back(high); return res; } //当nums[mid]<target,low=mid+1 else if (nums[mid] < target) low = mid + 1; //当nums[mid]>target,high=mid-1 else high = mid - 1; } res.push_back(-1); res.push_back(-1); return res; } }; int main() { Solution solute; int target = 8; vector<int> nums = { 5,7,7,8,8,10 }; vector<int> res; res = solute.searchRange(nums, target); for (int i = 0; i < res.size(); i++) cout << res[i] << endl; return 0; }
#include "./XmlCommon.h" #include <iberbar/Utility/String.h> void iberbar::Poster::CXmlProcMessageBuffer::AddMessage( UXmlProcMessageCode code, const char* format, ... ) { va_list va; va_start( va, format ); m_messages.push_back( UXmlProcMessage( code, StdFormatVa( format, va ) ) ); va_end( va ); }
#include <string> #include <iostream> #include <specex_pyimage.h> using namespace std; specex::PyImage::PyImage( py::array ds_pix, py::array ds_ivar, py::array ds_mask, py::array ds_readnoise, std::map<std::string,std::string> hdr_mt ){ auto pix_prop = ds_pix.request(); auto ivar_prop = ds_ivar.request(); auto mask_prop = ds_mask.request(); auto readnoise_prop = ds_readnoise.request(); double *pix_vals = (double*) pix_prop.ptr; double *ivar_vals = (double*) ivar_prop.ptr; int *mask_vals = ( int*) mask_prop.ptr; double *readnoise_vals = (double*) readnoise_prop.ptr; // assume all images equal in size to ds_pix size_t nx = pix_prop.shape[0]; size_t ny = pix_prop.shape[1]; // this is to match the existing ordering as used in specex with // specex::image_data objects image.resize(ny,nx); weight.resize(ny,nx); mask.resize(ny,nx); rdnoise.resize(ny,nx); for (size_t i = 0; i < nx*ny; i++){ image.data[i] = pix_vals[i]; weight.data[i] = ivar_vals[i]; mask.data[i] = mask_vals[i]; rdnoise.data[i] = readnoise_vals[i]; } header = hdr_mt; } std::vector<double> specex::PyImage::get_data(std::string tag){ auto v = this->image.data; if(tag == "weight") { v = this->weight.data;} if(tag == "mask") { v = this->mask.data;} if(tag == "rdnoise"){ v = this->rdnoise.data;} if(tag == "image") cout << tag << " array sizes " << image.n_cols() << " " << image.n_rows() << " " << image.data.size() << endl; std::vector<double> vi(v.size()); for (unsigned i = 0; i < v.size(); ++i) vi[i]=v[i]; return vi; } std::map<std::string,std::string> specex::PyImage::get_header(){ return this->header; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** psmaas - Patricia Aas */ #ifndef CORE_HISTORY_MODEL_TIME_FOLDER_H #define CORE_HISTORY_MODEL_TIME_FOLDER_H #ifdef HISTORY_SUPPORT #include "modules/history/OpHistoryFolder.h" //___________________________________________________________________________ // CORE HISTORY MODEL TIME FOLDER //___________________________________________________________________________ class HistoryTimeFolder : public HistoryFolder { friend class HistoryModel; public: /* * Public static Create method - will return 0 if no memory condition * * @param title * @param period * @param key * * @return **/ static HistoryTimeFolder* Create(const OpStringC& title, TimePeriod period, HistoryKey * key); /* * @return **/ virtual BOOL IsDeletable() const { return FALSE; } /* * @return **/ virtual HistoryFolderType GetFolderType() const { return TIME_FOLDER; } /* * @return **/ TimePeriod GetPeriod() const { return m_period; } #ifdef HISTORY_DEBUG virtual int GetSize() { return sizeof(HistoryTimeFolder) + GetTitleLength();} #endif //HISTORY_DEBUG virtual ~HistoryTimeFolder(){} private: /* * @param period * @param key * * Private constructor - use public static Create method for memory safety **/ HistoryTimeFolder(TimePeriod period, HistoryKey * key): HistoryFolder(key) { m_period = period; } TimePeriod m_period; }; typedef HistoryTimeFolder CoreHistoryModelTimeFolder; // Temorary typedef to old class name, so old code continues to compile #endif // HISTORY_SUPPORT #endif // CORE_HISTORY_MODEL_TIME_FOLDER_H
#include <QDial> class SamDial : public QDial { Q_OBJECT public: SamDial( QWidget* parent ); public slots: void iterate(); };
#include <iostream> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> #include <math.h> #include "Camera.h" #include "util/Vec3f.h" #include "world/Chunk.h" #include "Entity.h" #define ESCAPE 27 using namespace std; // window stuff int window, scale = 16, Width, Height; GLfloat gui[16]; Camera cam; Vec3f selected; // game stuff bool keys[256], buttons[3]; float mouseX, mouseY; Chunk* chunks[16]; Entity entity; // GL stuff GLuint selectedList; void Resize(int width, int height) { if (width == 0 || height == 0) return; glViewport(0, 0, width, height); Width = width; Height = height; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, Width, height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glGetFloatv(GL_PROJECTION_MATRIX, gui); cam.adjust(width/scale, height/scale); } void InitGL(int width, int height) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); Resize(width, height); } void start() { buttons[0] = GLUT_UP; buttons[1] = GLUT_UP; buttons[2] = GLUT_UP; entity = Entity(Vec3f(0.5f, 0.5f, 0.0f)); entity.setTarget(Vec3f(15.0f, 16.5f, 0.0f)); selectedList = glGenLists(1); glNewList(selectedList, GL_COMPILE); glBegin(GL_LINE_STRIP); glVertex3f(0.0f, 1.0f, 1.0f); glVertex3f(0.0f, 0.0f, 1.0f); glVertex3f(1.0f, 0.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glVertex3f(0.0f, 1.0f, 1.0f); glEnd(); glEndList(); for (int i = 0; i < 16; i++) { int x = i / 4 - 2; int y = i % 4 - 2; chunks[i] = new Chunk(x, y); chunks[i]->gen(); } } // Input void keyPressed(unsigned char key, int x, int y) { keys[key] = true; } void keyUp(unsigned char key, int x, int y) { keys[key] = false; } void mouseInput(int button, int state, int x, int y) { buttons[button] = state; mouseX = x; mouseY = Height - y; } int lMouseX = 0, lMouseY = 0; void motion(int x, int y) { mouseX = x; mouseY = Height - y; } void handleInput() { if (keys[ESCAPE]) { glutDestroyWindow(window); exit(0); } if (keys['w']) { cam.posY += 2.0f / scale; } else if (keys['s']) { cam.posY -= 2.0f / scale; } if (keys['a']) { cam.posX -= 2.0f / scale; } else if (keys['d']) { cam.posX += 2.0f / scale; } if (buttons[GLUT_RIGHT_BUTTON] == GLUT_DOWN) { cam.posX += (float)(lMouseX - mouseX) / scale; cam.posY += (float)(lMouseY - mouseY) / scale; } else if (buttons[GLUT_LEFT_BUTTON] == GLUT_DOWN) { //drag select } selected.set(floor(cam.posX -((Width/2-mouseX) / scale)), floor(cam.posY - ((Height/2-mouseY) / scale)) + 1, 0.0f); lMouseX = mouseX; lMouseY = mouseY; } void Tick() { entity.tick(); } void Draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); cam.use(); cam.apply(); for (int i = 0; i < 16; i++) { // cout << i << endl; chunks[i]->draw(); } entity.draw(); glTranslated(selected.x, -selected.y, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glCallList(selectedList); // gui // commented out for when I do work on gui glPushMatrix(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(gui); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor3f(1.0f, 0.0f, 0.0f); glutStrokeCharacter(GLUT_STROKE_ROMAN, 'a'); glutStrokeCharacter(GLUT_STROKE_ROMAN, 'b'); glutStrokeCharacter(GLUT_STROKE_ROMAN, 'c'); glutStrokeCharacter(GLUT_STROKE_ROMAN, 'd'); glPopMatrix(); glutSwapBuffers(); } void Update() { handleInput(); Tick(); Draw(); } int main(int argc, char **argv) { /* Initialize GLUT state - glut will take any command line arguments that pertain to it or X Windows - look at its documentation at http://reality.sgi.com/mjk/spec3/spec3.html */ glutInit(&argc, argv); /* Select type of Display mode: Double buffer RGBA color Alpha components supported Depth buffer */ glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH); /* get a 640 x 480 window * Open a window */ glutInitWindowSize(640, 480); window = glutCreateWindow(""); /* Register the function to do all our OpenGL drawing. */ glutDisplayFunc(&Draw); /* Even if there are no events, redraw our gl scene. */ glutIdleFunc(&Update); /* Register the function called when our window is resized. */ glutReshapeFunc(&Resize); /* Register the function called when the keyboard is pressed. */ glutKeyboardFunc(&keyPressed); glutKeyboardUpFunc(&keyUp); glutMouseFunc(&mouseInput); glutMotionFunc(&motion); glutPassiveMotionFunc(&motion); /* Initialize our window. */ InitGL(640, 480); start(); /* Start Event Processing Engine */ glutMainLoop(); return 0; }
#ifndef EDIT_HH_ # define EDIT_HH_ void undisplay_edit_tab (); void display_edit_panel (GtkWidget *w, gpointer p); void display_show_panel (GtkWidget *w, gpointer p); #endif //EDIT_HH_
#pragma once template<typename AllocStrategy> class AllocOn { public: void* operator new(std::size_t size) { return AllocStrategy::Alloc(size); } void operator delete(void* ptr) { AllocStrategy::Delete(ptr); } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "modules/widgets/OpWidgetPainterManager.h" #include "modules/widgets/OpWidget.h" #ifndef CSS_WIDGETPAINTER_H #define CSS_WIDGETPAINTER_H /** class CssWidgetPainter. The OpWidgetPainter that draw widgets in a simple nonskinned way, using the colors and properties that was set on the widgets from CSS. It is used as the fallbackpainter so it will paint things that other painters doesn't. */ class CssWidgetPainter : public OpWidgetPainter { public: virtual void InitPaint(VisualDevice* vd, OpWidget* widget); virtual BOOL CanHandleCSS() { return TRUE; } virtual OpWidgetInfo* GetInfo(OpWidget* widget = NULL); virtual BOOL DrawScrollbarDirection(const OpRect &drawrect, int direction, BOOL is_down, BOOL is_hovering); virtual BOOL DrawScrollbarBackground(const OpRect &drawrect); virtual BOOL DrawScrollbarKnob(const OpRect &drawrect, BOOL is_down, BOOL is_hovering); virtual BOOL DrawScrollbar(const OpRect &drawrect) {return FALSE;} #ifdef PAGED_MEDIA_SUPPORT virtual BOOL DrawPageControlBackground(const OpRect &drawrect); virtual BOOL DrawPageControlButton(const OpRect& drawrect, ARROW_DIRECTION direction, BOOL is_down, BOOL is_hovering); #endif // PAGED_MEDIA_SUPPORT virtual BOOL DrawDropdown(const OpRect &drawrect); virtual BOOL DrawDropdownButton(const OpRect &drawrect, BOOL is_down); virtual BOOL DrawListbox(const OpRect &drawrect); virtual BOOL DrawButton(const OpRect &drawrect, BOOL value, BOOL is_default); virtual BOOL DrawEdit(const OpRect &drawrect); virtual BOOL DrawDropDownHint(const OpRect &drawrect); virtual BOOL DrawMultiEdit(const OpRect &drawrect); virtual BOOL DrawRadiobutton(const OpRect &drawrect, BOOL value); virtual BOOL DrawCheckbox(const OpRect &drawrect, BOOL value); virtual BOOL DrawItem(const OpRect &drawrect, OpStringItem* item, BOOL is_listbox, BOOL is_focused_item, int indent); virtual BOOL DrawTreeViewRow(const OpRect &drawrect, BOOL focused) { return FALSE; } virtual BOOL DrawResizeCorner(const OpRect &drawrect, BOOL active); virtual BOOL DrawWidgetResizeCorner(const OpRect &drawrect, BOOL is_active, SCROLLBAR_TYPE scrollbar); virtual BOOL DrawProgressbar(const OpRect &drawrect, double fillpercent, INT32 progress_when_total_unknown, OpWidgetString* string, const char *empty_skin, const char *full_skin) { return FALSE; } virtual BOOL DrawPopupableString(const OpRect &drawrect, BOOL is_hovering_button); virtual BOOL DrawSlider(const OpRect& rect, BOOL horizontal, double min, double max, double pos, BOOL highlighted, BOOL pressed_knob, OpRect& out_knob_position, OpPoint& out_start_track, OpPoint& out_end_track); virtual BOOL DrawSliderFocus(const OpRect& slider_rect, const OpRect& track_rect, const OpRect& focus_rect); virtual BOOL DrawSliderTrack(const OpRect& slider_rect, const OpRect& track_rect); virtual BOOL DrawSliderKnob(const OpRect& slider_rect, const OpRect& track_rect, const OpRect& knob_rect); virtual BOOL DrawMonthView(const OpRect& drawrect, const OpRect& header_area); virtual BOOL DrawColorBox(const OpRect& drawrect, COLORREF color); private: VisualDevice* vd; OpWidget* widget; UINT32 gray, lgray, dgray, dgray2, fdef, bdef, black; WIDGET_COLOR color; OpWidgetInfo info; void DrawArrow(const OpRect &drawrect, int direction); void DrawCheckmark(OpRect rect); void Draw3DBorder(UINT32 lcolor, UINT32 dcolor, const OpRect &drawrect); void DrawSunkenExternalBorder(const OpRect& rect); void DrawSunkenBorder(OpRect rect); void DrawFocusRect(const OpRect &drawrect); void DrawDirectionButton(OpRect rect, int direction, BOOL is_scrollbar, BOOL is_down); }; #endif // CSS_WIDGETPAINTER_H
class Singleton { public: static Singleton* Instance() { if(pInstance_) return pInstance_; return new Singleton; } int ReturnInt() { return intValue; } private: Singleton() { intValue = 1; } Singleton(const Singleton&) {} static Singleton* pInstance_; int intValue; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef VEGAOPBITMAP_H #define VEGAOPBITMAP_H #if defined(VEGA_SUPPORT) && defined(VEGA_OPPAINTER_SUPPORT) #include "modules/pi/OpBitmap.h" #ifdef EMBEDDED_ICC_SUPPORT class ImageColorTransform; #endif // EMBEDDED_ICC_SUPPORT class VEGAFill; class VEGARenderer; class VEGARenderTarget; class VEGABackingStore; class VEGAOpBitmap : public OpBitmap { public: VEGAOpBitmap(UINT32 width, UINT32 height, BOOL transparent, BOOL alpha, UINT32 transpcolor, INT32 indexed); virtual ~VEGAOpBitmap(); OP_STATUS Construct(BOOL support_painter, BOOL is_indexed); #ifdef VEGA_USE_HW OP_STATUS Migrate(); #endif // VEGA_USE_HW virtual BOOL Supports(SUPPORTS /*supports*/) const; virtual void* GetPointer(AccessType access_type); virtual void ReleasePointer(BOOL changed); virtual OpPainter* GetPainter(); virtual void ReleasePainter(); /*virtual */OP_STATUS CopyRect(const OpPoint& dest_point, const OpRect& src_rect, OpBitmap* src); virtual OP_STATUS AddLine(void* data, INT32 line); #ifdef USE_PREMULTIPLIED_ALPHA OP_STATUS AddLineAndPremultiply(void* data, INT32 line); #endif // USE_PREMULTIPLIED_ALPHA #ifdef EMBEDDED_ICC_SUPPORT OP_STATUS AddLineWithColorTransform(void* data, INT32 line, ImageColorTransform* color_transform); #endif // EMBEDDED_ICC_SUPPORT virtual BOOL GetLineData(void* data, UINT32 line) const; #ifdef SUPPORT_INDEXED_OPBITMAP virtual OP_STATUS AddIndexedLine(void* data, INT32 line); virtual BOOL GetIndexedLineData(void* data, UINT32 line) const; virtual BOOL SetPalette(UINT8* /*pal*/, UINT32 /*num_colors*/); virtual BOOL GetPalette(UINT8* pal) const; #endif // SUPPORT_INDEXED_OPBITMAP virtual BOOL SetColor(UINT8* color, BOOL all_transparent, const OpRect* rect); virtual UINT32 Width() const; virtual UINT32 Height() const; virtual UINT8 GetBpp() const; virtual UINT32 GetBytesPerLine() const; virtual BOOL HasAlpha() const; virtual BOOL IsTransparent() const; virtual UINT32 GetTransparentColorIndex() const; VEGABackingStore* GetBackingStore() { #ifdef VEGA_LIMIT_BITMAP_SIZE OP_ASSERT(!isTiled()); #endif // VEGA_LIMIT_BITMAP_SIZE return backingstore; } OP_STATUS getFill(VEGARenderer* rend, VEGAFill** outfill); OpBitmap* GetSubBitmap(const OpRect& rect); void ReleaseSubBitmap(); static UINT32 GetAllocationSize(UINT32 width, UINT32 height, BOOL transparent, BOOL alpha, INT32 indexed); #ifdef VEGA_LIMIT_BITMAP_SIZE static bool needsTiling(UINT32 width, UINT32 height); bool needsTiling() const { return needsTiling(width, height); } /** Construct tiles for this bitmap. * @param is_indexed see Construct() * @return OpStatus::OK if all went well, OpStatus::ERR_NO_MEMORY on OOM */ OP_STATUS ConstructTiles(const unsigned tile_side, BOOL is_indexed); /// @return true if this bitmap is tiled bool isTiled() const { return bitmap_tiles != NULL; } /** Paint a tiled bitmap according to information in diinfo. Will * generate calls to VEGAOpPainter::PaintImage. * @param painter the painter to use * @param diinfo source and destination rect etc * @return the accumulated status from the calls to * PaintImage. OOM takes priority over other errors. */ OP_STATUS paintTiled(class VEGAOpPainter* painter, struct VEGADrawImageInfo& diinfo); /** Copy parts of a tiled bitmap to a render target. Will * generate calls to VEGARenderTarget::copyToBitmap. * @param rt the render target to copy to * @param width the width of the area to be copied * @param height the height of the area to be copied * @param srcx,srcy the top-left corner of the area to be copied, * relative to the top-left corner of the entire bitmap * @param dstx,dsty the top-left corner of the target area, * relative to the top-left corner of the render target * @return the accumulated status from the calls to * copyToBitmap. OOM takes priority over other errors. */ OP_STATUS copyTiled(class VEGARenderTarget* rt, unsigned int width, unsigned int height, unsigned int srcx, unsigned int srcy, unsigned int dstx, unsigned int dsty); /** Copy parts of srcbmp to this tiled bitmap. Will * generate calls to VEGAOpBitmap::CopyRect. * @param dest_point the top-left corner of the area to be copied, * relative to the top-left corner of this entire bitmap * @param src_rect the area in srcbmp to copy * @return the accumulated status from the calls to * CopyRect. OOM takes priority over other errors. */ OP_STATUS copyTiled(const OpPoint& dest_point, const OpRect& src_rect, VEGAOpBitmap* src_bmp); /** Copy parts of this tiled bitmap to target_bmp. Will * generate calls to VEGAOpBitmap::CopyRect. * @param src_rect the area in this tiled bitmap to copy * @param dest_point the top-left corner of the area to be copied, * relative to the top-left corner of target_bmp * @return the accumulated status from the calls to * CopyRect. OOM takes priority over other errors. */ OP_STATUS copyFromTiled(const OpRect& src_rect, const OpPoint& dest_point, VEGAOpBitmap* target_bmp); /** Draw parts of this tiled bitmap to ctx. Will * generate calls to VEGACanvasContext2D::drawImage. * @param ctx the target canvas context * @param src the area in this tiled bitmap to copy * @param dst the target area * @return the accumulated status from the calls to * CopyRect. OOM takes priority over other errors. */ OP_STATUS drawCanvasTiled(class CanvasContext2D* ctx, const double* src, const double* dst); #endif // VEGA_LIMIT_BITMAP_SIZE private: VEGABackingStore* backingstore; UINT32 width; UINT32 height; bool alpha; bool transparent; UINT32 transColor; UINT32* palette; unsigned int paletteSize; class VEGAOpPainter* painter; VEGAFill* fill; struct CachedSubBitmap { OpBitmap* bmp; OpRect rect; }; CachedSubBitmap subBitmapCache[9]; #ifdef VEGA_LIMIT_BITMAP_SIZE class VEGABitmapTileCollection* bitmap_tiles; #endif // VEGA_LIMIT_BITMAP_SIZE }; #endif // VEGA_SUPPORT && VEGA_OPPAINTER_SUPPORT #endif // !VEGAOPBITMAP_H
#include "APIServer.h" #include "Helpers.h" #include "KeyManager.h" #include <filesystem> APIServer::APIServer(uint32_t port, const std::string& secret, KeyManager& keyManager) : m_port(port), m_keyManager(keyManager) { m_server.Post("/create", [this, &secret](const httplib::Request& request, httplib::Response& response) { if (!contains(request.files, "key") || !contains(request.files, "id")) { std::cerr << "Requested new keys without the proper data..." << std::endl; response.status = 511; return; } const std::string& key = request.files.find("key")->second.content; if (key != secret) { std::cerr << "Requested new keys without the proper key... " << std::endl; response.status = 511; return; } const std::string& id = request.files.find("id")->second.content; // refresh keys before it all starts to avoid duplicates m_keyManager.refreshKeys(); // create the new key int playerAttempts = 0; std::string playerHash; do { playerHash = randomString(HASH_LENGTH); // dont let it infinite loop playerAttempts++; if (playerAttempts > 1024) { response.status = 500; return; } } while (m_keyManager.hasKey(convertHash(playerHash))); int moonAttempts = 0; std::string moonHash; do { moonHash = randomString(HASH_LENGTH); // dont let it infinite loop moonAttempts++; if (moonAttempts > 1024) { response.status = 500; return; } } while (m_keyManager.hasKey(convertHash(moonHash)) || moonHash == playerHash); // write the files and fill the content with the corresponding hash writeFile("../keys/" + id + ".txt", moonHash + " " + playerHash); // refresh keys after the files are written to get them, not efficient but who cares m_keyManager.refreshKeys(); std::cout << "Created key pair for user " << id << "." << std::endl; response.status = 200; response.set_content("{\"moonkey\": \"" + moonHash + "\", \"playerkey\": \"" + playerHash + "\"}", "application/json"); }); m_server.Post("/get", [this, &secret](const httplib::Request& request, httplib::Response& response) { if (!contains(request.files, "key") || !contains(request.files, "id")) { std::cerr << "Requested new keys without the proper data..." << std::endl; response.status = 511; return; } const std::string& key = request.files.find("key")->second.content; if (key != secret) { std::cerr << "Requested to get keys without the proper key... " << std::endl; response.status = 511; return; } const std::string& id = request.files.find("id")->second.content; // refresh keys before it all starts to avoid duplicates m_keyManager.refreshKeys(); if (!fileExists("../keys/" + id + ".txt")) { response.status = 200; response.set_content("{}", "application/json"); return; } std::string contents; readFile(contents, "../keys/" + id + ".txt"); std::string moonHash = contents.substr(0, HASH_LENGTH); std::string playerHash = contents.substr(HASH_LENGTH + 1, HASH_LENGTH); response.status = 200; response.set_content("{\"moonkey\": \"" + moonHash + "\", \"playerkey\": \"" + playerHash + "\"}", "application/json"); }); m_server.Post("/delete", [&secret](const httplib::Request& request, httplib::Response& response) { if (!contains(request.files, "key") || !contains(request.files, "id")) { std::cerr << "Requested to delete keys without the proper data..." << std::endl; response.status = 511; return; } const std::string& key = request.files.find("key")->second.content; if (key != secret) { std::cerr << "Requested to delete keys without the proper key... " << std::endl; response.status = 511; return; } const std::string& id = request.files.find("id")->second.content; if (!fileExists("../keys/" + id + ".txt")) { response.status = 500; return; } // validate that the id is a simple letter number combo so they the server can't delete incorrect files std::regex validHashRegex("[0-9a-zA-Z]+"); if (!std::regex_match(id, validHashRegex)) { response.status = 400; return; } if (!deleteFile("../keys/" + id + ".txt")) { response.status = 400; return; } std::cout << "Deleted key pair for user " << id << "." << std::endl; response.status = 200; response.set_content("{\"success\": true}", "application/json"); }); } void APIServer::run() { m_server.listen("0.0.0.0", m_port); }
// Created on: 1991-03-14 // Created by: Laurent PAINNOT // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _math_FunctionRoot_HeaderFile #define _math_FunctionRoot_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Real.hxx> #include <Standard_OStream.hxx> class math_FunctionWithDerivative; //! This class implements the computation of a root of a function of //! a single variable which is near an initial guess using a minimization //! algorithm.Knowledge of the derivative is required. The //! algorithm used is the same as in class math_FunctionRoot { public: DEFINE_STANDARD_ALLOC //! The Newton-Raphson method is done to find the root of the function F //! from the initial guess Guess.The tolerance required on //! the root is given by Tolerance. Iterations are stopped if //! the expected solution does not stay in the range A..B. //! The solution is found when abs(Xi - Xi-1) <= Tolerance; //! The maximum number of iterations allowed is given by NbIterations. Standard_EXPORT math_FunctionRoot(math_FunctionWithDerivative& F, const Standard_Real Guess, const Standard_Real Tolerance, const Standard_Integer NbIterations = 100); //! The Newton-Raphson method is done to find the root of the function F //! from the initial guess Guess. //! The tolerance required on the root is given by Tolerance. //! Iterations are stopped if the expected solution does not stay in the //! range A..B //! The solution is found when abs(Xi - Xi-1) <= Tolerance; //! The maximum number of iterations allowed is given by NbIterations. Standard_EXPORT math_FunctionRoot(math_FunctionWithDerivative& F, const Standard_Real Guess, const Standard_Real Tolerance, const Standard_Real A, const Standard_Real B, const Standard_Integer NbIterations = 100); //! Returns true if the computations are successful, otherwise returns false. Standard_Boolean IsDone() const; //! returns the value of the root. //! Exception NotDone is raised if the root was not found. Standard_Real Root() const; //! returns the value of the derivative at the root. //! Exception NotDone is raised if the root was not found. Standard_Real Derivative() const; //! returns the value of the function at the root. //! Exception NotDone is raised if the root was not found. Standard_Real Value() const; //! returns the number of iterations really done on the //! computation of the Root. //! Exception NotDone is raised if the root was not found. Standard_Integer NbIterations() const; //! Prints on the stream o information on the current state //! of the object. //! Is used to redefine the operator <<. Standard_EXPORT void Dump (Standard_OStream& o) const; protected: private: Standard_Boolean Done; Standard_Real TheRoot; Standard_Real TheError; Standard_Real TheDerivative; Standard_Integer NbIter; }; #include <math_FunctionRoot.lxx> #endif // _math_FunctionRoot_HeaderFile
// Created on: 1993-01-08 // Created by: Christian CAILLET // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_WorkLibrary_HeaderFile #define _IFSelect_WorkLibrary_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <Interface_HArray1OfHAsciiString.hxx> #include <Standard_Transient.hxx> class Interface_InterfaceModel; class Interface_Protocol; class IFSelect_ContextWrite; class Interface_EntityIterator; class Interface_CopyTool; class IFSelect_WorkLibrary; DEFINE_STANDARD_HANDLE(IFSelect_WorkLibrary, Standard_Transient) //! This class defines the (empty) frame which can be used to //! enrich a XSTEP set with new capabilities //! In particular, a specific WorkLibrary must give the way for //! Reading a File into a Model, and Writing a Model to a File //! Thus, it is possible to define several Work Libraries for each //! norm, but recommended to define one general class for each one : //! this general class will define the Read and Write methods. //! //! Also a Dump service is provided, it can produce, according the //! norm, either a parcel of a file for an entity, or any other //! kind of information relevant for the norm, class IFSelect_WorkLibrary : public Standard_Transient { public: //! Gives the way to Read a File and transfer it to a Model //! <mod> is the resulting Model, which has to be created by this //! method. In case of error, <mod> must be returned Null //! Return value is a status with free values. //! Simply, 0 is for "Execution OK" //! The Protocol can be used to work (e.g. create the Model, read //! and recognize the Entities) Standard_EXPORT virtual Standard_Integer ReadFile (const Standard_CString name, Handle(Interface_InterfaceModel)& model, const Handle(Interface_Protocol)& protocol) const = 0; //! Interface to read a data from the specified stream. //! @param model is the resulting Model, which has to be created by this method. //! In case of error, model must be returned Null //! Return value is a status: 0 - OK, 1 - read failure, -1 - stream failure. //! //! Default implementation returns 1 (error). Standard_EXPORT virtual Standard_Integer ReadStream (const Standard_CString theName, std::istream& theIStream, Handle(Interface_InterfaceModel)& model, const Handle(Interface_Protocol)& protocol) const; //! Gives the way to Write a File from a Model. //! <ctx> contains all necessary information : the model, the //! protocol, the file name, and the list of File Modifiers to be //! applied, also with restricted list of selected entities for //! each one, if required. //! In return, it brings the produced check-list //! //! The WorkLibrary has to query <applied> to get then run the //! ContextWrite by looping like this (example) : //! for (numap = 1; numap <= ctx.NbModifiers(); numap ++) { //! ctx.SetModifier (numap); //! cast ctx.FileModifier() to specific type -> variable filemod //! if (!filemod.IsNull()) filemod->Perform (ctx,writer); //! filemod then works with ctx. It can, either act on the //! model itself (for instance on its header), or iterate //! on selected entities (Start/Next/More/Value) //! it can call AddFail or AddWarning, as necessary //! } Standard_EXPORT virtual Standard_Boolean WriteFile (IFSelect_ContextWrite& ctx) const = 0; //! Performs the copy of entities from an original model to a new //! one. It must also copy headers if any. Returns True when done. //! The provided default works by copying the individual entities //! designated in the list, by using the general service class //! CopyTool. //! It can be redefined for a norm which, either implements Copy //! by another way (do not forget to Bind each copied result with //! its original entity in TC) and returns True, or does not know //! how to copy and returns False Standard_EXPORT virtual Standard_Boolean CopyModel (const Handle(Interface_InterfaceModel)& original, const Handle(Interface_InterfaceModel)& newmodel, const Interface_EntityIterator& list, Interface_CopyTool& TC) const; //! Gives the way of dumping an entity under a form comprehensive //! for each norm. <model> helps to identify, number ... entities. //! <level> is to be interpreted for each norm (because of the //! formats which can be very different) Standard_EXPORT virtual void DumpEntity (const Handle(Interface_InterfaceModel)& model, const Handle(Interface_Protocol)& protocol, const Handle(Standard_Transient)& entity, Standard_OStream& S, const Standard_Integer level) const = 0; //! Calls deferred DumpEntity with the recorded default level Standard_EXPORT void DumpEntity (const Handle(Interface_InterfaceModel)& model, const Handle(Interface_Protocol)& protocol, const Handle(Standard_Transient)& entity, Standard_OStream& S) const; //! Records a default level and a maximum value for level //! level for DumpEntity can go between 0 and <max> //! default value will be <def> Standard_EXPORT void SetDumpLevels (const Standard_Integer def, const Standard_Integer max); //! Returns the recorded default and maximum dump levels //! If none was recorded, max is returned negative, def as zero Standard_EXPORT void DumpLevels (Standard_Integer& def, Standard_Integer& max) const; //! Records a short line of help for a level (0 - max) Standard_EXPORT void SetDumpHelp (const Standard_Integer level, const Standard_CString help); //! Returns the help line recorded for <level>, or an empty string Standard_EXPORT Standard_CString DumpHelp (const Standard_Integer level) const; DEFINE_STANDARD_RTTIEXT(IFSelect_WorkLibrary,Standard_Transient) protected: //! Required to initialise fields Standard_EXPORT IFSelect_WorkLibrary(); private: Standard_Integer thelevdef; Handle(Interface_HArray1OfHAsciiString) thelevhlp; }; #endif // _IFSelect_WorkLibrary_HeaderFile
#pragma once #include <QWidget> namespace Ui { class ScaleStatisticsForm; } class ScaleStatisticsModel; class ScaleStatisticsForm : public QWidget { Q_OBJECT public: explicit ScaleStatisticsForm(QWidget *parent = nullptr); ~ScaleStatisticsForm(); ScaleStatisticsModel *getModel() const; void setModel(ScaleStatisticsModel *model); private: void updateResultsTab(); void updateCorrelationsTab(); void removeTab(int index); ScaleStatisticsModel *m_model; Ui::ScaleStatisticsForm *ui; };
#pragma once #include "plbase/PluginBase.h" #include "CTaskSimple.h" #include "CVector.h" #include "CVector2D.h" enum eUseGunFlags : unsigned __int8 { USE_GUN_RIGHT_HAND = 1, USE_GUN_LEFT_HAND = 2 }; #pragma pack(push, 1) class PLUGIN_API CTaskSimpleUseGun : public CTaskSimple { public: __int8 field_8; __int8 field_9; __int8 field_A; __int8 field_B; __int8 field_C; union { eUseGunFlags m_nStateFlags; struct { unsigned __int8 m_bRightHand : 1; unsigned __int8 m_bLefttHand : 1; }; }; __int8 field_E; __int8 field_F; __int8 field_10; __int8 gap_11[3]; CVector2D field_14; class CEntity *m_pTarget; CVector m_vTarget; void *m_pAnimBlendAssociation; class CWeaponInfo *m_pWeaponInfo; __int16 field_34; __int16 field_36; __int8 field_38; __int8 field_39; __int8 field_3A; __int8 field_3B; }; #pragma pack(pop) //VALIDATE_SIZE(CTaskSimpleUseGun, 0x3C);
// Fill out your copyright notice in the Description page of Project Settings. #include "kinect2ArrayProject.h" #include "kinect2ArrayProjectGameMode.h"
#pragma once #include "MythConfig.hh" #include <stdio.h> /* The maximum number of people who can talk at once */ #define CHAT_MAXPEOPLE 200 #include "PEOPLE.hh" #include <string> using namespace std; /* typedef struct { int active; TCPsocket sock; IPaddress peer; void* addtionaldata; } PEOPLE; */ //people[CHAT_MAXPEOPLE]; class mythVirtualServer { public: // string mythVirtualServer::GetLocalAddress(); static int acceptthreadstatic(void* data); void acceptthread(); static mythVirtualServer* CreateNew(int port); int StartServer(); int StopServer(); virtual void ServerCloseCallBack(PEOPLE* people); virtual void ServerDecodeCallBack(PEOPLE* people,char* data,int datalength); int closePeople(PEOPLE* people); int ContainPeople(PEOPLE* mpeople); ~mythVirtualServer(void); protected: mythVirtualServer(int port); private: TCPsocket servsock; SDLNet_SocketSet socketset; void cleanup(int exitcode); int initalsocket(int port); int m_port; bool m_stop; void HandleServer(void); void HandleClient(int which); PEOPLE *people[CHAT_MAXPEOPLE]; SDL_Thread* acceptthreadHandle; };
#ifndef TRANTOR_THREAD_POOL_H_ #define TRANTOR_THREAD_POOL_H_ #include <queue> #include <mutex> #include <atomic> #include <condition_variable> #include <thread> #include <memory> #include "TrantorNonCopyable.h" namespace trantor { class TrantorFixedThreadPool :TrantorNonCopyable { public: explicit TrantorFixedThreadPool(const int thread_num); ~TrantorFixedThreadPool(); void pushTask(std::function<void()> func); void waitUntilFinished(); bool isFree(); uint64_t getTaskNumInQueue() { std::unique_lock<std::mutex> lock(mtx_); return task_queue_.size(); } private: std::queue<std::function<void()> > task_queue_; std::vector<std::shared_ptr<std::thread> > thread_queue_; std::mutex mtx_; std::condition_variable not_empty_cv_; std::condition_variable empty_cv_; std::atomic<bool> wait_empty_; std::atomic<bool> pool_alive_; void threadFunc(); }; class TrantorSingleThread : TrantorNonCopyable { public: explicit TrantorSingleThread():thread_pool_(1) {} void pushTask(std::function<void()> func) { thread_pool_.pushTask(func); } void waitUntilFinished() { thread_pool_.waitUntilFinished(); } bool isFree() { return thread_pool_.isFree(); } uint64_t getTaskNumInQueue() { return thread_pool_.getTaskNumInQueue(); } private: TrantorFixedThreadPool thread_pool_; }; class TrantorCachedThreadPool : TrantorNonCopyable { public: explicit TrantorCachedThreadPool():max_thread_num_(INT16_MAX){} TrantorCachedThreadPool(const uint16_t max_thread_num) :max_thread_num_(max_thread_num) {} void pushTask(std::function<void()> func); uint16_t getThreadNum(); void reset(); void waitUntilFinished(); private: std::vector<std::shared_ptr<TrantorSingleThread> > single_thread_vec_; std::mutex mtx_; uint16_t max_thread_num_; }; } #endif
//interfaces de las clases #include "estudiantes.h" using namespace std; //FUNCIONES DE CLASE //constructor por defecto estudiante::estudiante(void) { //datos de busqueda strcpy(datos.cedula,""); //datos de identificacion strcpy(datos.nombre,""); datos.anno = 0; strcpy(datos.institucion,""); //datos de clasificacion datos.sexo = 'M'; fecha* fec = new fecha(); fec->copiar_en(datos.fecha_nac); //datos personales strcpy(datos.direccion,""); strcpy(datos.email,""); strcpy(datos.telefono,""); strcpy(datos.movil,""); //datos del objeto datos.valido = false; } //FUNCIONES DE CLASE PARA ARCHIVO //cargar los datos del estudiante en la estructura de datos unsigned short estudiante::leer(unsigned long pos) { ifstream archivo; archivo.open("datos_estudiantes.dat",ios::binary); if(archivo.fail()) return ARCH_NO_LEER; archivo.seekg(pos*sizeof(datos_estudiante),ios::beg); archivo.read((char*)&datos,sizeof(datos_estudiante)); archivo.close(); return 0; } //guardar los datos del estudiante en un archivo unsigned short estudiante::escribir(void) { ofstream archivo; //se abre el archivo para escritura, añadidura y binario archivo.open("datos_estudiantes.dat",ios::app|ios::binary); //el archivo no existe se crea if(archivo.bad()) archivo.open("datos_estudiantes.dat"); archivo.write((char*)&datos,sizeof(datos_estudiante)); archivo.close(); return 0; } //modificar los datos del estudiantes en el archivo unsigned short estudiante::escribir(unsigned long pos) { fstream archivo; archivo.open("datos_estudiantes.dat",ios::in|ios::out|ios::binary); if(archivo.fail()) return ARCH_NO_ESCRIBIR; archivo.seekp(pos*sizeof(datos_estudiante),ios::beg); archivo.write((char*)&datos,sizeof(datos_estudiante)); archivo.close(); return 0; } //FUNCIONES DE CLASE PARA INGRESO //ingreso por copia de datos en la clase estudiante void estudiante::copiar(datos_estudiante data) { //datos de busqueda strcpy(datos.cedula,data.cedula); //datos de identificacion strcpy(datos.nombre,data.nombre); datos.anno = data.anno; strcpy(datos.institucion,data.institucion); //datos de clasificacion datos.sexo = data.sexo; fecha* fec = new fecha(); fec->copiar(data.fecha_nac); fec->copiar_en(datos.fecha_nac); //datos personales strcpy(datos.direccion,data.direccion); strcpy(datos.email,data.email); strcpy(datos.telefono,data.telefono); strcpy(datos.movil,data.movil); //datos del objeto datos.valido = data.valido; } //ingreso de datos desde teclado void estudiante::ingresar(void) { //ingresar la cedula unsigned short n = 0; bool encontrado; //hasta tener una cedula valida system("cls"); cout<<"\n\t\tDATOS DEL ESTUDIANTE\n\n"; do { cout<<setw(25)<<"Cedula? "; strcpy(datos.cedula,ingresar_numero("##########")); //validar la cedula ingresada n = validar_cedula(datos.cedula); if(n > 0) { cout<<setw(25); imprimir_error(n); } //determina si ya existe el estudiante unsigned long pos; encontrado = buscar_estudiante(datos,pos); if(encontrado) { cout<<setw(25); imprimir_error(EST_YA_EXISTE); } }while(n > 0 || encontrado); cout<<endl; //ingresar el nombre cout<<setw(25)<<"Nombre Completo? "; cin.getline(datos.nombre,EST_MAX_NOMBRE); //años de estudio del estudiante cout<<setw(25)<<"Anno/Semestre/Grado? "; datos.anno = ingresar_numero(1,10); cout<<endl; //institucion o titulo del estudiante cout<<setw(25)<<"Institucion/Empresa? "; cin.getline(datos.institucion,EST_MAX_INSTITUCION); //sexo cout<<setw(25)<<"Sexo [f/m]? "; datos.sexo = ingresar_caracter("FM"); cout<<endl; //edad cout<<setw(25)<<"Fecha de Nacimiento? "; fecha* fec = new fecha(); fec->ingresar(); fec->copiar_en(datos.fecha_nac); cout<<endl; //direccion cout<<setw(25) << "Direccion? "; cin.getline(datos.direccion,EST_MAX_DIRECCION); //correo electronico do { cout<<setw(25) << "Email? " ; cin.getline(datos.email,EST_MAX_EMAIL); n = validar_email(datos.email); if(n > 0) { cout<<setw(25); imprimir_error(n); } }while(n > 0); //numero de telefono fijo cout<<setw(25)<<"Telefono? "; strcpy(datos.telefono,ingresar_numero("#######")); cout<<endl; //numero de celular cout<<setw(25)<<"Celular? "; strcpy(datos.movil,ingresar_numero("#########")); cout<<endl; //validar el objeto datos.valido = true; } //FUNCIONES DE CLASE PARA REPORTE //imprime los datos ostream& operator << (ostream& co, const datos_estudiante &a) { co<<setw(25)<<"Cedula: " <<a.cedula<<endl; co<<setw(25)<<"Nombre: " <<a.nombre<<endl; co<<setw(25)<<"Nacimiento: " <<a.fecha_nac<<endl; co<<setw(25)<<"Anno: " <<a.anno<<endl; co<<setw(25)<<"Institucion: " <<a.institucion<<endl; co<<setw(25)<<"Direccion: " <<a.direccion<<endl; co<<setw(25)<<"Email: " <<a.email<<endl; co<<setw(25)<<"Telefono: " <<a.telefono<<endl; co<<setw(25)<<"Movil: " <<a.movil<<endl; co<<setw(25)<<"Valido: " <<boolalpha<<a.valido<<endl; } //ingreso de datos en la clase estudiante void estudiante::copiar_en(datos_estudiante &data) { //datos de busqueda strcpy(data.cedula,datos.cedula); //datos de identificacion strcpy(data.nombre,datos.nombre); data.anno = datos.anno; strcpy(data.institucion,datos.institucion); //datos de clasificacion data.sexo = datos.sexo; fecha* fec = new fecha(); fec->copiar(datos.fecha_nac); fec->copiar_en(data.fecha_nac); //datos personales strcpy(data.direccion,datos.direccion); strcpy(data.email,datos.email); strcpy(data.telefono,datos.telefono); strcpy(data.movil,datos.movil); //datos del objeto data.valido = datos.valido; } //imprime los datos del estudiante void estudiante::imprimir(void) { if(datos.valido) { cout<<setw(25)<<"Cedula: "<<datos.cedula<<endl; cout<<setw(25)<<"Nombre: "<<datos.nombre<<endl; fecha* fec = new fecha(); unsigned short edad; fec->calcular_edad(datos.fecha_nac,edad); cout<<setw(25)<<"Edad: "<<edad<<endl; cout<<setw(25)<<"Anno: "<<datos.anno<<endl; cout<<setw(25)<<"Institucion: "<<datos.institucion<<endl; if(strcmp(datos.direccion,"NULL") != 0) cout<<setw(25)<<"Direccion: "<<datos.direccion<<endl; if(strcmp(datos.email,"NULL") != 0) cout<<setw(25)<<"Email: "<<datos.email<<endl; if(strcmp(datos.telefono,"NULL") != 0) cout<<setw(25)<<"Telefono: "<<datos.telefono<<endl; if(strcmp(datos.movil,"NULL") != 0) cout<<setw(25)<<"Movil: "<<datos.movil<<endl; } } //FUNCIONES DE CLASE PARA BUSQUEDA //busca un estudiante dados los datos bool estudiante::comparar(datos_estudiante data) { return datos == data; } //FUNCIONES DE CLASE PARA MODIFICACION //busca un estudiante dados los datos void estudiante::modificar(void) { //hasta tener una cedula valida cout<<setw(25)<<"Cedula: "<<datos.cedula<<endl; bool opcion; //ingresar el nombre cout<<setw(25)<<"Nombre Completo: "<<datos.nombre<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Nombre Completo? "; cin.getline(datos.nombre,40); } else cout<<endl; //años de estudio del estudiante cout<<setw(25)<<"Anno/Semestre/Grado: "<<datos.anno<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Anno/Semestre/Grado? "; datos.anno = ingresar_numero(1,10); cout<<endl; } else cout<<endl; //institucion o titulo del estudiante cout<<setw(25)<<"Institucion/Empresa: "<<datos.institucion<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Institucion/Empresa? "; cin.getline(datos.institucion,30); } else cout<<endl; //sexo cout<<setw(25)<<"Sexo [f/m]: "<<datos.sexo<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Sexo [f/m]? "; datos.sexo = ingresar_caracter("FM"); cout<<endl; } else cout<<endl; //edad cout<<setw(25)<<"Fecha de Nacimiento: "<<datos.fecha_nac.aaaammdd<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Fecha de Nacimiento? "; fecha* fec = new fecha(); fec->ingresar(); fec->copiar_en(datos.fecha_nac); cout<<endl; } else cout<<endl; //direccion cout<<setw(25)<<"Direccion: "<<datos.direccion<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Direccion? "; cin.getline(datos.direccion,50); } else cout<<endl; cout<<setw(25)<<"Email: "<<datos.email<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; unsigned short n = 0; //correo electronico do { cout<<setw(25) << "Email? " ; cin.getline(datos.email,40); n = validar_email(datos.email); if(n > 0) { cout<<setw(25); imprimir_error(n); } }while(n > 0); } else cout<<endl; //numero de telefono fijo cout<<setw(25)<<"Telefono: "<<datos.telefono<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Telefono? "; strcpy(datos.telefono,ingresar_numero("#######")); cout<<endl; } else cout<<endl; //numero de celular cout<<setw(25)<<"Celular: "<<datos.movil<<endl; cout<<setw(25)<<"Conservar [s/n]? "; if(!ingresar_sn()) { cout<<endl; cout<<setw(25)<<"Celular? "; strcpy(datos.movil,ingresar_numero("#########")); cout<<endl; } cout<<endl; //validar el objeto datos.valido = true; } //FUNCIONES DE CLASE PARA ELIMINACION //eliminar los datos de la estructura de datos void estudiante::validar(bool valor) { datos.valido = valor; } //FUNCIONES DE CLASE SOBRECARGADAS // operador friend de test de igualdad sobrecargado bool operator== (const datos_estudiante& a, const datos_estudiante& b) { for(int i=0; i<MAX_CEDULA; i++) if(a.cedula[i] != b.cedula[i]) return false; return true; } //FUNCIONES DE USUARIO //funcion para imprimir el menu del estudiante void menu_estudiante(usuario* usu) { char opcion = '*'; do { system("cls"); cout<<"\n\t\t\tESTUDIANTES\n\n"; cout<<setw(25)<<""<<"TECLA\n"; cout<<setw(25)<<"Ingresar: " <<"[i/I]\n";//ALTA cout<<setw(25)<<"Buscar: " <<"[b/B]\n";//BUSQUEDA cout<<setw(25)<<"Imprimir: " <<"[p/P]\n";//REPORTE cout<<setw(25)<<"Modificar: " <<"[m/M]\n";//MODIFICACION cout<<setw(25)<<"Eliminar: " <<"[e/E]\n\n";//BAJA cout<<setw(25)<<"Retornar: " <<"[ESC]\n\n";//EXIT cout<<setw(25)<<"Elija una opcion? "; opcion = toupper(getche()); switch(opcion) { case 'I': if(usu->permiso_escribir(USU_ESTUDIANTE)) ingresar_estudiantes(); break; case 'B': buscar_estudiantes(); break; case 'P': imprimir_estudiantes(); break; case 'M': if(usu->permiso_escribir(USU_ESTUDIANTE)) modificar_estudiantes(); break; case 'E': if(usu->permiso_escribir(USU_ESTUDIANTE)) eliminar_estudiantes(); break; default: cout<<endl<<endl; if((int)opcion != 27) { cout<<setw(25)<<"Opcion no valida! "; getch(); } else { unsigned long n; n = estudiantes_no_validos(); if(n > 0) { cout<<setw(25)<<"Datos no validos: "<<n<<endl; //verificación de salida cout<<endl; cout<<setw(25)<<"Desea eliminarlos [s/n]? "; if(ingresar_sn()) guardar_estudiantes(); } } break; } }while((int)opcion != 27); } //FUNCIONES DE USUARIO PARA INGRESO //ingreso de datos en la clase void ingresar_estudiantes(void)//MENU DE ALTAS { //menu de ingreso de estudiantes char opcion = '*'; do { system("cls"); cout<<"\n\t\tINGRESAR ESTUDIANTE\n\n"; cout<<setw(25)<<""<<"TECLA\n"; cout<<setw(25)<<"Archivo: " <<"[a/A]\n"; cout<<setw(25)<<"Teclado: " <<"[t/T]\n\n"; cout<<setw(25)<<"Retornar: " <<"[ESC]\n\n"; cout<<setw(25)<<"Elija una opcion? "; opcion = toupper(getche()); switch(opcion) { case 'A': ingresar_archivo_estudiantes(); break; case 'T': ingresar_estudiante(); break; default: if((int)opcion != 27) { cout<<endl<<endl; cout<<setw(25)<<"Opcion no valida! "; getch(); } break; } }while((int)opcion != 27); } //funcion para ingresar desde archivo void ingresar_archivo_estudiantes(void) { //apertura del archivo char ruta[EST_BUFFER]; cout<<endl<<endl; cout<<setw(25)<<"Path del archivo CSV? "; cin.getline(ruta,EST_BUFFER); //buffer de entrada char fila[EST_BUFFER]; //archivo fstream archivo; archivo.open(ruta,ios::in); if(archivo.fail()) { cout<<setw(25); imprimir_error(ARCH_NO_LEER); archivo.close(); return; } unsigned long n = 0; unsigned long pos; //leer el archivo texto while(archivo.getline(fila,EST_BUFFER,'\n') != NULL) { if(strcmp(fila,"") != 0) { datos_estudiante data; data = obtener_estudiante(fila); if(!buscar_estudiante(data,pos)) { estudiante* est = new estudiante(); est->copiar(data); est->escribir(); n++;//leidos } } } //cierre del archivo archivo.close(); //se ingresaron los datos cout<<endl; cout<<setw(25)<<"Datos leidos: "<<n<<"\n\n"; system("pause"); } //permite dividir la cadena en campos diferentes datos_estudiante obtener_estudiante(char* fila) { char campo[EST_CAMPOS][EST_MAX]; unsigned short indices[EST_CAMPOS]; unsigned short n = 0; unsigned short j = 0; unsigned short c = 0; unsigned short longitud = strlen(fila); //todos los caracteres de la linea recorridos for(j=0; j<longitud; j++) if(fila[j] == ';') indices[n++] = j; indices[n++] = j; //dato de devolucion if(n != EST_CAMPOS) { cout<<setw(25); imprimir_error(ARCH_EST_NO_COMPLETO); datos_estudiante data; return data; } //recorro los indices for(unsigned short i=0; i<n; i++) { unsigned short inicio = 0; if(i>0) inicio = indices[i-1] + 1; //llenado de campos c = 0; for(j=inicio; j<indices[i]; j++) { campo[i][c] = fila[j]; c++; if(i==EST_CEDULA && c==MAX_CEDULA) break; if(i==EST_NOMBRE && c==EST_MAX_NOMBRE-1) break; if(i==EST_INSTITUCION && c==EST_MAX_INSTITUCION-1) break; if(i==EST_SEXO && c==EST_MAX_SEXO) break; if(i==EST_FEC_NACIMIENTO && c==FEC_MAX) break; if(i==EST_DIRECCION && c==EST_MAX_DIRECCION-1) break; if(i==EST_EMAIL && c==EST_MAX_EMAIL-1) break; if(i==EST_TELEFONO && c==EST_MAX_TELEFONO-1) break; if(i==EST_MOVIL && c==EST_MAX_MOVIL-1) break; } campo[i][c] = '\0'; } //verifico que sea una cedula valida int k; k = validar_cedula(campo[EST_CEDULA]); if(k > 0) { cout<<setw(25); imprimir_error(k); datos_estudiante data; return data; } datos_estudiante data; //numero de cedula valida strcpy(data.cedula,campo[EST_CEDULA]); //nombre del estudiante strcpy(data.nombre,campo[EST_NOMBRE]); //año de estudios n = 0; for(int i=0;i<strlen(campo[EST_ANNO]);i++) n = 10 * n + (campo[EST_ANNO][i] - '0'); data.anno = n; //institucion a la que pertenece strcpy(data.institucion,campo[EST_INSTITUCION]); //genero del estudiante data.sexo = campo[EST_SEXO][0]; //ingreso de la edad del estudiante fecha* fec = new fecha(); fec->ingresar_mmddaaaa(campo[EST_FEC_NACIMIENTO]); fec->copiar_en(data.fecha_nac); //ingreso de la direccion strcpy(data.direccion,campo[EST_DIRECCION]); //ingreso de el correo electronico strcpy(data.email,campo[EST_EMAIL]); //telefonos strcpy(data.telefono,campo[EST_TELEFONO]); //movil strcpy(data.movil,campo[EST_MOVIL]); //validar el objeto data.valido = true; //todos los datos han sido ingresados return data; } //funcion para ingresar desde teclado void ingresar_estudiante(void) { do { estudiante* est = new estudiante(); est->ingresar(); est->escribir();//retorna error //ingresar mas estudiantes cout<<endl; cout<<setw(25)<<"Nuevo estudiante [s/n] ? "; }while(ingresar_sn()); } //FUNCIONES DE USUARIO PARA REPORTE //funcion para imprimir el archivo de estudiantes void imprimir_estudiantes(void)//MENU { unsigned long total = 0; //ubicar el total de los elementos //0 .. total-1 total = total_estudiantes(); if(total == 0) return; unsigned long pos = 0; char opcion = '*'; do { system("cls"); cout<<"\n\t\tIMPRIMIR ESTUDIANTE\n"; estudiante* est = new estudiante(); est->leer(pos);//retorna error cout<<endl; est->imprimir(); cout<<endl; cout<<setw(25)<<""<<"TECLA\n"; cout<<setw(25)<<"Primero: " <<"[ARRIBA]\n"; cout<<setw(25)<<"Anterior: " <<"[IZQUIERDA]\n"; cout<<setw(25)<<"Siguiente: " <<"[DERECHA]\n"; cout<<setw(25)<<"Ultimo: " <<"[ABAJO]\n\n"; cout<<setw(25)<<"Retornar: " <<"[ESC]\n\n"; cout<<setw(25)<<"Elija una opcion? "; opcion = getch(); ungetch(opcion); opcion = getch(); switch(opcion) { case 'H': pos = 0; break; case 'K': if(pos > 0) pos--; break; case 'M': if(pos < (total - 1)) pos++; break; case 'P': pos = total - 1; break; default: if((int)opcion != 27) { cout<<endl<<endl; cout<<setw(25)<<"Opcion no valida! "; getch(); } break; } }while((int)opcion != 27); } //FUNCIONES DE USUARIO PARA BUSQUEDA //funcion para buscar estudiantes void buscar_estudiantes(void)//MENU DE BUSQUEDAS { system("cls"); cout<<"\n\t\tBUSCAR ESTUDIANTE\n\n"; datos_estudiante data; unsigned short n = 0; do { cout<<setw(25)<<"Cedula? "; strcpy(data.cedula,ingresar_numero("##########")); //validar la cedula ingresada n = validar_cedula(data.cedula); if(n > 0) { cout<<setw(25); imprimir_error(n); } }while(n > 0); //cedula valida cout<<endl; unsigned long pos; if(buscar_estudiante(data,pos)) { estudiante* est = new estudiante(); est->copiar(data); cout<<endl; est->imprimir(); } else { cout<<setw(25); imprimir_error(EST_NO_ENCONTRADO); } cout<<endl; system("pause"); } //funcion para buscar un estudiante en el archivo bool buscar_estudiante(datos_estudiante &data, unsigned long &pos) { //archivo fstream archivo; archivo.open("datos_estudiantes.dat",ios::in|ios::binary); if(archivo.fail()) return false; pos = 0; datos_estudiante cab; archivo.seekp(pos*sizeof(datos_estudiante),ios::beg); archivo.read((char*)&cab,sizeof(datos_estudiante)); while(!archivo.eof()) { estudiante* est = new estudiante(); est->copiar(cab); if(est->comparar(data)) { est->copiar_en(data); archivo.close(); return true; } //leo el siguiente dato pos++; archivo.seekp(pos*sizeof(datos_estudiante),ios::beg); archivo.read((char*)&cab,sizeof(datos_estudiante)); } //cierre del archivo archivo.close(); return false; } //FUNCIONES DE USUARIO PARA MODIFICACION //funcion para modificar estudiantes void modificar_estudiantes(void)//MENU DE MODIFICACIONES { system("cls"); cout<<"\n\t\tMODIFICAR ESTUDIANTE\n\n"; datos_estudiante data; unsigned short n = 0; do { cout<<setw(25)<<"Cedula? "; strcpy(data.cedula,ingresar_numero("##########")); //validar la cedula ingresada n = validar_cedula(data.cedula); if(n > 0) { cout<<setw(25); imprimir_error(n); } }while(n > 0); //cedula valida unsigned long pos; cout<<endl; if(buscar_estudiante(data,pos)) { estudiante* est = new estudiante(); est->copiar(data); cout<<endl; est->modificar(); est->escribir(pos); } else { cout<<setw(25); imprimir_error(EST_NO_ENCONTRADO); } //se ingresaron los datos cout<<endl; system("pause"); } //FUNCIONES DE USUARIO PARA ELIMINACION //funcion para buscar un estudiante void eliminar_estudiantes(void)//MENU DE ELMINACIONES { system("cls"); cout<<"\n\t\tELIMINAR ESTUDIANTE\n\n"; datos_estudiante data; unsigned short n = 0; do { cout<<setw(25)<<"Cedula? "; strcpy(data.cedula,ingresar_numero("##########")); //validar la cedula ingresada n = validar_cedula(data.cedula); if(n > 0) { cout<<setw(25); imprimir_error(n); } }while(n > 0); //cedula valida unsigned long pos; cout<<endl; if(buscar_estudiante(data,pos)) { estudiante* est = new estudiante(); est->copiar(data); est->validar(false); est->escribir(pos); cout<<endl; cout<<data; } else { cout<<setw(25); imprimir_error(EST_NO_ENCONTRADO); } //se ingresaron los datos cout<<endl; system("pause"); } //FUNCIONES UTILES //obtencion del total de estudiantes en el registro unsigned long total_estudiantes(void) { ifstream archivo; archivo.open("datos_estudiantes.dat",ios::binary); if(archivo.fail()) return 0; //lee el total de archivos unsigned long n = 0; datos_estudiante data; archivo.read((char*)&data,sizeof(datos_estudiante)); while(!archivo.eof()) { n++; archivo.read((char*)&data,sizeof(datos_estudiante)); } archivo.close(); return n; } //verifica que existan datos invalidos unsigned long estudiantes_no_validos(void) { ifstream archivo; archivo.open("datos_estudiantes.dat",ios::binary); if(archivo.fail()) return 0; //lee el total de archivos unsigned long n = 0; datos_estudiante data; archivo.read((char*)&data,sizeof(datos_estudiante)); while(!archivo.eof()) { if(!data.valido) n++; archivo.read((char*)&data,sizeof(datos_estudiante)); } archivo.close(); return n; } //ARCHIVOS //verifica que existan datos invalidos void guardar_estudiantes(void) { //archivo de lectura ifstream archivo; archivo.open("datos_estudiantes.dat",ios::binary); if(archivo.fail()) { cout<<setw(25); imprimir_error(ARCH_NO_LEER); return; } //archivo de escritura ofstream temporal; temporal.open("temporal.dat",ios::app|ios::binary); if(temporal.fail()) { cout<<setw(25); imprimir_error(ARCH_NO_ESCRIBIR); archivo.close(); return; } //datos validos unsigned long pos = 0; datos_estudiante data; archivo.read((char*)&data,sizeof(datos_estudiante)); while(!archivo.eof()) { if(data.valido) temporal.write((char*)&data,sizeof(datos_estudiante)); archivo.read((char*)&data,sizeof(datos_estudiante)); } //datos escritos archivo.close(); temporal.close(); //cambio de nombre remove("datos_estudiantes.dat"); rename("temporal.dat","datos_estudiantes.dat"); }
// Programm: Bruchrechner // Beschreibung: Eingabe iener mathematischen Aufgabe, Bruchrechner // Autor: // Klasse: IJ209, Heinrich-Hertz-Berufskoleg // Zusammenarbeit mit: // Erstell-Datum: 24 November 2009 // //Änderungen: 1 Dezember 2009 Abfrage nach dem Nenner (ob null); wiederholungs abfrage(while schleife) // 7 Dezember 2009 verbesserung der Abfrage nach dem Nenner // #include "stdafx.h" #include "cstdlib" #include "iostream" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int iZähler1, iZähler2, iNenner1, iNenner2; //reservierung von speicher für die Variablen int iErgebnisZ, iErgebnisN; //reservierung von speicher für die Variablen char cantwort; cout <<"Hallo das ist ein Rechner von Bruchzahlen."<< endl; //ausgabe von Begrüßung do { //1. Bruch eingeben cout <<"Bitte geben Sie den Zaehler vom ersten Bruch ein."<< endl; //Frage nach Zähler1 cin >> iZähler1; //einlesen von Zähler1 cout <<"Bitte geben Sie den Nenner vom ersten Bruch ein."<< endl; //Frage nach Nenner1 cin >> iNenner1; //einlesen von Nenner1 cout <<'\n'; //zeilenumbruch //2. Bruch eingeben cout <<"Bitte geben Sie den Zaehler vom zweiten Bruch ein."<< endl; //Frage nach Zähler2 cin >> iZähler2; //einlesen von Zähler2 cout <<"Bitte geben Sie den Nenner vom zweiten Bruch ein."<< endl; //Frage nach Nenner2 cin >> iNenner2; //einlesen von Nenner2 cout <<'\n'; //zeilenumbruch if (iNenner1 && iNenner2 != 0) { //Addition iErgebnisZ = iZähler1 * iZähler2; //Rechnung von dErgebnisZ iErgebnisN = iNenner1 * iNenner2; //Rechung von dErgebnisN cout <<"Das Ergebnis ist "<< iErgebnisZ <<"/" << iErgebnisN << endl; //ausgabe vom Ergebnis cout <<"Wollen Sie das Program neu starten?(j/n)"; cin >> cantwort; } else { cout << "Falsche Eingabe die Nenner dürfen nicht den Wert Null haben"<< endl; cout << "Wollen sie das eine neue Eingabe Machen?? (j/n)"; cin >> cantwort; } } while (cantwort == 'j'); system("pause"); return 0; }
#ifndef VIGENERE_H_ #define VUGENERE_H_ #include <iostream> using namespace std; static string keyVigenere; static int lenKey, lenAlphabet,lenMessage; int * generateKey(string,string); int * encryptVigenere(int *,int *); int * decryptVigenere(int *,int *); int * matchCharToIndex(string,string); string matchIndexToChar(int *, string); int * memoryAllocation( int ); void setLength(string,string,string); #endif
/*This is the draft main part of the code to train a model to classify patches. Here, the main idea is to classify each patch. The model is trained in Dlib in C++ and the overall accuracy for 10 images is about 55 percent. The results are not acceptable yet however by data augmentation and better training images (or parameter optimization) it would definitely achieve good results. */ template < int N, template <typename> class BN, int stride, typename SUBNET > using block = BN<con<N, 3, 3, 1, 1, relu<BN<con<N, 3, 3, stride, stride, SUBNET>>>>>; template < template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET > using residual = add_prev1<block<N, BN, 1, tag1<SUBNET>>>; template < template <int, template<typename>class, int, typename> class block, int N, template<typename>class BN, typename SUBNET > using residual_down = add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<block<N, BN, 2, tag1<SUBNET>>>>>>; static std::vector<dlib::matrix<dlib::rgb_pixel>> images; template <typename SUBNET> using res = relu<residual<block, 8, bn_con, SUBNET>>; template <typename SUBNET> using ares = relu<residual<block, 8, affine, SUBNET>>; template <typename SUBNET> using res_down = relu<residual_down<block, 8, bn_con, SUBNET>>; template <typename SUBNET> using ares_down = relu<residual_down<block, 8, affine, SUBNET>>; const unsigned long number_of_classes = 2; using net_type = loss_multiclass_log<fc<number_of_classes, avg_pool_everything< res<res<res<res_down< res<res<res<res<res<res<res<res<res< // repeat this layer 9 times res_down< res< input<matrix<rgb_pixel>> >>>>>>>>>>>>>>>>>>; template <typename SUBNET> using pres = prelu<add_prev1<bn_con<con<8, 3, 3, 1, 1, prelu<bn_con<con<8, 3, 3, 1, 1, tag1<SUBNET>>>>>>>>; int row = 101; int col = 101; int train_images_num = 1000; int train_images_mitosis = 500; stringstream str; std::vector<unsigned long> train_labels; std::vector<matrix<rgb_pixel>> train_images; std::vector<matrix<rgb_pixel>> train_images_resize; train_images.clear(); train_images.resize(train_images_num); cout << "before resize train images" << endl; for (int i = 0; i < train_images_num; i++) { train_images[i].set_size(row, col); } cout << "after resize train images" << endl; train_images_resize.clear(); train_images_resize.resize(train_images_num); train_labels.clear(); train_labels.resize(train_images_num); cout << "before loading train images" << endl; for (size_t i = 0; i < train_images_num; ++i) { str << trainInputDirDL << i << ".jpg"; load_image(train_images_resize[i], str.str()); resize_image(train_images_resize[i], train_images[i], interpolate_bilinear()); if (i < train_images_mitosis) { cout << "mitosis" << endl; train_labels[i] = 0; } else { cout << "nonmitosis" << endl; train_labels[i] = 1; } str.str(""); cout << "i: " << i << endl; } cout << "before model" << endl; net_type net; dnn_trainer<net_type, adam> trainer(net, adam(0.0005, 0.9, 0.999)); trainer.set_iterations_without_progress_threshold(2000); trainer.set_learning_rate_shrink_factor(0.1); // The learning rate will start at 1e-3. trainer.set_learning_rate(1e-3); trainer.be_verbose(); cout << trainer << endl; dlib::rand rnd; // gives error for (auto&& img : train_images) disturb_colors(img, rnd); cout << "before train" << endl; trainer.set_synchronization_file(trainDataDir + "mitosis_network_sync", std::chrono::seconds(60)); trainer.train(train_images, train_labels); cout << "after train" << endl; net.clean(); serialize(trainDataDir + "mitosis_network.dat") << net; std::vector<unsigned long> predicted_labels = net(train_images); int num_right = 0; int num_wrong = 0; // And then let's see if it classified them correctly. for (size_t i = 0; i < train_images_resize.size(); ++i) // ++i { if (predicted_labels[i] == train_labels[i]) ++num_right; else ++num_wrong; } cout << "training num_right: " << num_right << endl; cout << "training num_wrong: " << num_wrong << endl; cout << "training accuracy: " << num_right / (double)(num_right + num_wrong) << endl; std::vector<matrix<rgb_pixel>> test_images; std::vector<unsigned long> test_labels; int test_images_num = 13; test_images.clear(); test_images.resize(test_images_num); test_labels.clear(); test_labels.resize(test_images_num); std::vector<matrix<rgb_pixel>> test_images_resize; test_images_resize.clear(); test_images_resize.resize(test_images_num); num_right = 0; num_wrong = 0; int test_images_mitosis = 4; stringstream str2; for (int i = 0; i < test_images_num; ++i) { str2 << outputDirDL << i << ".jpg"; load_image(test_images_resize[i], str2.str()); resize_image(test_images_resize[i], test_images[i], interpolate_bilinear()); if (i < test_images_mitosis) { //cout << "mitosis" << endl; test_labels[i] = 0; } else { //cout << "nonmitosis" << endl; test_labels[i] = 1; } str2.str(""); } cout << "before predicted labels: " << endl; std::vector<unsigned long> predicted_labels_test = net(test_images); cout << "after predicted labels: " << endl; for (size_t i = 0; i < test_images.size(); ++i) { cout << "predicted results: " << predicted_labels_test[i] << endl; if (predicted_labels_test[i] == test_labels[i]) ++num_right; else ++num_wrong; } cout << "testing num_right: " << num_right << endl; cout << "testing num_wrong: " << num_wrong << endl; cout << "testing accuracy: " << num_right / (double)(num_right + num_wrong) << endl;
/** * created: 2013-4-7 22:12 * filename: FKRandomGenerator * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include "../Include/FKRandomGenerator.h" #include <stdlib.h> //------------------------------------------------------------------------ CTrueRandomGenerator::CTrueRandomGenerator() : m_hCrypt( NULL ) { srand(GetTickCount() + 230912); int ret = 1; if( !CryptAcquireContext( &m_hCrypt, NULL, NULL, PROV_RSA_FULL, 0) ) { ret = CryptAcquireContext( &m_hCrypt, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET); } if( !ret ) m_hCrypt = NULL; } //------------------------------------------------------------------------ CTrueRandomGenerator::~CTrueRandomGenerator() { if( m_hCrypt ) { CryptReleaseContext(m_hCrypt, 0); m_hCrypt = NULL; } } //------------------------------------------------------------------------ __int64 CTrueRandomGenerator::Generate64() { if(m_hCrypt == NULL) { __int64 i = 3 * rand() << 3 + GetTickCount(); return i; } BYTE data[sizeof(__int64)]; __int64 r = 0; if( m_hCrypt ) { if( CryptGenRandom( m_hCrypt, sizeof(data), data) ) { memcpy( &r, data, sizeof(data) ); } } return r > 0 ? r : -r; } //------------------------------------------------------------------------ UINT32 CTrueRandomGenerator::Generate32() { if(m_hCrypt == NULL) { __int64 i = 3 * rand() << 3 + GetTickCount(); return i & 0xFFFFFFFF; } BYTE data[sizeof(UINT32)]; UINT32 r = 0; if( m_hCrypt ) { if( CryptGenRandom( m_hCrypt, sizeof(data), data) ) { memcpy( &r, data, sizeof(data) ); } } return r; } //------------------------------------------------------------------------ CTrueRandomGenerator* GetRandomGenerator() { static CTrueRandomGenerator g_TrueRandomGenerator; return &g_TrueRandomGenerator; } //------------------------------------------------------------------------
/* This file is part of FineFramework project */ #ifndef FFW_UTILS_ANY #define FFW_UTILS_ANY #include <typeinfo> #include <string> #include <string.h> #include <unordered_map> #include <memory> #include <vector> #include "config.h" namespace ffw { class Array; class Object; /** * @ingroup utils */ class Any { public: class Content { public: virtual ~Content(){} virtual Content* createCopy() = 0; virtual const std::type_info& getTypeid() const = 0; virtual bool toBool() const = 0; virtual bool isInteger() const = 0; virtual bool isFloat() const = 0; virtual int getInteger() const = 0; virtual float getFloat() const = 0; virtual double getDouble() const = 0; virtual bool compare(const Content* other) const = 0; }; template<class T, class Enable = void> class Data: public Content { public: template<class ... Args> Data(Args&&... args):value(std::forward<Args>(args)...){ } virtual ~Data(){ } Data* createCopy() override { return new Data{ value }; } const std::type_info& getTypeid() const override { return typeid(T); } T& get() { return value; } const T& get() const { return value; } bool toBool() const override { return false; } bool isInteger() const override { return false; } bool isFloat() const override { return false; } int getInteger() const override { return 0; } float getFloat() const override { return 0.0f; } double getDouble() const override { return 0.0; } bool compare(const Content* other) const override { return value == static_cast<const Data<T>&>(*other).value; } private: T value; }; template<class T> class Data<T, typename std::enable_if<std::is_integral<T>::value>::type>: public Content { public: template<class ... Args> Data(Args&&... args):value(std::forward<Args>(args)...){ } virtual ~Data(){ } Data* createCopy() override { return new Data{ value }; } const std::type_info& getTypeid() const override { return typeid(T); } T& get() { return value; } const T& get() const { return value; } bool toBool() const override { return value != 0; } bool isInteger() const override { return true; } bool isFloat() const override { return false; } int getInteger() const override { return static_cast<int>(value); } float getFloat() const override { return static_cast<float>(value); } double getDouble() const override { return static_cast<double>(value); } bool compare(const Content* other) const override { return value == static_cast<const Data<T>&>(*other).value; } private: T value; }; template<class T> class Data<T, typename std::enable_if<std::is_floating_point<T>::value>::type> : public Content { public: template<class ... Args> Data(Args&&... args) :value(std::forward<Args>(args)...) { } virtual ~Data() { } Data* createCopy() override { return new Data{ value }; } const std::type_info& getTypeid() const override { return typeid(T); } T& get() { return value; } const T& get() const { return value; } bool toBool() const override { return value != 0; } bool isInteger() const override { return false; } bool isFloat() const override { return true; } int getInteger() const override { return static_cast<int>(value); } float getFloat() const override { return static_cast<float>(value); } double getDouble() const override { return static_cast<double>(value); } bool compare(const Content* other) const override { return value == static_cast<const Data<T>&>(*other).value; } private: T value; }; inline Any():content(nullptr){ } inline Any(const Any& other):content(nullptr){ if(!other.empty()) { content.reset(other.content->createCopy()); } } inline Any(Any&& other):content(nullptr){ std::swap(content, other.content); } template<class T> inline Any(T value):content(nullptr){ content.reset(new Data<T>{ value }); } /*template<size_t N> inline Any(const char(&value)[N]) : content(nullptr) { content.reset(new Data<std::string>(value)); }*/ /*template<> inline Any(const char* value) : content(nullptr) { content.reset(new Data<std::string>(value)); }*/ inline Any(std::initializer_list<std::pair<std::string, Any>> list); inline Any(std::initializer_list<Any> list); inline virtual ~Any() { } inline bool empty() const { return (content == nullptr); } inline void reset(){ content.reset(); } template<class T> inline T& getAs(){ if(content == nullptr || content->getTypeid() != typeid(T)){ throw std::bad_cast(); } return static_cast<Data<T>&>(*content.get()).get(); } template<class T> inline const T& getAs() const { if(content == nullptr || content->getTypeid() != typeid(T)){ throw std::bad_cast(); } return static_cast<const Data<T>&>(*content.get()).get(); } template<class T> inline void set(T value = T()){ *this = value; } template<class T> inline bool is() const { if (empty())return false; return (content->getTypeid() == typeid(T)); } inline bool toBool() const { if(empty())return false; if(content->getTypeid() == typeid(bool)){ return getAs<bool>(); } else { return content->toBool(); } } inline bool isBool() const { return is<bool>(); } inline std::string toString() const { if(empty())return ""; const auto& type = content->getTypeid(); if(type == typeid(const char*)){ return std::string(getAs<const char*>()); } else if(type == typeid(char*)){ return std::string(getAs<char*>()); } else if(type == typeid(std::string)){ return getAs<std::string>(); } else { return ""; } } inline bool isString() const { return ( is<const char*>() || is<char*>() || is<std::string>() ); } inline int toInt() const { if(empty())return 0; return content->getInteger(); } inline bool isInt() const { if (empty())return false; return content->isInteger(); } inline float toFloat() const { if (empty())return 0; return content->getFloat(); } inline double toDouble() const { if (empty())return 0; return content->getDouble(); } inline bool isFloat() const { if (empty())return false; return content->isFloat(); } inline bool isNumber() const { if (empty())return false; return content->isFloat() || content->isInteger(); } inline bool isObject() const; inline bool isArray() const; inline ffw::Array& getAsArray(); inline ffw::Object& getAsObject(); inline const ffw::Array& getAsArray() const; inline const ffw::Object& getAsObject() const; inline void clear() { content.reset(); } inline const std::type_info& getTypeid() const { if (empty())return typeid(nullptr); return content->getTypeid(); } // GCC will complain if this is missing but not MSVC nor Clang #if !defined(_MSC_VER) && !defined(__APPLE__) template<class T> inline explicit operator T() const { return getAs<T>(); } #endif template<class T> inline explicit operator T&(){ return getAs<T>(); } template<class T> inline explicit operator const T&() const { return getAs<T>(); } inline void swap(Any& other){ using std::swap; swap(content, other.content); } template<class T> inline Any& operator = (const T& value) { Any(value).swap(*this); return *this; } template<class T> inline Any& operator = (T&& value) { Any(value).swap(*this); return *this; } inline Any& operator = (const Any& other){ Any(other).swap(*this); return *this; } inline Any& operator = (Any&& other){ Any(other).swap(*this); return *this; } inline Any& operator [] (const std::string& key); inline const Any& operator [] (const std::string& key) const; inline Any& operator [] (size_t n); inline const Any& operator [] (size_t n) const; template<class T> inline bool operator == (const T& other) const { if(content->getTypeid() == typeid(T)){ return getAs<T>() == other; } return false; } template<class T> inline bool operator != (const T& other) const { return !(*this == other); } inline bool operator == (const Any& other) const { if (content != nullptr && other.content != nullptr && content->getTypeid() == other.content->getTypeid()) { return content->compare(other.content.get()); } else { return false; } } inline bool operator != (const Any& other) const { if (content != nullptr && other.content != nullptr && content->getTypeid() == other.content->getTypeid()) { return !content->compare(other.content.get()); } else { return true; } } private: std::unique_ptr<Content> content; }; /** * @ingroup utils */ class Array { public: typedef std::vector<Any> Vec; typedef Vec::allocator_type allocator_type; typedef Vec::reference reference; typedef Vec::const_reference const_reference; typedef Vec::pointer pointer; typedef Vec::const_pointer const_pointer; typedef Vec::iterator iterator; typedef Vec::const_iterator const_iterator; typedef Vec::reverse_iterator reverse_iterator; typedef Vec::const_reverse_iterator const_reverse_iterator; typedef Vec::difference_type difference_type; typedef Vec::size_type size_type; typedef Vec::value_type value_type; inline Array(){ } inline virtual ~Array(){ } inline Array(const Any& value){ vec.push_back(value); } inline Array(const Array& other){ vec = other.vec; } inline Array(Array&& other){ std::swap(vec, other.vec); } inline Array(const std::initializer_list<Any>& list){ vec.reserve(list.size()); for(auto& pair : list){ vec.push_back(pair); } } inline void swap(Array& other){ std::swap(vec, other.vec); } inline Array& operator = (const Array& other){ Array(other).swap(*this); return *this; } inline Array& operator = (Array&& other){ Array(other).swap(*this); return *this; } inline Array& operator = (const std::initializer_list<Any>& list){ Array(list).swap(*this); return *this; } inline Any& operator [] (size_type n){ return vec[n]; } inline const Any& operator [] (size_type n) const { return vec[n]; } template<class It> inline void assign(It first, It last){ vec.assign(first, last); } inline void assign(size_type n, const Any& value){ vec.assign(n, value); } inline reference at(size_type n){ return vec.at(n); } inline const_reference at(size_type n) const { return vec.at(n); } inline reference back(){ return vec.back(); } inline const_reference back() const { return vec.back(); } inline iterator begin(){ return vec.begin(); } inline const_iterator begin() const { return vec.begin(); } inline size_type capacity() const { return vec.capacity(); } inline const_iterator cbegin() const { return vec.cbegin(); } inline const_iterator cend() const { return vec.cend(); } inline void clear(){ return vec.clear(); } inline const_reverse_iterator crbegin() const { return vec.crbegin(); } inline const_reverse_iterator crend() const { return vec.crend(); } inline value_type* data(){ return vec.data(); } inline const value_type* data() const { return vec.data(); } inline bool empty() const { return vec.empty(); } inline iterator end(){ return vec.end(); } inline const_iterator end() const{ return vec.end(); } inline iterator erase(iterator position){ return vec.erase(position); } inline iterator erase(iterator first, iterator last){ return vec.erase(first, last); } inline reference front(){ return vec.front(); } inline const_reference front() const { return vec.front(); } inline allocator_type get_allocator() const { return vec.get_allocator(); } inline iterator insert (iterator position, const value_type& val){ return vec.insert(position, val); } inline void insert (iterator position, size_type n, const value_type& val){ vec.insert(position, n, val); } template <class InputIterator> inline void insert (iterator position, InputIterator first, InputIterator last){ vec.insert(position, first, last); } inline size_type max_size() const { return vec.max_size(); } inline void pop_back(){ vec.pop_back(); } inline void push_back(const value_type& val){ vec.push_back(val); } inline reverse_iterator rbegin(){ return vec.rbegin(); } inline const_reverse_iterator rbegin() const { return vec.rbegin(); } inline reverse_iterator rend(){ return vec.rend(); } inline const_reverse_iterator rend() const { return vec.rend(); } inline void reserve(size_type n){ vec.reserve(n); } inline void resize(size_type n, value_type val = value_type()){ vec.resize(n, val); } inline size_type size() const { return vec.size(); } inline void shrink_to_fit() { vec.shrink_to_fit(); } inline bool operator == (const Array& other) const { return vec == other.vec; } inline bool operator != (const Array& other) const { return vec != other.vec; } private: Vec vec; }; /** * @ingroup utils */ class Object { public: typedef std::unordered_map<std::string, Any> Map; typedef Map::allocator_type allocator_type; typedef Map::reference reference; typedef Map::const_reference const_reference; typedef Map::pointer pointer; typedef Map::const_pointer const_pointer; typedef Map::iterator iterator; typedef Map::const_iterator const_iterator; typedef Map::difference_type difference_type; typedef Map::size_type size_type; typedef Map::key_type key_type; typedef Map::local_iterator local_iterator; typedef Map::const_local_iterator const_local_iterator; typedef Map::mapped_type mapped_type; typedef Map::hasher hasher; typedef Map::value_type value_type; typedef Map::key_equal key_equal; inline Object(){ } inline virtual ~Object(){ } inline Object(const std::string& key, const Any& value){ map.insert(std::make_pair(key, value)); } inline Object(const Object& other){ map = other.map; } inline Object(Object&& other){ std::swap(map, other.map); } inline Object(const std::initializer_list<std::pair<std::string, Any>>& list){ map.reserve(list.size()); for(auto& pair : list){ map.insert(pair); } } inline bool exists(const std::string& key) const { return map.find(key) != map.end(); } inline bool contains(const std::string& key) const { return map.find(key) != map.end(); } inline bool has_key(const std::string& key) const { return map.find(key) != map.end(); } inline void swap(Object& other){ std::swap(map, other.map); } inline Object& operator = (const Object& other){ Object(other).swap(*this); return *this; } inline Object& operator = (Object&& other){ Object(other).swap(*this); return *this; } inline Object& operator = (const std::initializer_list<std::pair<std::string, Any>>& list){ Object(list).swap(*this); return *this; } inline std::pair<iterator, bool> insert(const std::string& key, const Any& value){ return map.insert(std::make_pair(key, value)); } inline Any& operator [] (const key_type& key){ return map[key]; } inline const Any& operator [] (const key_type& key) const { return map.at(key); } inline mapped_type& at(const key_type& key){ return map.at(key); } inline const mapped_type& at(const key_type& key) const { return map.at(key); } inline iterator begin(){ return map.begin(); } inline const_iterator begin() const { return map.begin(); } inline local_iterator begin(size_type n){ return map.begin(n); } inline const_local_iterator begin(size_type n) const { return map.begin(n); } inline size_type bucket(const key_type& k) const { return map.bucket(k); } inline size_type bucket_count() const { return map.bucket_count(); } inline size_type bucket_size(size_type n) const { return map.bucket_size(n); } inline const_iterator cbegin() const { return map.cbegin(); } inline const_local_iterator cbegin(size_type n) const { return map.cbegin(n); } inline const_iterator cend() const { return map.cend(); } inline const_local_iterator cend(size_type n) const { return map.cend(n); } inline void clear(){ map.clear(); } inline size_type count(const key_type& key) const { return map.count(key); } /*template <class... Args> inline std::pair<iterator, bool> emplace(Args&&... args){ return map.emplace(std::forward(args)); }*/ inline bool empty() const { return map.empty(); } inline iterator end(){ return map.end(); } inline const_iterator end() const { return map.end(); } inline local_iterator end(size_type n){ return map.end(n); } inline const_local_iterator end(size_type n) const { return map.end(n); } inline std::pair<iterator, iterator> equal_range (const key_type& k){ return map.equal_range(k); } inline std::pair<const_iterator, const_iterator> equal_range (const key_type& k) const { return map.equal_range(k); } inline iterator erase(const_iterator position){ return map.erase(position); } inline size_type erase(const key_type& value){ return map.erase(value); } inline iterator erase(const_iterator first, const_iterator last){ return map.erase(first, last); } inline iterator find(const key_type& key){ return map.find(key); } inline const_iterator find(const key_type& key) const { return map.find(key); } inline allocator_type get_allocator() const { return map.get_allocator(); } inline hasher hash_function() const { return map.hash_function(); } inline std::pair<iterator, bool> insert(const value_type& val){ return map.insert(val); } template <class P> inline std::pair<iterator, bool> insert(P&& val){ return map.insert(std::move(val)); } inline iterator insert(const_iterator hint, const value_type& val){ return map.insert(hint, val); } template <class P> inline iterator insert(const_iterator hint, P&& val){ return map.insert(hint, std::move(val)); } template <class InputIterator> inline void insert(InputIterator first, InputIterator last){ map.insert(first, last); } inline void insert(std::initializer_list<value_type> il){ map.insert(il); } inline key_equal key_eq() const { return map.key_eq(); } inline float load_factor() const { return map.load_factor(); } inline size_type max_bucket_count() const { return map.max_bucket_count(); } inline float max_load_factor() const { return map.max_load_factor(); } inline void max_load_factor(float z){ map.max_load_factor(z); } inline size_type max_size() const { return map.max_size(); } inline void rehash(size_type n){ map.rehash(n); } inline void reserve(size_type n){ map.reserve(n); } inline size_type size() const { return map.size(); } inline bool operator == (const Object& other) const { return map == other.map; } inline bool operator != (const Object& other) const { return map != other.map; } private: Map map; }; inline Any::Any(std::initializer_list<std::pair<std::string, Any>> list){ content.reset(new Data<Object>{ list }); } inline Any::Any(std::initializer_list<Any> list){ content.reset(new Data<Array>{ list }); } inline Any& Any::operator [] (const std::string& key){ return getAs<Object>()[key]; } inline const Any& Any::operator [] (const std::string& key) const { return getAs<Object>()[key]; } inline Any& Any::operator [] (size_t n){ return getAs<Array>()[n]; } inline const Any& Any::operator [] (size_t n) const { return getAs<Array>()[n]; } inline bool Any::isObject() const { return is<ffw::Object>(); } inline bool Any::isArray() const { return is<ffw::Array>(); } inline ffw::Array& Any::getAsArray() { return getAs<ffw::Array>(); } inline ffw::Object& Any::getAsObject() { return getAs<ffw::Object>(); } inline const ffw::Array& Any::getAsArray() const { return getAs<ffw::Array>(); } inline const ffw::Object& Any::getAsObject() const { return getAs<ffw::Object>(); } } inline void swap(ffw::Any& first, ffw::Any& second){ first.swap(second); } inline void swap(ffw::Object& first, ffw::Object& second){ first.swap(second); } inline void swap(ffw::Array& first, ffw::Array& second){ first.swap(second); } #endif
#include <iostream> #include <functional> #include <string> #include <iterator> #include <algorithm> template<typename T, typename ... Ts> auto concat(T t, Ts ... ts) { std::cout << __PRETTY_FUNCTION__ << std::endl; if constexpr (sizeof...(ts) > 0) { return [=](auto ... parameters) { return t(concat(ts...)(parameters...)); }; } else { return t; } } static bool begins_with_a(std::string const& s) { return s.find("a") == 0; } static bool ends_with_b(std::string const& s) { return s.rfind("b") == s.length() - 1; } template<typename A, typename B, typename F> auto combine(F binary_func, A a, B b) { return [=](auto param) { return binary_func(a(param), b(param)); }; } void test1() { auto a_xxx_b(combine( std::logical_and<>{}, begins_with_a, ends_with_b )); std::copy_if(std::istream_iterator<std::string>{std::cin}, {}, std::ostream_iterator<std::string>{std::cout, ", "}, a_xxx_b); std::cout << "\n"; } int main() { auto twice([](int i){return i*2;}); auto thrice([](int i){return i*3;}); auto combine([](auto x, auto y) {return x*y;}); auto combined( concat(twice, twice, thrice, thrice, std::plus<int>{}) ); std::cout << combined(2,3) << std::endl; test1(); }
// ============================================================================ // Data Structures For Game Programmers // Ron Penton // HashTable.h // This file holds the Linekd Hash Table implementation. // ============================================================================ #ifndef GNMAP_H #define GNMAP_H #include "GnSystem.h" #include "GnList.h" #include "GnTArray.h" // ------------------------------------------------------- // Name: GnHashEntry // Description: This is the hash table entry class. It // stores a key and data pair. // ------------------------------------------------------- template< class KeyType, class DataType > class GNSYSTEM_ENTRY GnHashEntry : public GnMemoryObject { public: KeyType m_key; DataType m_data; ~GnHashEntry() { GnT::PointerTraits<DataType>::SetNull(m_data); } }; template<class KeyType> class GnDefaultMapHash { public: static gtuint HashIndex( KeyType key ) { return (gtuint)key; } }; template<class KeyType> class GnDefaultEqual { public: static bool IsEqual(KeyType key1, KeyType key2) { return key1 == key2; } }; template < class KeyType, class DataType, template<class> class DataDeallocate = GnDefaultDeallocate, template<class> class MapHash = GnDefaultMapHash, template<class> class MapEqual = GnDefaultEqual > class GnTMap; // ------------------------------------------------------- // Name: HashTable // Description: This is the hashtable class. // ------------------------------------------------------- template < class KeyType, class DataType, template<class> class DataDeallocate, template<class> class MapHash, template<class> class MapEqual > class GNSYSTEM_ENTRY GnTMap : public GnMemoryObject { public: // typedef the entry class to make is easier to work with. typedef GnHashEntry<KeyType, DataType> Entry; typedef GnListIterator<Entry, DataDeallocate> Iterator; protected: gtuint m_size; gtuint m_count; GnTPrimitiveArray< GnList<Entry, DataDeallocate>* > m_table; public: GnTMap( int p_size = 30 ) : m_table( p_size ) { // set the size, hash function, and count. m_size = p_size; m_count = 0; for (gtuint i = 0 ; i < m_size ; i++) { m_table.SetAt(i, GnNew GnList<Entry, DataDeallocate>); } } virtual ~GnTMap() { RemoveAll(); for (gtuint i = 0 ; i < m_size ; i++) GnDelete m_table.GetAt(i); } // ---------------------------------------------------------------- // Name: Insert // Description: Inserts a new key/data pair into the table. // Arguments: p_key: the key // p_data: the data attached to the key. // Return Value: None // ---------------------------------------------------------------- void Insert( KeyType p_key, DataType p_data ) { GnAssert( Find(p_key) == false ); // create an entry structure. Entry entry; SetValue(entry, p_key, p_data); // get the hash value from the key, and modulo it // so that it fits within the table. gtuint index = MapHash<KeyType>::HashIndex( p_key ) % m_size; // add the entry to the correct index, increment the count. m_table[index]->Append( entry ); m_count++; } // ---------------------------------------------------------------- // Name: Find // Description: Finds a key in the table // Arguments: p_key: the key to search for // Return Value: a pointer to the entry that has the key/data, // or 0 if not found. // ---------------------------------------------------------------- Entry* Find( KeyType p_key ) { // find out which index the key should exist in gtuint index = MapHash<KeyType>::HashIndex( p_key ) % m_size; // get an iterator for the list in that index. GnListIterator<Entry, DataDeallocate> itr = m_table[index]->GetIterator(); // search each item while( itr.Valid() ) { // if the keys match, then return a pointer to the entry if( MapEqual<KeyType>::IsEqual( itr.Item().m_key, p_key ) ) return &(itr.Item()); itr.Forth(); } // no match was found, return 0. return 0; } inline void SetAt(KeyType p_key, DataType data, bool bDelete = false) { Entry* entry = Find(p_key); if( entry ) { if( bDelete ) DataDeallocate<Entry>::Delete(*entry); entry->m_data = data; return; } Insert(p_key, data); } inline bool GetAt(KeyType p_key, DataType& outData) { Entry* entry = Find(p_key); if( entry == NULL ) return false; outData = entry->m_data; return true; } // ---------------------------------------------------------------- // Name: Remove // Description: Removes an entry based on key // Arguments: p_key: the key // Return Value: true if removed, false if not found. // ---------------------------------------------------------------- bool Remove( KeyType p_key, bool bDelete = false ) { // find the index that the key should be in. gtuint index = MapHash<KeyType>::HashIndex( p_key ) % m_size; // get an iterator for the list in that index. GnListIterator<Entry, DataDeallocate> itr = m_table[index]->GetIterator(); // search each item while( itr.Valid() ) { // if the keys match, then remove the node, and return true. if( MapEqual<KeyType>::IsEqual( itr.Item().m_key, p_key ) ) { ClearValue( itr.Item() ); m_table[index]->Remove( itr, bDelete ); m_count--; return true; } itr.Forth(); } // item wasn't found, return false. return false; } inline void RemoveAll(bool bDelete = false) { for ( gtuint i = 0 ; i < m_size ; i++ ) { GnListIterator<Entry, DataDeallocate> itr = m_table[i]->GetIterator(); while( itr.Valid() ) { ClearValue( itr.Item() ); itr.Forth(); } m_table[i]->RemoveAll(bDelete); } m_count = 0; } void GetFirstIter(GnListIterator<Entry, DataDeallocate>& outIter) { for ( gtuint i = 0 ; i < m_size ; i++ ) { GnListIterator<Entry, DataDeallocate> itr = m_table[i]->GetIterator(); if( itr.Valid() ) { outIter = itr; return; } } outIter.m_list = NULL; outIter.m_node = NULL; } void GetNextIter(GnListIterator<Entry, DataDeallocate>& inOutIter) { GnAssert(inOutIter.Valid()); GnListIterator<Entry, DataDeallocate> outIter = inOutIter; outIter.Forth(); if( outIter.Valid() ) { inOutIter = outIter; return; } Entry ent = inOutIter.Item(); gtuint i = MapHash<KeyType>::HashIndex( ent.m_key ) % m_size; for ( ++i ; i < m_size ; i++ ) { GnListIterator<Entry, DataDeallocate> itr = m_table[i]->GetIterator(); if( itr.Valid() ) { inOutIter = itr; return; } } inOutIter.m_list = NULL; inOutIter.m_node = NULL; } // ---------------------------------------------------------------- // Name: Count // Description: Gets the number of entries in the table. // Arguments: None // Return Value: Number of entries in the table. // ---------------------------------------------------------------- int Count() { return m_count; } protected: virtual void SetValue(Entry& item, KeyType key, DataType val) { item.m_key = key; item.m_data = val; } virtual void ClearValue(Entry& item) { } }; template < class KeyType, class DataType, template<class> class DataDeallocate = GnObjectMapEntityDeallocate, template<class> class MapHash = GnDefaultMapHash, template<class> class MapEqual = GnDefaultEqual > class GnTObjectDeleteMap; template < class KeyType, class DataType, template<class> class DataDeallocate, template<class> class MapHash, template<class> class MapEqual > class GnTObjectDeleteMap : public GnTMap<KeyType, DataType, DataDeallocate, MapHash, MapEqual> { public: GnTObjectDeleteMap(gtuint size = 5) : GnTMap<KeyType, DataType, DataDeallocate, MapHash, MapEqual>(size) { } }; template < class KeyType, class DataType, template<class> class DataDeallocate = GnPrimitiveMapEntityDeallocate, template<class> class MapHash = GnDefaultMapHash, template<class> class MapEqual = GnDefaultEqual > class GnTPrimitiveDeleteMap; template < class KeyType, class DataType, template<class> class DataDeallocate, template<class> class MapHash, template<class> class MapEqual > class GnTPrimitiveDeleteMap : public GnTMap<KeyType, DataType, DataDeallocate, MapHash, MapEqual> { public: GnTPrimitiveDeleteMap(gtuint size = 5) : GnTMap<KeyType, DataType, DataDeallocate, MapHash, MapEqual>(size) { } }; #endif // #ifndef GNMAP_H
// // Matrix3x3.h // Odin.MacOSX // // Created by Daniel on 24/09/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef Odin_MacOSX_Matrix3x3_h #define Odin_MacOSX_Matrix3x3_h #include "Matrix.h" #include <initializer_list> #include <cassert> namespace odin { namespace math { // Specialization for matrix 3x3 template <typename T> class Matrix<T,3,3> { public: Matrix<T,3,3>(); Matrix<T,3,3>(T m00, T m01, T m02, T m10, T m11, T m12, T m20, T m21, T m22); Matrix<T,3,3>(std::initializer_list<T> l); Matrix<T,3,3>(T v); explicit Matrix<T,3,3>(const Vector<T,3>& u, const Vector<T,3>& v, const Vector<T,3>& w); template <typename U> explicit Matrix<T,3,3>(const Matrix<U,3,3>& m); explicit Matrix<T,3,3>(const Matrix<T,2,2>& m); explicit Matrix<T,3,3>(const Matrix<T,2,3>& m); explicit Matrix<T,3,3>(const Matrix<T,2,4>& m); explicit Matrix<T,3,3>(const Matrix<T,3,2>& m); explicit Matrix<T,3,3>(const Matrix<T,3,4>& m); explicit Matrix<T,3,3>(const Matrix<T,4,2>& m); explicit Matrix<T,3,3>(const Matrix<T,4,3>& m); explicit Matrix<T,3,3>(const Matrix<T,4,4>& m); ~Matrix<T,3,3>(); Matrix<T,3,3>& operator = (const Matrix<T,3,3>& m); Vector<T,3>& operator[](UI32 i); const Vector<T,3>& operator[](UI32 i) const; private: Vector<T,3> data[3]; }; template <typename T> T determinant(const Matrix<T,3,3>& m); template <typename T> Matrix<T,3,3> inverse(const Matrix<T,3,3>& m); template <typename T> Matrix<T,3,3> operator / (const Matrix<T,3,3>& left, const Matrix<T,3,3>& right); template <typename T> Matrix<T,3,3>& operator /= (Matrix<T,3,3>& left, const Matrix<T,3,3>& right); typedef Matrix<F32,3,3> mat3; typedef Matrix<F32,3,3> mat3x3; typedef Matrix<F64,3,3> dmat3; typedef Matrix<F64,3,3> dmat3x3; #include "Matrix3x3.inl" } } #endif
#ifndef SLOT_H #define SLOT_H #include <string> class Slot { public: Slot ( std::string type ); int get_count_available() const; std::string get_type() const; void set_type ( const std::string& new_type ); int get_count() const; void add ( int quantity ); void reserve ( int quantity ); private: std::string type; int count; int reserved_count; }; #endif
#pragma once #include <SFML/Graphics.hpp> namespace Sonar { class InputManager { public: InputManager() = default; ~InputManager() = default; bool IsSpriteClicked(const sf::Sprite& object, sf::Mouse::Button button, const sf::RenderWindow& window) const; sf::Vector2i GetMousePosition(const sf::RenderWindow& window) const; }; }
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Gogul Balakrishnan, Akash Lal, Thomas Reps // University of Wisconsin, Madison. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // 3. Neither the name of the University of Wisconsin, Madison nor the // names of its contributors may be used to endorse or promote // products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // e-mail: bgogul@cs.wisc.edu, akash@cs.wisc.edu, reps@cs.wisc.edu // ////////////////////////////////////////////////////////////////////////////// #include "ARConfig.hpp" #include "Matrix.hpp" #include <iostream> namespace AR { // // Initialize the hashtable used for canoncial matrices // RCMatrix::CnclMats* RCMatrix::cnclMats = NULL; Matrix::ProdCache* Matrix::prodCache = NULL; const float Matrix::cacheEntryThreshold = 0.90f; // const Matrix::ProdCache::size_type Matrix::maxProdCacheSize = 100000; // Max size of cache MatrixPair::MatrixPairUsage_t Matrix::transAccessCnt = 1; // // Some stats unsigned int Matrix::cacheHits = 0; unsigned int Matrix::cacheAccesses = 0; unsigned int Matrix::nMats = 0; //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // O v e r l o a d e d < < O p e r a t o r s //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // R C M A T R I X I M P L E M E N T A T I O N //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // // Decrease ref count // void RCMatrix::decrRef() { assert(count > 0); count = (satRef?count:--count); if(!count) { if(cnclMats) cnclMats->erase(MatrixDimPair_t(mat, N)); delete this; } } // // Increase ref count // void RCMatrix::incrRef() { if(!satRef) { if(count == UINT_MAX) satRef = true; else count++; } return; } //---------------------------------------------- // Compute the haskey for a given matrix //---------------------------------------------- RCMatrix::MatrixHkey_t RCMatrix::computeHashKey(const int* p, unsigned _N) { // FIXME: this should be made better? unsigned int rv; int i = 0; rv = _N; const int* matPtr = p; unsigned NbyN = _N * _N; // const row // for(i = 0; i < _N; ++i) { rv = 997 * rv + *matPtr; matPtr++; } // diagonal matPtr = p; for(i = 0; i < _N; ++i) { rv = 997 * rv + *matPtr; matPtr += (_N + 1); } /* for(i =0; i < NbyN; ++i) { rv = 997 * rv + *matPtr; matPtr++; } */ return rv; } //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // M A T R I X I M P L E M E N T A T I O N //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //------------------------------------- // Get the canonical matrix //------------------------------------- RCMatrix* RCMatrix::getCnclMatrix(const int* p, unsigned _N) { if(!cnclMats) { // Default settings... cnclMats = new RCMatrix::CnclMats(100000); } // Nick's Hash RCMatrix::MatrixDimPair_t pn(p, _N); CnclMats::iterator it = cnclMats->find(pn); // insert it if not there if( it == cnclMats->end() ) { RCMatrix* m = new RCMatrix( p, _N ); cnclMats->insert( CnclMats::value_type( MatrixDimPair_t(m->mat, m->N), m ) ); m->incrRef(); return m; } else { RCMatrix* m = (*it).second; m->incrRef(); return m; } } //------------------------------------- // Delete (cleanup) the table of canonical matrices //------------------------------------- void RCMatrix::deleteCnclMatrices() { if(cnclMats){ delete cnclMats; cnclMats = NULL; } } void Matrix::clearCaches() { RCMatrix::deleteCnclMatrices(); if(prodCache){ delete Matrix::prodCache; prodCache = 0; } } void Matrix::printMatrixStats(FILE* fp) { fprintf(fp, "Cache Behaviour:\n"); fprintf(fp, " Hits:\t%u\n", cacheHits); fprintf(fp, " Accesses:\t%u\n", cacheAccesses); if(cacheAccesses) fprintf(fp, " Hit Rate:\t%.2f\n", (float)cacheHits/cacheAccesses); fprintf(fp, "Canonical Mats:\n"); fprintf(fp, "Total Nr Of Matrices:\t%u\n", nMats); fprintf(fp, "CnclMatrixTable:"); /* if(RCMatrix::cnclMats) RCMatrix::cnclMats->PrintHashDist(fp); fprintf(fp, "Product Cache:"); if(prodCache) prodCache->PrintHashDist(fp); */ } //------------------- // Print //------------------- void Matrix::Print(std::ostream & out) const { int x = 0; out << "[" << std::endl; for(int i = 0; i < getDim(); i++) { out << " "; for(int j = 0; j < getDim(); j++) { out << rcmat->mat[x] << ", "; x++; } out << std::endl; } out << "]"; return; } //------------------- // Print //------------------- void Matrix::prettyPrint(FILE* fp) const { unsigned N = getDim(); int x = 0; fprintf(fp, "[\n"); for(int i = 0; i < N; i++) { fprintf(fp, " "); for(int j = 0; j < N; j++) { fprintf(fp, "%d, ", rcmat->mat[x]); x++; } fprintf(fp, "\n"); } fprintf(fp, "]"); return; } std::ostream& operator<< (std::ostream & out, const Matrix &m) { m.Print(out); return(out); } //--------------------------------- // Default constructor // // Creates the identity matrix //--------------------------------- Matrix::Matrix(unsigned N) { int *tempMatrix = new int[N * N]; int *p = tempMatrix; for(unsigned i = 0; i < N; i++) { for(unsigned j = 0; j < N; j++) { if (i == j) { *p = 1; } else { *p = 0; } p++; } } rcmat = RCMatrix::getCnclMatrix(tempMatrix, N); delete tempMatrix; nMats++; } //------------------------------------ // Return the identity matrix //------------------------------------ Matrix Matrix::mkId(unsigned N) { static unsigned curN = 0; static Matrix* m = NULL; if(curN == N) { return *m; } curN = N; delete m; m = new Matrix(N); return *m; //static Matrix m(N); // Default constructor creates the identity matrix //return m; } //------------------------------------- // Return a transposed matrix. // ------------------------------------ Matrix Matrix::transpose(const Matrix& m) { unsigned N = m.getDim(); // allocate space for result static unsigned lastN = 0; static int *p = NULL; if(lastN < N) { p = new int[N * N]; lastN = N; } int *q = m.rcmat->mat; for (unsigned i = 0; i < N; i++) { for (unsigned j = 0; j < N; j++) { p[i * N + j] = q[j * N + i]; } } return Matrix(p, N); } //------------------- // Add two matrices //------------------- Matrix Matrix::add(const Matrix& mat1, const Matrix& mat2) { assert(mat1.getDim() == mat2.getDim()); unsigned N = mat1.getDim(); // allocate space for result static unsigned lastN = 0; static int *result = NULL; if(lastN < N) { result = new int[N * N]; lastN = N; } unsigned i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { result[i * N + j] = mat1[i * N + j] + mat2[i * N + j]; } } return Matrix(result, N); } //------------------------------------ // Find the difference of two matrices //------------------------------------ Matrix Matrix::subtract(const Matrix& mat1, const Matrix& mat2) { assert(mat1.getDim() == mat2.getDim()); unsigned N = mat1.getDim(); // allocate space for result static unsigned lastN = 0; static int *result = NULL; if(lastN < N) { result = new int[N * N]; lastN = N; } unsigned i, j; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { result[i * N + j] = mat1[i * N + j] - mat2[i * N + j]; } } return Matrix(result, N); } //------------------------ // Multiply two matrices //------------------------ Matrix Matrix::multiply(const Matrix& mat1, const Matrix& mat2) { assert(mat1.getDim() == mat2.getDim()); unsigned N = mat1.getDim(); // allocate space for result static unsigned lastN = 0; static int *multResult = NULL; if(lastN < N) { multResult = new int[N * N]; lastN = N; } #ifdef NO_PROD_CACHING multiplyMatrices(multResult, mat1.rcmat->mat, mat2.rcmat->mat, N); Matrix *m = new Matrix(multResult, mat1.getDim()); return m; #else if(!prodCache) prodCache = new ProdCache(200000); cacheAccesses++; Matrix* m; MatrixPair pair(mat1.rcmat, mat2.rcmat); ProdCache::iterator it = prodCache->find(pair); // insert it if not there if( it == prodCache->end() ) { // Not in cache multiplyMatrices(multResult, mat1.rcmat->mat, mat2.rcmat->mat, N); m = new Matrix(multResult, N); prodCache->insert( ProdCache::value_type( pair, m->rcmat ) ); m->rcmat->incrRef(); // Account for the fact that rcmat is in prodCache // FIXME: Need a policy to remove matrices in prodCache } else { cacheHits++; m = new Matrix((*it).second); (*it).first.incUsageCnt(); assert(m->rcmat->mat); } #ifdef VSA_ARA_USE_LFU_POLICY // Throw away least-frequently used cache entries MatrixPair::incUsageCnt(transAccessCnt); if(prodCache->size() >= maxProdCacheSize) { std::vector<MatrixPair> toBeRemoved; // Mark entries whose usage is below threshold ProdCache::iterator beg = prodCache->begin(); ProdCache::iterator end = prodCache->end(); while(beg != end) { if(((float)(*beg).first.getUsageCnt()/transAccessCnt) < cacheEntryThreshold) { toBeRemoved.push_back((*beg).first); } beg++; } // Remove the marked entries for(unsigned i = 0; i < toBeRemoved.size(); ++i) { ProdCache::iterator it = prodCache->find(toBeRemoved[i]); // NOTE: it cannot be end (*it).second->decrRef(); // Update reference count for RCmatrix prodCache->erase(it); } transAccessCnt = 1; } #endif // FIXME: A bit clumsy here . . . Matrix retM = *m; delete m; return retM; #endif // NO_PROD_CACHING } //---------------------------------- // Multiply two matrices (Helper) //---------------------------------- void Matrix::multiplyMatrices(int* multResult, const int *op1,const int *op2, unsigned N) { unsigned i, j, k; for(i = 0; i < N; ++i) { for(j = 0; j < N; ++j) { multResult[i * N + j]=0; for(k = 0; k < N; ++k) { multResult[i * N + j] += op1[i * N + k] * op2[k * N + j]; } } } } } // namespace AR
#include <sstream> #include <iostream> #include <string> #include <fstream> #include "generator.h" //-------------------------------------------------------------------------------------------------- GlobalSpaceGen* AbstractGen::globalSpaceGenPtr = nullptr; //-------------------------------------------------------------------------------------------------- void GlobalVarGen::Generate(std::string &str) { str = type; str += " > "; str += name; } void GlobalVarGen::GenValue(std::string &str) { str = name; str += ".set "; str += value; } //-------------------------------------------------------------------------------------------------- void GlobalFuncGen::Generate(std::string &str) { // Первоначально осуществляется генерация списка атрибутов str = "["; if(name == "main") { str += "arg] > main\n"; } else { for(auto paramName: paramNames) { str += paramName; str += ", "; } str += "ret_param_xxxx] > "; str += name; str += "\n"; } // Далее идет формирование тела функции, которое пока не прописано str += " seq > @\n"; str += " ...\n"; } void GlobalFuncGen::GenValue(std::string &str) { if(name == "main") { str += "\n main arg\n"; } } //-------------------------------------------------------------------------------------------------- void GlobalSpaceGen::Generate(std::string &str) { str = ""; // Формирование списка глобальных объектов std::string strObj = ""; for(auto globalObject: globalObjects) { globalObject->Generate(strObj); str += " "; str += strObj; str += "\n"; } } void GlobalSpaceGen::GenValue(std::string &str) { // Формирование списка инициализаций for(auto globalObject: globalObjects) { std::string strInit = ""; globalObject->GenValue(strInit); str += " "; str += strInit; str += "\n"; } //str += "\n"; } //........................................................................ // Добавление очередного объекта к глобальному пространству void GlobalSpaceGen::Add(AbstractGen* obj) { globalObjects.push_back(obj); } //-------------------------------------------------------------------------------------------------- void ApplicationGen::Generate(std::string &str) { str = "+package c2eo\n\n" "+alias global c2eo.global\n\n" "[args...] > app\n" " seq > @\n" " global args\n"; } //-------------------------------------------------------------------------------------------------- void FullGen::Generate(std::string &str) { }
#include "OgreFramework.h" using namespace Ogre; template<> OgreFramework* Ogre::Singleton<OgreFramework>::msSingleton = 0; /// <summary> /// Initializes a new instance of the <see cref="OgreFramework"/> class. Just init some required variables. /// </summary> OgreFramework::OgreFramework() { m_MoveSpeed = 0.4f; m_RotateSpeed = 0.3f; m_bShutDownOgre = false; m_iNumScreenShots = 0; m_pRoot = 0; m_pSceneMgr = 0; m_pRenderWnd = 0; m_pCamera = 0; m_pViewport = 0; m_pLog = 0; m_pTimer = 0; m_pInputMgr = 0; m_pKeyboard = 0; m_pMouse = 0; m_pTrayMgr = 0; m_FrameEvent = Ogre::FrameEvent(); } /// <summary> /// Inits the ogre framework. /// 1.Instantiates the log manager class /// 2. Creates a new Ogre root /// 3. Creates the scene manager and set some ambient light /// 4. Creates the camera and sets its position and clip planes /// 5. Creates the viewport and sets the background color /// 6. Creates the input devices /// 7. Loads the resources /// 8. Creates the timer /// 9. Creates the debug overlay /// 10. Sets the render window active /// </summary> /// <param name="wndTitle">The WND title.</param> /// <param name="pKeyListener">The p key listener.</param> /// <param name="pMouseListener">The p mouse listener.</param> /// <returns></returns> bool OgreFramework::initOgre(Ogre::String wndTitle, Ogre::SceneType sceneType, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener ) { Ogre::LogManager* logMgr = new Ogre::LogManager(); m_pLog = Ogre::LogManager::getSingleton().createLog("OgreLogfile.log", true, true, false); m_pLog->setDebugOutputEnabled(true); m_pRoot = new Ogre::Root("plugins.cfg"); if(!m_pRoot->showConfigDialog()) return false; m_pRenderWnd = m_pRoot->initialise(true, wndTitle); m_pSceneMgr = m_pRoot->createSceneManager(sceneType, "SceneManager"); Ogre::Vector3 lightdir(0.55, -0.3, 0.75); lightdir.normalise(); m_light = m_pSceneMgr->createLight("tstLight"); m_light->setType(Ogre::Light::LT_DIRECTIONAL); m_light->setDirection(lightdir); m_light->setDiffuseColour(Ogre::ColourValue::White); m_light->setSpecularColour(Ogre::ColourValue(0.4, 0.4, 0.4)); m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f)); m_cameraNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode("CameraNode"); m_cameraNode->setPosition(Vector3(0, 60, 60)); m_pCamera = m_pSceneMgr->createCamera("Camera"); m_pCamera->setNearClipDistance(1); m_pViewport = m_pRenderWnd->addViewport(m_pCamera); m_pViewport->setBackgroundColour(Ogre::ColourValue::Blue); m_pCamera->setAspectRatio(Real(m_pViewport->getActualWidth()) / Real(m_pViewport->getActualHeight())); m_pViewport->setCamera(m_pCamera); m_cameraNode->attachObject(m_pCamera); size_t hWnd = 0; m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd); m_pInputMgr = OIS::InputManager::createInputSystem(hWnd); m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true)); m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true)); m_pMouse->getMouseState().height = m_pRenderWnd->getHeight(); m_pMouse->getMouseState().width = m_pRenderWnd->getWidth(); if(pKeyListener == 0) m_pKeyboard->setEventCallback(this); else m_pKeyboard->setEventCallback(pKeyListener); if(pMouseListener == 0) m_pMouse->setEventCallback(this); else m_pMouse->setEventCallback(pMouseListener); Ogre::String secName, typeName, archName; Ogre::ConfigFile cf; cf.load("resources.cfg"); Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); m_pTimer = new Ogre::Timer(); m_pTimer->reset(); OgreBites::InputContext inputContext = OgreBites::InputContext::InputContext(); inputContext.mMouse = m_pMouse; /* m_pTrayMgr = new OgreBites::SdkTrayManager("TrayMgr", m_pRenderWnd, inputContext, this); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->hideCursor(); */ m_pRenderWnd->setActive(true); return true; } /// <summary> /// Finalizes an instance of the <see cref="OgreFramework"/> class. /// </summary> OgreFramework::~OgreFramework() { if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr); if(m_pTrayMgr) delete m_pTrayMgr; if(m_pRoot) delete m_pRoot; if(m_pTimer) delete m_pTimer; } /// <summary> /// Interacts agains the keyPressedEvent. /// </summary> /// <param name="keyEventRef">The key event ref.</param> /// <returns></returns> bool OgreFramework::keyPressed(const OIS::KeyEvent &keyEventRef) { if(m_pKeyboard->isKeyDown(OIS::KC_ESCAPE)) { m_bShutDownOgre = true; return true; } if(m_pKeyboard->isKeyDown(OIS::KC_SYSRQ)) { m_pRenderWnd->writeContentsToTimestampedFile("BOF_Screenshot_", ".png"); return true; } if(m_pKeyboard->isKeyDown(OIS::KC_M)) { static int mode = 0; if(mode == 2) { m_pCamera->setPolygonMode(PM_SOLID); mode = 0; } else if(mode == 0) { m_pCamera->setPolygonMode(PM_WIREFRAME); mode = 1; } else if(mode == 1) { m_pCamera->setPolygonMode(PM_POINTS); mode = 2; } } if(m_pKeyboard->isKeyDown(OIS::KC_O)) { if(m_pTrayMgr->isLogoVisible()) { m_pTrayMgr->hideLogo(); m_pTrayMgr->hideFrameStats(); } else { m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); } } return true; } /// <summary> /// Keys the released. /// </summary> /// <param name="keyEventRef">The key event ref.</param> /// <returns></returns> bool OgreFramework::keyReleased(const OIS::KeyEvent &keyEventRef) { return true; } /// <summary> /// Mouses the moved. /// </summary> /// <param name="evt">The evt.</param> /// <returns></returns> bool OgreFramework::mouseMoved(const OIS::MouseEvent &evt) { m_cameraNode->yaw(Degree(evt.state.X.rel * -0.1f)); m_cameraNode->pitch(Degree(evt.state.Y.rel * -0.1f)); return true; } /// <summary> /// Mouses the pressed. /// </summary> /// <param name="evt">The evt.</param> /// <param name="id">The id.</param> /// <returns></returns> bool OgreFramework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { return true; } /// <summary> /// Mouses the released. /// </summary> /// <param name="evt">The evt.</param> /// <param name="id">The id.</param> /// <returns></returns> bool OgreFramework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { return true; } /// <summary> /// Updates the ogre. /// </summary> /// <param name="timeSinceLastFrame">The time since last frame.</param> void OgreFramework::updateOgre(double timeSinceLastFrame) { m_MoveScale = m_MoveSpeed * (float)timeSinceLastFrame; m_RotScale = m_RotateSpeed * (float)timeSinceLastFrame; m_TranslateVector = Vector3::ZERO; getInput(); moveCamera(); m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame; // TODO: check the overlay system. // m_pTrayMgr->frameRenderingQueued(m_FrameEvent); } /// <summary> /// Moves the camera. /// </summary> void OgreFramework::moveCamera() { if(m_pKeyboard->isKeyDown(OIS::KC_LSHIFT)) { m_cameraNode->translate(m_cameraNode->getOrientation() * m_TranslateVector); } else { m_cameraNode->translate(m_cameraNode->getOrientation() * (m_TranslateVector / 10)); } } /// <summary> /// Gets the input. /// </summary> void OgreFramework::getInput() { if(m_pKeyboard->isKeyDown(OIS::KC_A)) m_TranslateVector.x = -m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_D)) m_TranslateVector.x = m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_W)) m_TranslateVector.z = -m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_S)) m_TranslateVector.z = m_MoveScale; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/GameState.h" #include "MyGameState.generated.h" /** * */ UCLASS() class FIGHTWITHBLOCK_API AMyGameState : public AGameState { GENERATED_BODY() AMyGameState(); UPROPERTY(EditAnywhere, Category = "MapProperty") int32 MapSize = 2; UPROPERTY(EditAnywhere, Category = "MapProperty") int32 BlockSize = 260; UPROPERTY(EditAnywhere, Category = "MapProperty") int32 MaxZ = 1; void GenerateGround_(); void GenerateGround(); UFUNCTION(reliable, NetMulticast, WithValidation) void ServerGenerateGround(); class ABlockBase* SpawnBlock(const struct FBlock* Block, float Size); protected: virtual void BeginPlay() override; private: TArray<class ABlockBase*> AllBlockInfo; TArray<FName> GroundRowNames; TArray<FName> SurfaceRowNames; UDataTable* GroundDataTable; UDataTable* SurfaceDataTable; };
// // Created by Lee on 2019-04-22. // #ifndef UBP_CLIENT_CPP_VER_JSONPARSER_H #define UBP_CLIENT_CPP_VER_JSONPARSER_H #include <vector> #include <QJsonObject> #include "Photo.h" #include "PhotoGroup.h" class JsonParser { public: static Photo jsonToPhoto(QJsonObject json); static PhotoGroup jsonToPhotoGroup(QJsonObject json); static std::vector<PhotoGroup> jsonToPhotoGroupVector(QJsonArray json); }; #endif //UBP_CLIENT_CPP_VER_JSONPARSER_H
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "UnrealAI/UnrealAI Fundamentals/AI_FundamentalController.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeAI_FundamentalController() {} // Cross Module References UNREALAI_API UClass* Z_Construct_UClass_AAI_FundamentalController_NoRegister(); UNREALAI_API UClass* Z_Construct_UClass_AAI_FundamentalController(); AIMODULE_API UClass* Z_Construct_UClass_AAIController(); UPackage* Z_Construct_UPackage__Script_UnrealAI(); AIMODULE_API UClass* Z_Construct_UClass_UBlackboardComponent_NoRegister(); // End Cross Module References void AAI_FundamentalController::StaticRegisterNativesAAI_FundamentalController() { } UClass* Z_Construct_UClass_AAI_FundamentalController_NoRegister() { return AAI_FundamentalController::StaticClass(); } struct Z_Construct_UClass_AAI_FundamentalController_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CurrentBlackboard_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CurrentBlackboard; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AAI_FundamentalController_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AAIController, (UObject* (*)())Z_Construct_UPackage__Script_UnrealAI, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AAI_FundamentalController_Statics::Class_MetaDataParams[] = { { "HideCategories", "Collision Rendering Utilities|Transformation" }, { "IncludePath", "UnrealAI Fundamentals/AI_FundamentalController.h" }, { "ModuleRelativePath", "UnrealAI Fundamentals/AI_FundamentalController.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AAI_FundamentalController_Statics::NewProp_CurrentBlackboard_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "AI" }, { "Comment", "/** blackboard */" }, { "EditInline", "true" }, { "ModuleRelativePath", "UnrealAI Fundamentals/AI_FundamentalController.h" }, { "ToolTip", "blackboard" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AAI_FundamentalController_Statics::NewProp_CurrentBlackboard = { "CurrentBlackboard", nullptr, (EPropertyFlags)0x004000000008001c, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AAI_FundamentalController, CurrentBlackboard), Z_Construct_UClass_UBlackboardComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AAI_FundamentalController_Statics::NewProp_CurrentBlackboard_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_AAI_FundamentalController_Statics::NewProp_CurrentBlackboard_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AAI_FundamentalController_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AAI_FundamentalController_Statics::NewProp_CurrentBlackboard, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AAI_FundamentalController_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AAI_FundamentalController>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AAI_FundamentalController_Statics::ClassParams = { &AAI_FundamentalController::StaticClass, "Engine", &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_AAI_FundamentalController_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_AAI_FundamentalController_Statics::PropPointers), 0, 0x009002A4u, METADATA_PARAMS(Z_Construct_UClass_AAI_FundamentalController_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AAI_FundamentalController_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AAI_FundamentalController() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AAI_FundamentalController_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AAI_FundamentalController, 76344303); template<> UNREALAI_API UClass* StaticClass<AAI_FundamentalController>() { return AAI_FundamentalController::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_AAI_FundamentalController(Z_Construct_UClass_AAI_FundamentalController, &AAI_FundamentalController::StaticClass, TEXT("/Script/UnrealAI"), TEXT("AAI_FundamentalController"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AAI_FundamentalController); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
#pragma once #include "Field.h" class Player { protected: Field* field; public: bool inGame = true; virtual void Update() = 0; virtual int GetSymbol(int i, int j) { return field->GetSymbol(i, j); } virtual int GetScore() { return field->GetScore(); } virtual int GetLines() { return field->GetLines(); } };