blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
d756e015beb8cedce2293326d1c7430e9bc4b913
986d745d6a1653d73a497c1adbdc26d9bef48dba
/stdlib/cont/mset1.cpp
acfec557f18b3ab29dc119ad579e6c1edeabd997
[ "LicenseRef-scancode-other-permissive" ]
permissive
AnarNFT/books-code
879f75327c1dad47a13f9c5d71a96d69d3cc7d3c
66750c2446477ac55da49ade229c21dd46dffa99
refs/heads/master
2021-01-20T23:40:30.826848
2011-01-17T11:14:34
2011-01-17T11:14:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,110
cpp
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <set> #include <algorithm> #include <iterator> using namespace std; int main() { /* type of the collection: * - duplicates allowed * - elements are integral values * - descending order */ typedef multiset<int,greater<int> > IntSet; IntSet coll1; // empty multiset container // insert elements in random order coll1.insert(4); coll1.insert(3); coll1.insert(5); coll1.insert(1); coll1.insert(6); coll1.insert(2); coll1.insert(5); // iterate over all elements and print them IntSet::iterator pos; for (pos = coll1.begin(); pos != coll1.end(); ++pos) { cout << *pos << ' '; } cout << endl; // insert 4 again and process return value IntSet::iterator ipos = coll1.insert(4); cout << "4 inserted as element " << distance(coll1.begin(),ipos) + 1 << endl; // assign elements to another multiset with ascending order multiset<int> coll2(coll1.begin(), coll1.end()); // print all elements of the copy copy (coll2.begin(), coll2.end(), ostream_iterator<int>(cout," ")); cout << endl; // remove all elements up to element with value 3 coll2.erase (coll2.begin(), coll2.find(3)); // remove all elements with value 5 int num; num = coll2.erase (5); cout << num << " element(s) removed" << endl; // print all elements copy (coll2.begin(), coll2.end(), ostream_iterator<int>(cout," ")); cout << endl; }
[ [ [ 1, 71 ] ] ]
b679e92f8bfd58ea633fab0e74310e6fa24f9fae
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/__ffl_dump/source/ffl_dump_unexception_filter.cpp
f00040d1d002810711732800093843bed0412c5f
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
6,262
cpp
#include "../include/ffl_dump_unexception_filter.h" #include "../include/ffl_dump_mini.h" #include "../include/ffl_dump_report.h" #include "../include/ffl_dump_log.h" #include "../include/ffl_c_string.h" #include "../include/ffl_date_time.h" #include <process.h> #include <cstdio> #include <cstdlib> #if defined(_MSC_VER) && (_MSC_VER > 1310) static void ffl_invalid_parameter( const wchar_t * /* expression */, const wchar_t * /* function */, const wchar_t * /* file */, unsigned int /* line */, uintptr_t /* reserved */ ) { ::RaiseException( EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL ); } #endif static void ffl_purecall_handler() { ::RaiseException( EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL ); } static void make_file_name( ffl_tchar_t * output, size_t output_count, const ffl_tchar_t * prefix, const ffl_tchar_t * ext ) { if( output != NULL && output_count > 0 && prefix != NULL && ext != NULL ) { ffl_tchar_t module_name[MAX_PATH] = { 0, }; if( ::GetModuleFileName( NULL, module_name, FFL_COUNTOF( module_name ) ) <= 0 ) { static const ffl_tchar_t unknown[] = FFL_T( "Unknown" ); ffl_strncpy( module_name, FFL_COUNTOF( module_name ), unknown, FFL_COUNTOF( unknown ) ); } ffl_date_time date; ffl_tchar_t drive[_MAX_DRIVE] = { 0, }; ffl_tchar_t dir[_MAX_DIR] = { 0, }; ffl_tchar_t name[_MAX_FNAME] = { 0, }; ffl_tchar_t temp[MAX_PATH] = { 0, }; ffl_splitpath( module_name, drive, FFL_COUNTOF( drive ), dir, FFL_COUNTOF( dir ), name, FFL_COUNTOF( name ), NULL, 0 ); static const ffl_tchar_t file_name_format[] = FFL_T( "%s%s_%d.%d.%d_%d.%d.%d.%s" ); ffl_snprintf( temp, FFL_COUNTOF( temp ), file_name_format, prefix, name, date.year(), date.month(), date.day(), date.hour(), date.minute(), date.second(), ext ); ffl_makepath( output, output_count, drive, dir, temp, NULL ); int count = 0; DWORD attr = ::GetFileAttributes( output ); while( attr != INVALID_FILE_ATTRIBUTES ) { static const ffl_tchar_t file_name_format_next[] = FFL_T( "%s%s_%d.%d.%d_%d.%d.%d(%d).%s" ); ++count; ffl_snprintf( temp, FFL_COUNTOF( temp ), file_name_format_next, prefix, name, date.year(), date.month(), date.day(), date.hour(), date.minute(), date.second(), count, ext ); ffl_makepath( output, output_count, drive, dir, temp, NULL ); attr = ::GetFileAttributes( output ); } } } static void record( ffl_dump_param_t * param, const ffl_tchar_t * prefix ) { if( param != NULL && prefix != NULL ) { static const ffl_tchar_t minidump_ext[] = FFL_T( "dmp" ); static const ffl_tchar_t log_ext[] = FFL_T( "txt" ); static const ffl_tchar_t report_ext[] = FFL_T( "rpt" ); ffl_tchar_t temp_file[MAX_PATH] = { 0, }; make_file_name( temp_file, FFL_COUNTOF( temp_file ), prefix, minidump_ext ); ffl_dump_mini minidump; minidump.dump( temp_file, param ); make_file_name( temp_file, FFL_COUNTOF( temp_file ), prefix, log_ext ); ffl_dump_log dumplog; dumplog.dump( temp_file, param ); make_file_name( temp_file, FFL_COUNTOF( temp_file ), prefix, report_ext ); ffl_dump_report dumpreport; dumpreport.dump( temp_file, param ); } } static unsigned int __stdcall ffl_dump_recod_function( void * arg ) { ffl_dump_param_t * param = reinterpret_cast < ffl_dump_param_t * >( arg ); if( param != NULL ) { static const ffl_tchar_t crash_prefix[] = FFL_T( "" ); record( param, crash_prefix ); } return 0; } int ffl_dump_unexception_filter::dump_level_ = ffl_dump_level_light; ffl_dump_unexception_filter::ffl_dump_unexception_filter( int level /* = ffl_dump_level_light */ ) { install( level ); } ffl_dump_unexception_filter::~ffl_dump_unexception_filter() { } void ffl_dump_unexception_filter::install( int level /* = ffl_dump_level_light */ ) { if( level != ffl_dump_level_none ) { dump_level_ = level; #if defined(_MSC_VER) && (_MSC_VER > 1310) // crt error handler ::_set_invalid_parameter_handler( ffl_invalid_parameter ); #endif _set_purecall_handler( ffl_purecall_handler ); // win32 api handler ::SetUnhandledExceptionFilter( top_level_filter ); } } void ffl_dump_unexception_filter::snapping( int level /* = ffl_dump_level_light */ ) { __try { ::RaiseException( EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL ); } __except( do_snapping( level, GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER ) { } } LONG ffl_dump_unexception_filter::top_level_filter( EXCEPTION_POINTERS * exception_ptr ) { if( exception_ptr != NULL && exception_ptr->ExceptionRecord != NULL ) { ffl_dump_param_t * param = NULL; param = reinterpret_cast< ffl_dump_param_t * >( ::malloc( sizeof( ffl_dump_param_t ) ) ); if( param != NULL ) { param->level = dump_level_; param->dump_thread = ::GetCurrentThread(); param->dump_thread_id = ::GetCurrentThreadId(); param->exception_ptr = exception_ptr; if( exception_ptr->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW ) { unsigned int id = 0; HANDLE handle = reinterpret_cast< HANDLE >( ::_beginthreadex( NULL, 0, ffl_dump_recod_function, param, 0, &id ) ); if( handle != NULL ) { ::WaitForSingleObject( handle, INFINITE ); ::CloseHandle( handle ); handle = NULL; } } else { static const ffl_tchar_t crash_prefix[] = FFL_T( "" ); record( param, crash_prefix ); } ::free( param ); param = NULL; return EXCEPTION_EXECUTE_HANDLER; } } return EXCEPTION_CONTINUE_SEARCH; } void ffl_dump_unexception_filter::do_snapping( int level, EXCEPTION_POINTERS * exception_ptr ) { if( level != ffl_dump_level_none && exception_ptr != NULL ) { ffl_dump_param_t * param = NULL; param = reinterpret_cast< ffl_dump_param_t * >( ::malloc( sizeof( ffl_dump_param_t ) ) ); if( param != NULL ) { static const ffl_tchar_t snapping_prefix[] = FFL_T( "snap_" ); param->level = dump_level_; param->dump_thread = ::GetCurrentThread(); param->dump_thread_id = ::GetCurrentThreadId(); param->exception_ptr = exception_ptr; record( param, snapping_prefix ); } } }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 217 ] ] ]
bddf3aae12c4d1893c148647a20a14fa2314dadc
bb5fe5e17222debb66ca316e0411fc77dfbe0b3b
/SpaceRoguelike/SpaceRoguelike/GFE/GreenState.hpp
fefc0f4189c3755d891565f8c3ca1ce2ffb38fbd
[]
no_license
GloryFish/SpaceRoguelike
0c56add11219f691647ffe0df4c3fefd385540ca
63e938cecbd681d2c9b667f2defbd8f03a4e2960
refs/heads/master
2016-09-05T20:05:35.730834
2011-09-13T02:53:49
2011-09-13T02:53:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,091
hpp
#ifndef GREEN_STATE_HPP_INCLUDED #define GREEN_STATE_HPP_INCLUDED #include <SFML/Graphics.hpp> #include "IState.hpp" namespace GFE { /// Provides simple Splash screen game state class GreenState : public IState { public: /** * GreenState constructor * @param[in] theGame is a pointer to the App class. */ GreenState(Game* theGame); /** * SplashState deconstructor */ virtual ~GreenState(void); /** * DoInit is responsible for initializing this State */ virtual void DoInit(void); /** * ReInit is responsible for Reseting this state when the * StateManager::ResetActiveState() method is called. This way a Game * State can be restarted without unloading and reloading the game assets */ virtual void ReInit(void); /** * HandleEvents is responsible for handling input events for this * State when it is the active State. * @param[in] theEvent to process from the App class Loop method */ virtual void HandleEvents(sf::Event theEvent); /** * UpdateFixed is responsible for handling all State fixed update needs for * this State when it is the active State. */ virtual void UpdateFixed(void); /** * UpdateVariable is responsible for handling all State variable update * needs for this State when it is the active State. * @param[in] theElapsedTime since the last Draw was called */ virtual void UpdateVariable(float theElapsedTime); /** * Draw is responsible for handling all Drawing needs for this State * when it is the Active State. */ virtual void Draw(void); protected: /** * Cleanup is responsible for performing any cleanup required before * this State is removed. */ virtual void Cleanup(void); private: // Variables ///////////////////////////////////////////////////////////////////////// }; // class GreenState } #endif // CORE_SPLASH_STATE_HPP_INCLUDED
[ [ [ 1, 76 ] ] ]
c8d4b8e4030f2ea52fef5ffec990f4dd6a8552f2
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEAudio/SEAudioRendering/SEWave.cpp
d9c985b4bb53bc1dfe39ed3f04d7ac415237d31e
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
GB18030
C++
false
false
9,468
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEAudioPCH.h" #include "SEWave.h" #include "SEWaveCatalog.h" #include "SEWaveVersion.h" #include "SEBitHacks.h" using namespace Swing; SE_IMPLEMENT_RTTI(Swing, SEWave, SEObject); SE_IMPLEMENT_STREAM(SEWave); SE_IMPLEMENT_DEFAULT_NAME_ID(SEWave, SEObject); //SE_REGISTER_STREAM(SEWave); int SEWave::ms_BytesPerSample[SEWave::WT_COUNT] = { 1, // WT_MONO4 1, // WT_MONO8 2, // WT_MONO16 1, // WT_STEREO4 1, // WT_STEREO8 2, // WT_STEREO16 2, // WT_QUAD16 2, // WT_REAR16 2, // WT_51CHN16 2, // WT_61CHN16 2 // WT_71CHN16 }; int SEWave::ms_ChannelsPerSample[SEWave::WT_COUNT] = { 1, // WT_MONO4 1, // WT_MONO8 1, // WT_MONO16 2, // WT_STEREO4 2, // WT_STEREO8 2, // WT_STEREO16 4, // WT_QUAD16 2, // WT_REAR16 6, // WT_51CHN16 7, // WT_61CHN16 8 // WT_71CHN16 }; std::string SEWave::ms_FormatName[SEWave::WT_COUNT] = { "WT_MONO4", "WT_MONO8", "WT_MONO16", "WT_STEREO4", "WT_STEREO8", "WT_STEREO16", "WT_QUAD16", "WT_REAR16", "WT_51CHN16", "WT_61CHN16", "WT_71CHN16" }; //---------------------------------------------------------------------------- SEWave::SEWave(FormatMode eFormat, unsigned int uiFrequency, int iDataSize, unsigned char* pData, const char* pWaveName, bool bInsert) { SE_ASSERT( pWaveName ); m_eFormat = eFormat; m_uiFrequency = uiFrequency; m_iDataSize = iDataSize; m_pData = pData; SetName(pWaveName); m_bIsInCatalog = bInsert; if( bInsert ) { SEWaveCatalog::GetActive()->Insert(this); } } //---------------------------------------------------------------------------- SEWave::SEWave() { m_eFormat = WT_COUNT; m_uiFrequency = 0; m_iDataSize = 0; m_pData = 0; } //---------------------------------------------------------------------------- SEWave::~SEWave() { SE_DELETE[] m_pData; if( m_bIsInCatalog ) { SEWaveCatalog::GetActive()->Remove(this); } } //---------------------------------------------------------------------------- SEWave* SEWave::Load(const char* pWaveName) { SE_ASSERT( pWaveName ); std::string strFileName = std::string(pWaveName) + std::string(".sewf"); const char* pDecorated = SESystem::SE_GetPath(strFileName.c_str(), SESystem::SM_READ); if( !pDecorated ) { return 0; } char* acBuffer; int iSize; bool bLoaded = SESystem::SE_Load(pDecorated, acBuffer, iSize); if( !bLoaded ) { // 文件读取失败. return 0; } if( iSize < SEWaveVersion::LENGTH ) { // 文件太小. SE_DELETE[] acBuffer; return 0; } // 获取文件版本. SEWaveVersion tempVersion(acBuffer); if( !tempVersion.IsValid() ) { SE_DELETE[] acBuffer; return 0; } char* pcCurrent = acBuffer + SEWaveVersion::LENGTH; // 获取wave format和frequency. int iFormat; unsigned int uiFrequency; pcCurrent += SESystem::SE_Read4le(pcCurrent, 1, &iFormat); pcCurrent += SESystem::SE_Read4le(pcCurrent, 1, &uiFrequency); FormatMode eFormat = (FormatMode)iFormat; // 获取wave data. // 注意16位采样数据存在endian问题. int iDataSize; pcCurrent += SESystem::SE_Read4le(pcCurrent, 1, &iDataSize); unsigned char* pData = SE_NEW unsigned char[iDataSize]; if( iFormat == WT_MONO4 || iFormat == WT_MONO8 || iFormat == WT_STEREO4 || iFormat == WT_STEREO8 ) { SESystem::SE_Read1(pcCurrent, iDataSize, pData); } else { // 对于16位采样数据,数据区字节数应为偶数. SE_ASSERT( IsEven(iDataSize) ); SESystem::SE_Read2le(pcCurrent, iDataSize>>1, pData); } SEWave* pWave = SE_NEW SEWave(eFormat, uiFrequency, iDataSize, pData, pWaveName); SE_DELETE[] acBuffer; return pWave; } //---------------------------------------------------------------------------- bool SEWave::Save(const char* pFileName) { if( !pFileName ) { return false; } FILE* pFile = SESystem::SE_Fopen(pFileName, "wb"); if( !pFile ) { return false; } // 写文件版本. SESystem::SE_Write1(pFile, SEWaveVersion::LENGTH, SEWaveVersion::LABEL); // 写wave format和frequency. int iFormat = (int)m_eFormat; SESystem::SE_Write4le(pFile, 1, &iFormat); SESystem::SE_Write4le(pFile, 1, &m_uiFrequency); // 写wave data. // 注意16位采样数据存在endian问题. SESystem::SE_Write4le(pFile, 1, &m_iDataSize); if( iFormat == WT_MONO4 || iFormat == WT_MONO8 || iFormat == WT_STEREO4 || iFormat == WT_STEREO8 ) { SESystem::SE_Write1(pFile, m_iDataSize, m_pData); } else { // 对于16位采样数据,数据区字节数应为偶数. SE_ASSERT( IsEven(m_iDataSize) ); SESystem::SE_Write2le(pFile, m_iDataSize>>1, m_pData); } SESystem::SE_Fclose(pFile); return true; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // streaming //---------------------------------------------------------------------------- void SEWave::Load(SEStream& rStream, SEStream::SELink* pLink) { SE_BEGIN_DEBUG_STREAM_LOAD; SEObject::Load(rStream, pLink); // native data int iFormat; rStream.Read(iFormat); m_eFormat = (FormatMode)iFormat; rStream.Read(m_uiFrequency); // 获取wave data. // 注意16位采样数据存在endian问题. rStream.Read(m_iDataSize); m_pData = SE_NEW unsigned char[m_iDataSize]; if( iFormat == WT_MONO4 || iFormat == WT_MONO8 || iFormat == WT_STEREO4 || iFormat == WT_STEREO8 ) { rStream.Read(m_iDataSize, m_pData); } else { // 对于16位采样数据,数据区字节数应为偶数. SE_ASSERT( IsEven(m_iDataSize) ); rStream.Read(m_iDataSize>>1, (unsigned short*)m_pData); } m_bIsInCatalog = true; SEWaveCatalog::GetActive()->Insert(this); SE_END_DEBUG_STREAM_LOAD(SEWave); } //---------------------------------------------------------------------------- void SEWave::Link(SEStream& rStream, SEStream::SELink* pLink) { SEObject::Link(rStream, pLink); } //---------------------------------------------------------------------------- bool SEWave::Register(SEStream& rStream) const { return SEObject::Register(rStream); } //---------------------------------------------------------------------------- void SEWave::Save(SEStream& rStream) const { SE_BEGIN_DEBUG_STREAM_SAVE; SEObject::Save(rStream); // native data rStream.Write((int)m_eFormat); rStream.Write(m_uiFrequency); // 写wave data. // 注意16位采样数据存在endian问题. rStream.Write(m_iDataSize); if( m_eFormat == WT_MONO4 || m_eFormat == WT_MONO8 || m_eFormat == WT_STEREO4 || m_eFormat == WT_STEREO8 ) { rStream.Write(m_iDataSize, m_pData); } else { // 对于16位采样数据,数据区字节数应为偶数. SE_ASSERT( IsEven(m_iDataSize) ); rStream.Write(m_iDataSize>>1, (unsigned short*)m_pData); } SE_END_DEBUG_STREAM_SAVE(SEWave); } //---------------------------------------------------------------------------- int SEWave::GetDiskUsed(const SEStreamVersion& rVersion) const { int iSize = SEObject::GetDiskUsed(rVersion) + sizeof(int); // m_eFormat iSize += sizeof(m_uiFrequency) + sizeof(m_iDataSize); iSize += m_iDataSize*sizeof(m_pData[0]); return iSize; } //---------------------------------------------------------------------------- SEStringTree* SEWave::SaveStrings(const char*) { SEStringTree* pTree = SE_NEW SEStringTree; // strings pTree->Append(Format(&TYPE, GetName().c_str())); pTree->Append(Format("format =", ms_FormatName[m_eFormat].c_str())); pTree->Append(Format("frequency = ", m_uiFrequency)); // children pTree->Append(SEObject::SaveStrings()); return pTree; } //----------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 329 ] ] ]
69734ae4b5bb83bba06c19a58ae70c8d61a53ff1
87cfed8101402f0991cd2b2412a5f69da90a955e
/daq/daqadaptor/Demo/DemoAout.h
e0400b6fbe4bb382e0f5e27c0aa2209fdaa744ec
[]
no_license
dedan/clock_stimulus
d94a52c650e9ccd95dae4fef7c61bb13fdcbd027
890ec4f7a205c8f7088c1ebe0de55e035998df9d
refs/heads/master
2020-05-20T03:21:23.873840
2010-06-22T12:13:39
2010-06-22T12:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,297
h
// demoOut.h : Declaration of CdemoOut class // Copyright 1998-2003 The MathWorks, Inc. // $Revision: 1.1.4.3 $ $Date: 2003/08/29 04:44:13 $ #ifndef __DEMOAOUT_H_ #define __DEMOAOUT_H_ #include "resource.h" // main symbols //This abstract class extends the CswClockedDevice class by a single .. //..pure virtual function GetSingleValue() class ATL_NO_VTABLE CDemoAoutputBase: public CswClockedDevice { public: typedef short RawDataType; enum BitsEnum {Bits=16}; // bits must fit in rawdatatype virtual HRESULT PutSingleValue(int index,RawDataType Value)=0; }; ///////////////////////////////////////////////////////////////////////////// // CDemoAout class declaration // // CDemoAout is based on ImwDevice and ImwOutput via chains:.. //.. ImwDevice -> CmwDevice -> CswClockedDevice -> CDemoAoutputBase ->.. //.. TADDevice -> CDemoAout and.. //.. ImwOutput -> TADDevice -> CDemoAout class ATL_NO_VTABLE CDemoAout : public TDADevice<CDemoAoutputBase>, //is based on ImwDevice public CComCoClass<CDemoAout, &CLSID_DemoAout> // public IDispatchImpl<IDemoOut, &IID_IDemoOut, &LIBID_DEMOLib> { typedef TDADevice<CDemoAoutputBase> TBaseObj; public: //TO_DO: In this macro enter (1)name of the adaptor class,.. //..(2)program ID, (3)version independent program ID, (4)index of the name.. //..bearing resource string -- from the resource.h file. Keep flags untouched. DECLARE_REGISTRY( CDemoAdapt, _T("Demo.DemoAout.1"), _T("Demo.DemoAout"), IDS_PROJNAME, THREADFLAGS_BOTH ) //END TO_DO //this line is not needed if the program does not support aggregation DECLARE_PROTECT_FINAL_CONSTRUCT() //ATL macros internally implementing QueryInterface() for the mapped interfaces BEGIN_COM_MAP(CDemoAout) // COM_INTERFACE_ENTRY(IDemoAout) COM_INTERFACE_ENTRY(ImwDevice) COM_INTERFACE_ENTRY(ImwOutput) END_COM_MAP() public: CDemoAout(); HRESULT Open(IUnknown *Interface,long ID); HRESULT PutSingleValue(int chan,RawDataType value); //DeviceId data member currently is not used in the demo program UINT DeviceId; typedef std::vector<RawDataType> BufferT; BufferT Buffer; BufferT::iterator NextPoint; }; #endif //__DEMOOAOUT_H_ // DemoOut.cpp : Implementation of CDemoAout
[ [ [ 1, 70 ] ] ]
a73cc4e25ebd5e7c7ceb4c0fbee0f35660c72530
4de35be6f0b79bb7eeae32b540c6b1483b933219
/aura/gpsprotocol.cpp
fc07a0c2ecf339372bd2670b6eb6e68175489c8f
[]
no_license
NoodleBoy/aura-bot
67b2cfb44a0c8453f54cbde0526924e416a2a567
2a7d84dc56653c7a4a8edc1552a90bc848b5a5a9
refs/heads/master
2021-01-17T06:52:05.819609
2010-12-30T15:18:41
2010-12-30T15:18:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,451
cpp
/* Copyright [2010] [Josko Nikolic] 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 "aura.h" #include "util.h" #include "gpsprotocol.h" // // CGPSProtocol // CGPSProtocol :: CGPSProtocol( ) { } CGPSProtocol :: ~CGPSProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// //////////////////// // SEND FUNCTIONS // //////////////////// BYTEARRAY CGPSProtocol :: SEND_GPSC_INIT( uint32_t version ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_INIT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, version, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSC_RECONNECT( unsigned char PID, uint32_t reconnectKey, uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_RECONNECT ); packet.push_back( 0 ); packet.push_back( 0 ); packet.push_back( PID ); UTIL_AppendByteArray( packet, reconnectKey, false ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSC_ACK( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_ACK ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_INIT( uint16_t reconnectPort, unsigned char PID, uint32_t reconnectKey, unsigned char numEmptyActions ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_INIT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, reconnectPort, false ); packet.push_back( PID ); UTIL_AppendByteArray( packet, reconnectKey, false ); packet.push_back( numEmptyActions ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_RECONNECT( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_RECONNECT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_ACK( uint32_t lastPacket ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_ACK ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, lastPacket, false ); AssignLength( packet ); return packet; } BYTEARRAY CGPSProtocol :: SEND_GPSS_REJECT( uint32_t reason ) { BYTEARRAY packet; packet.push_back( GPS_HEADER_CONSTANT ); packet.push_back( GPS_REJECT ); packet.push_back( 0 ); packet.push_back( 0 ); UTIL_AppendByteArray( packet, reason, false ); AssignLength( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// inline bool CGPSProtocol :: AssignLength( BYTEARRAY &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes = UTIL_CreateByteArray( (uint16_t)content.size( ), false ); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } inline bool CGPSProtocol :: ValidateLength( BYTEARRAY &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length uint16_t Length; BYTEARRAY LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = UTIL_ByteArrayToUInt16( LengthBytes, false ); if( Length == content.size( ) ) return true; } return false; }
[ "[email protected]@268e31a9-a219-ec89-1cb4-ecc417c412f6", "[email protected]" ]
[ [ [ 1, 2 ], [ 4, 18 ], [ 20, 173 ] ], [ [ 3, 3 ], [ 19, 19 ] ] ]
416b995f9de863a888e59c3e847f20f5606557f1
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Scene/DirectionalLight.h
25812416483732e6b63e3e58b3dc749fce9fa52c
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
h
#ifndef __SLON_ENGINE_GRAPHICS_LIGHT_DIRECTIONAL_H__ #define __SLON_ENGINE_GRAPHICS_LIGHT_DIRECTIONAL_H__ #include "../Utility/math.hpp" #include "Light.h" namespace slon { namespace scene { /** Directional light source. */ class SLON_PUBLIC DirectionalLight : public Light { public: DirectionalLight(); // Override Node using Node::accept; void accept(CullVisitor& visitor) const; // Oveerride Entity const math::AABBf& getBounds() const { return bounds<math::AABBf>::infinite(); } // Override Light LIGHT_TYPE getLightType() const { return DIRECTIONAL; } bool isShadowCaster() const { return shadowCaster; } /** Set normalized color of the light source. */ void setColor(const math::Vector4f& _color) { color = _color; } /** Set nambient light intensity. */ void setAmbient(float ambient_) { ambient = ambient_; } /** Set intensity of the light source. */ void setIntensity(float _intensity) { intensity = _intensity; } /** Set direction of the light source. */ void setDirection(const math::Vector3f& _direction) { direction = _direction; } /** Toggle shadow casting for light source. */ void toggleShadow(bool toggle) { shadowCaster = toggle; } /** Get light direction. */ const math::Vector3f& getDirection() const { return direction; } /** Get normalized color of the light source. */ const math::Vector4f& getColor() const { return color; } /** Get ambient of the light source. */ float getAmbient() const { return ambient; } /** Get intensity of the light source. */ float getIntensity() const { return intensity; } private: // light props math::Vector4f color; math::Vector3f direction; float intensity; float ambient; bool shadowCaster; }; } // namespace scene } // namespace slon #endif // __SLON_ENGINE_GRAPHICS_LIGHT_DIRECTIONAL_H__
[ "devnull@localhost" ]
[ [ [ 1, 68 ] ] ]
8297e3a26fe77f86308c6c202e1c2ad371bd6833
5d3c1be292f6153480f3a372befea4172c683180
/trunk/Event Heap/c++/Windows/include/eh2_FieldValue.h
b1004e64f814d4e4eade59cb2cb6270da43db49f
[ "Artistic-2.0" ]
permissive
BackupTheBerlios/istuff-svn
5f47aa73dd74ecf5c55f83765a5c50daa28fa508
d0bb9963b899259695553ccd2b01b35be5fb83db
refs/heads/master
2016-09-06T04:54:24.129060
2008-05-02T22:33:26
2008-05-02T22:33:26
40,820,013
0
0
null
null
null
null
UTF-8
C++
false
false
3,495
h
/* Copyright (c) 2003 The Board of Trustees of The Leland Stanford Junior * University. All Rights Reserved. * * See the file LICENSE.txt for information on redistributing this software. */ /* $Id: eh2_FieldValue.h,v 1.6 2003/07/01 06:40:45 tomoto Exp $ */ #ifndef _EH2_FIELDVALUE_H_ #define _EH2_FIELDVALUE_H_ #include <eh2_Base.h> #include <eh2_Types.h> #include <eh2_EventConsts.h> /** @file Definition of eh2_FieldValue class. @internal This header belongs to the eh2i_ev package. */ class eh2i_ev_FieldValue; // impl /** Represents the values contained by a field. Usual applications need not use this class because eh2_Event and eh2_Field class provides enough shortcut methods to access to the values directly bypassing this object. @todo Setter/getter for non-basic types. See eh2_Event. */ class EH2_DECL eh2_FieldValue : public idk_ut_TProxyObject<eh2i_ev_FieldValue>, public eh2_EventConsts { private: friend class eh2i_ev_FieldValue; eh2_FieldValue(eh2i_ev_FieldValue* impl); public: ~eh2_FieldValue(); /** Returns the value type of the field value. */ FieldValueType getFieldValueType() const; /** Sets the value type of the field value. When FVT_ACTUAL is passed, the actual value will be initialized to NULL. */ void setFieldValueType(FieldValueType type); /** Returns non-zero if the field value is virtual. */ int isVirtual() const; /** Copy the value of the give object. */ void copyValue(const eh2_FieldValue* other); /** Sets the value. @throws eh2_FieldOperationException The data type is different. */ void setIntValue(int value); /** Sets the value. If the data type of the field is not string, the value is converted to string type. */ void setStringValue(const char* value); /** Sets the value. @throws eh2_FieldOperationException The data type is different. */ void setDoubleValue(double value); /** Sets the value. @throws eh2_FieldOperationException The data type is different. */ void setFloatValue(float value); /** Sets the value. @throws eh2_FieldOperationException The data type is different. */ void setBooleanValue(int value); /** Sets the value. @throws eh2_FieldOperationException The data type is different. */ void setLongValue(idk_long value); /** Returns non-zero if the value is NULL. @throws eh2_FieldOperationException The value is not actual. */ int isNull() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ int getIntValue() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ const char* getStringValue() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ double getDoubleValue() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ float getFloatValue() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ int getBooleanValue() const; /** Returns the value. @throws eh2_FieldOperationException The value is not actual or data type is different. */ idk_long getLongValue() const; }; #endif
[ "ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26" ]
[ [ [ 1, 141 ] ] ]
a3025d438be201d731b4410805fc9fb3b8dd6446
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/GameController.h
77717f8628b98d16e2c87a9cc73ebce13db1edc9
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
1,200
h
#pragma once #include "Definitions.h" #include "DirectInput.h" #include "Unit.h" #include "Renderable.h" #include "FriendlyUnit.h" #include "EnemyUnit.h" #include "Structures.h" #include "Button.h" #include "Quadrant.h" #include <time.h> #include "Quadrant.h" #include "Clickable.h" class GameController { private: int m_TotalNumOfEnemies; int m_TotalNumOfStations; // an array of objects to draw; QuadData m_Galaxy[GALAXY_SIZE][GALAXY_SIZE]; int QuadRow, QuadCol; // our current quad //clickable Button m_Buttons[BUTTONS_AMOUNT]; CDirectInput* UserInput; int m_GameTurns; int m_CurrentTurn; GAMESTATE m_Control_State; Quadrant m_ActiveQuad; Command m_Command; Clickable* mClickable[CLICKABLES_SIZE]; int m_QuadRow; int m_QuadCol; public: GameController(void); ~GameController(void); void UpdateGame(float DeltaTime); void LoadTextures(void); void CheckInput(); void ShowResults(); void UpdateEnemies(); CRenderable** GetRenderList(void); int GetRenderListNumber(void); CFriendlyUnit GetFriendlyUnit(void); void Scan(); void Check_Win_Lose(); };
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7", "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7", "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7", "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 8 ], [ 15, 18 ], [ 23, 24 ], [ 26, 26 ], [ 30, 32 ], [ 50, 51 ], [ 55, 57 ], [ 65, 68 ], [ 71, 71 ] ], [ [ 9, 10 ], [ 12, 12 ], [ 27, 27 ], [ 29, 29 ], [ 33, 36 ], [ 52, 54 ], [ 58, 58 ] ], [ [ 11, 11 ], [ 25, 25 ] ], [ [ 13, 14 ], [ 19, 22 ], [ 28, 28 ], [ 37, 49 ], [ 59, 64 ], [ 69, 70 ] ] ]
b7f6e3fe54489f075fd9f798284019484f28f493
a230afa027a8a672c3d3581df13439127c795a55
/Rendrer/osgData.h
c6cca9c4627941ceb85f5967885a74fbf26ce6b6
[]
no_license
ASDen/CGsp
fbecb2463d975412f85fa343e87fda9707b7801a
2657b72269566c59cc0127239e3827f359197f9e
refs/heads/master
2021-01-25T12:02:10.331018
2010-09-22T12:43:19
2010-09-22T12:43:19
503,933
1
0
null
null
null
null
UTF-8
C++
false
false
9,225
h
#pragma once typedef Polyhedron::Edge_iterator Edge_iterator; typedef Polyhedron::Halfedge_const_iterator Halfedge_const_iterator; typedef Primitives* pPrimitive; typedef NxActorDesc* pNxActorDesc; typedef KeyFrameModifier* pKeyFrameModifier; class CGSP_CC PolyhedronNode : public osg::Drawable { public: union { NxActor* RigidActor; NxCloth* ClothActor; }; std::vector<pKeyFrameModifier> ModStack; osg::ref_ptr<osg::PositionAttitudeTransform> Pos; osg::ref_ptr<osg::PositionAttitudeTransform> ModifiedPos; void ApplyModifier(pKeyFrameModifier M) { ModStack.push_back(M); } void UpdateAtFrame(int Fnum) { const_cast<PolyhedronNode*>(this)->getParent(0)->getParent(0)->asTransform()->asPositionAttitudeTransform()->setPosition(ModifiedPos->getPosition()); const_cast<PolyhedronNode*>(this)->getParent(0)->getParent(0)->asTransform()->asPositionAttitudeTransform()->setAttitude(ModifiedPos->getAttitude()); const_cast<PolyhedronNode*>(this)->getParent(0)->getParent(0)->asTransform()->asPositionAttitudeTransform()->setScale(ModifiedPos->getScale()); std::vector<pKeyFrameModifier>::iterator i; ModifiedPos = dynamic_cast<osg::PositionAttitudeTransform*> (Pos->clone(osg::CopyOp::DEEP_COPY_ALL)); for(i=ModStack.begin();i!=ModStack.end();i++) { (*i)->DoAtFrame(ModifiedPos,Fnum); } } pPrimitive P; NxActorDesc ActorDesc; osg::Vec3 Position; osg::Vec3 PColor; bool WireFrame; bool AntialisedLines; TexType TextureType; PolyhedronNode():WireFrame(true){} PolyhedronNode(pPrimitive iP,osg::Vec3 Pos=osg::Vec3(0,0,0)):P(iP),Position(Pos),PColor(1.0f,1.0f,1.0f) {} PolyhedronNode(const PolyhedronNode& poly,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY): osg::Drawable(poly,copyop) {} META_Object(myPoly,PolyhedronNode) virtual void drawImplementation(osg::RenderInfo&) const { //if(this->getNumParents()>0) //if(RigidActor == NULL && ClothActor == NULL) { } DrawPolyhedron(); const_cast<PolyhedronNode*>(this)->dirtyBound(); } virtual osg::BoundingBox computeBound() const { osg::BoundingBox bbox; Kernel::Iso_cuboid_3 c3 = CGAL::bounding_box(P->ModifiedMesh.points_begin (), P->ModifiedMesh.points_end ()); bbox.set (CGAL::to_double(c3.xmin()),CGAL::to_double(c3.ymin()),CGAL::to_double(c3.zmin()),CGAL::to_double(c3.xmax()),CGAL::to_double(c3.ymax()),CGAL::to_double(c3.zmax())); return bbox; } void DrawPolyhedron() const { ::glColor3f(PColor.x(),PColor.y(),PColor.z()); // change the color of facets Facet_iterator f; for(f = P->ModifiedMesh.facets_begin(); f != P->ModifiedMesh.facets_end(); f++) { ::glBegin(GL_POLYGON); Vector_3 n = compute_facet_normal<Facet,Kernel>(*f); ::glNormal3d(CGAL::to_double(n.x()),CGAL::to_double(n.y()),CGAL::to_double(n.z())); Halfedge_facet_circulator he = f->facet_begin(); Halfedge_facet_circulator end = he; CGAL_For_all(he,end) { const Point_3& p = he->vertex()->point(); ::glTexCoord2f(he->u(),he->v()); ::glVertex3d(CGAL::to_double(p.x()),CGAL::to_double(p.y()),CGAL::to_double(p.z())); } ::glEnd(); } if(!WireFrame)return; ::glColor3f(0.0f,0.0f,0.0f); // change the color of lines ::glEnable(GL_POLYGON_OFFSET_FILL); ::glPolygonOffset(1.0f,1.0f); if(AntialisedLines) { ::glEnable(GL_LINE_SMOOTH); ::glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); } ::glBegin(GL_LINES); Edge_iterator he; for(he = P->ModifiedMesh.edges_begin(); he != P->ModifiedMesh.edges_end(); he++) { const Point_3& a = he->vertex()->point(); const Point_3& b = he->opposite()->vertex()->point(); ::glVertex3d(CGAL::to_double(a.x()),CGAL::to_double(a.y()),CGAL::to_double(a.z())); ::glVertex3d(CGAL::to_double(b.x()),CGAL::to_double(b.y()),CGAL::to_double(b.z())); } ::glEnd(); } }; class CGSP_CC LightNode { public: osg::Light* myLight ; osg::LightSource* lightS; osg::StateSet* rootStateSet; osg::Vec4 Position; osg::Vec3 Direction; osg::Vec4 Ambient; osg::Vec4 Diffuse; osg::Vec4 Specular; double SpotCutoff; double SpotExponent; double ConstantAttenuation; LightNode() { myLight = new osg::Light; myLight->setLightNum(0); Position = osg::Vec4(0.0,0.0,0.0,1.0f); Direction = osg::Vec3(1.0f,1.0f,-0.5f); Ambient = osg::Vec4(0.0f,0.0f,1.0f,1.0f); Diffuse = osg::Vec4(0.0f,0.0f,1.0f,1.0f); Specular = osg::Vec4(0.0f,0.0f,0.0f,1.0f); SpotCutoff = 20.0f; SpotExponent = 5.0f; ConstantAttenuation = 0.5f; myLight->setPosition(Position); myLight->setAmbient(Ambient); myLight->setDiffuse(Diffuse); myLight->setSpecular(Specular); myLight->setSpotCutoff(SpotCutoff); myLight->setSpotExponent(SpotExponent); myLight->setDirection(Direction); myLight->setConstantAttenuation(ConstantAttenuation); lightS = new osg::LightSource; rootStateSet = new osg::StateSet; lightS->setLight(myLight); lightS->setLocalStateSetModes(osg::StateAttribute::ON); lightS->setStateSetModes(*rootStateSet,osg::StateAttribute::ON); } ~LightNode(){}; }; class MyGraphicsContext { public: MyGraphicsContext() { osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = 1; traits->height = 1; traits->windowDecoration = false; traits->doubleBuffer = false; traits->sharedContext = 0; traits->pbuffer = true; _gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (!_gc) { traits->pbuffer = false; _gc = osg::GraphicsContext::createGraphicsContext(traits.get()); } if (_gc.valid()) { _gc->realize(); _gc->makeCurrent(); } } bool valid() const { return _gc.valid() && _gc->isRealized(); } private: osg::ref_ptr<osg::GraphicsContext> _gc; }; class CGSP_CC osgPolyManager { public: std::vector<PolyhedronNode*> PolyBag; osg::ref_ptr<osg::Group> root; osg::Group* lightGroup; osgPolyManager() { root=new osg::Group(); lightGroup = new osg::Group; root->addChild(lightGroup); } template <class Manager> void AddPolyhedron(PolyhedronNode* Pn, std::string fname = std::string(""), TexType ty = Tex_CGAL_General, int val = 0, float Hor = 0.09 , float Ver = 0.1) { typedef typename Manager::UpdateCallback UC; Pn->setUseDisplayList( false ); PolyBag.push_back(Pn); osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform(); pat->setPosition(Pn->Position); root->addChild(pat); osg::Geode* g = new osg::Geode(); g->addDrawable(Pn); if(fname.size()>0) { g->setStateSet(AddTex(fname)); Traingulate tr; switch(ty) { case Tex_CGAL_General: tr.Do(Pn->P->ModifiedMesh); Texture::CalcUV<Tex_CGAL_General>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; case Tex_Sphere: tr.Do(Pn->P->ModifiedMesh); Texture::CalcUV<Tex_Sphere>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; case Tex_Box: Texture::CalcUV<Tex_Box>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; case Tex_Cylinder: Texture::CalcUV<Tex_Cylinder>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; case Tex_Torus: Texture::CalcUV<Tex_Torus>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; case Tex_Tube: Texture::CalcUV<Tex_Tube>(Pn->P->ModifiedMesh, Pn->P, val, Hor, Ver); break; } Pn->P->setMesh(Pn->P->ModifiedMesh); } pat->setUpdateCallback(new UC(Pn)); pat->addChild(g); Pn->Pos = static_cast<osg::PositionAttitudeTransform*> (pat->clone(osg::CopyOp::DEEP_COPY_ALL)); Pn->ModifiedPos = static_cast<osg::PositionAttitudeTransform*> (pat->clone(osg::CopyOp::DEEP_COPY_ALL)); } osg::StateSet* AddTex(std::string fname) { MyGraphicsContext gc; if (!gc.valid()) { osg::notify(osg::NOTICE)<<"Unable to create the graphics context required to build 3d image."<<std::endl; return 0; } osg::ref_ptr<osg::Image> image = osgDB::readImageFile(fname.c_str()); if (!image) { std::cout << "Couldn't load texture." << std::endl; return 0; } GLint textureSize = osg::Texture3D::getExtensions(0,true)->maxTexture3DSize(); if (textureSize > 256) int textureSize = 256; image->scaleImage(textureSize,textureSize,1); osg::Texture3D* texture = new osg::Texture3D; texture->setFilter(osg::Texture3D::MIN_FILTER,osg::Texture3D::LINEAR); texture->setFilter(osg::Texture3D::MAG_FILTER,osg::Texture3D::LINEAR); texture->setWrap(osg::Texture3D::WRAP_R,osg::Texture3D::REPEAT); texture->setImage(image); osg::StateSet* stateset = new osg::StateSet; stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON); return stateset; } void AddLight(LightNode* lightSrc) { lightGroup->addChild(lightSrc->lightS); } void UpdateFrame(int Fnum) { std::vector<PolyhedronNode*>::iterator i; for(i=PolyBag.begin();i!=PolyBag.end();i++) { (*i)->P->UpdateAtFrame(Fnum); (*i)->dirtyBound(); } } };
[ [ [ 1, 322 ] ] ]
7a50d40c4a6ff9c35d94f636da259c3d0408953d
e2bbf1e9ccbfea663803cb692d6b6754f37ca3d8
/MoreOBs/MoreOBs/moreobs.cpp
14116b619136f018f307559611da58a7ccf656f9
[]
no_license
binux/moreobs
65efa6143f49a15ee1cdb0eea38670d808415e97
8f2319b6d76573c0054fcd40304b620e38527f4c
refs/heads/master
2021-01-10T14:09:48.174517
2010-08-10T07:53:46
2010-08-10T07:53:46
46,993,885
3
0
null
null
null
null
UTF-8
C++
false
false
3,478
cpp
#include "includes.h" #include "config.h" #include "moreobs.h" #include "client.h" #include "protocol.h" #include "game.h" #include "gamelist.h" #include "clientlist.h" #include "control.h" #include <boost/bind.hpp> #include <boost/date_time/posix_time/posix_time.hpp> CMoreObs::CMoreObs ( CConfig *cfg ) { m_port = cfg->GetInt("listen_port",10383); m_controlPort = cfg->GetInt("control_port",10230); protocol = new Protocol( ); serverName = cfg->GetString("server_name","MoreObs"); about = cfg->GetString("server_about","A personal WTV server!"); information = cfg->GetString("server_information","By Binux@CN"); ircAdress = cfg->GetString("server_irc","none"); webAdress = cfg->GetString("server_web","binux.yo2.cn"); uploadRate = cfg->GetInt("server_uploadRate",1000000); updateTimer = cfg->GetInt("update_frequency",1000); gameList = new CGameList( ); clientList = new CClientList( ); shutdown = false; m_ioService = new boost::asio::io_service; m_acceptor = new boost::asio::ip::tcp::acceptor(*m_ioService,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),m_port)); m_timer = new boost::asio::deadline_timer(*m_ioService, boost::posix_time::milliseconds(500)); control = new CControl( m_ioService, m_controlPort, this ); } CMoreObs::~CMoreObs(void) { delete protocol; delete gameList; delete clientList; delete control; delete m_acceptor; delete m_timer; delete m_ioService; } void CMoreObs::Run ( ) { try { CONSOLE_Print("[MOREOBS] start listening !",DEBUG_LEVEL_MESSAGE); CClient* t_socket = new CClient(m_ioService,this); clientList->New(t_socket); m_acceptor->async_accept(*t_socket->GetSocket(),boost::bind(&CMoreObs::handle_accept,this,t_socket,boost::asio::placeholders::error)); m_timer->expires_from_now( boost::posix_time::milliseconds( updateTimer ) ); m_timer->async_wait(boost::bind(&CMoreObs::handle_timer,this,boost::asio::placeholders::error)); } catch(boost::system::system_error& e) { CONSOLE_Print(string("[MOREOBS]") + e.what() , DEBUG_LEVEL_ERROR); } control->Run(); m_ioService->run(); } bool CMoreObs::Update( ) { if(shutdown) { m_ioService->stop( ); return false; } clientList->Update( ); gameList->Update( ); return true; } void CMoreObs::handle_accept( CClient * t_socket , const boost::system::error_code& error ) { if (!error) { try { t_socket->Run(); //CONSOLE_Print("[MOREOBS] Get a new client from [" + t_socket->GetSocket( )->remote_endpoint( ).address( ).to_string( ) + "]",DEBUG_LEVEL_MESSAGE); CClient* t_socket = new CClient(m_ioService,this); clientList->New(t_socket); m_acceptor->async_accept(*t_socket->GetSocket(),boost::bind(&CMoreObs::handle_accept,this,t_socket,boost::asio::placeholders::error)); } catch(boost::system::system_error& e) { CONSOLE_Print(string("[MOREOBS]") + e.what() , DEBUG_LEVEL_ERROR); } } } void CMoreObs::handle_timer( const boost::system::error_code& error ) { Update( ); m_timer->expires_from_now( boost::posix_time::milliseconds( updateTimer ) ); m_timer->async_wait(boost::bind(&CMoreObs::handle_timer,this,boost::asio::placeholders::error)); }
[ "17175297.hk@dc2ccb66-e3a1-11de-9043-17b7bd24f792", "17175297.HK@dc2ccb66-e3a1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 5 ], [ 7, 7 ], [ 10, 11 ], [ 13, 15 ], [ 29, 29 ], [ 34, 38 ], [ 46, 49 ], [ 66, 67 ], [ 69, 69 ], [ 79, 82 ] ], [ [ 6, 6 ], [ 8, 9 ], [ 12, 12 ], [ 16, 28 ], [ 30, 33 ], [ 39, 45 ], [ 50, 65 ], [ 68, 68 ], [ 70, 78 ], [ 83, 106 ] ] ]
ebfffc8325844f5549bb2e37a882e5d9dd1d6453
cb41590937157a6869320c566e2f86aa8098e747
/TP1_Cliente/Source/common_Socket.cpp
382ed357d304afdc7ea22bcf0b3036b6f571f68a
[]
no_license
natlehmann/taller-2010-2c-poker-cliente
2ba189016b443f655a6211ccc7122574cff0773a
d8fac33b71c93add6dc22c89f3c21afdbf83f561
refs/heads/master
2021-01-19T02:13:07.089144
2010-09-01T01:33:19
2010-09-01T01:33:19
32,321,085
0
0
null
null
null
null
UTF-8
C++
false
false
3,748
cpp
#include "common_Socket.h" Socket::Socket() { } Socket::Socket(const int sockfd) { this->valido = true; this->sockfd = sockfd; this->cantConexiones = 0; } Socket::Socket(const int cantConexiones, const int puerto) { this->valido = false; this->sockfd = -1; this->cantConexiones = cantConexiones; this->puerto = puerto; } Socket::~Socket() { } bool Socket::abrir() { int fd = -1; bool resul = true; if (!esValido()) { fd = ::socket(AF_INET, SOCK_STREAM, 0); if (fd != -1) { this->sockfd = fd; this->valido = true; } else { resul = false; } } return resul; } bool Socket::bindear() { struct sockaddr_in direccion; direccion.sin_family = AF_INET; direccion.sin_port = htons(this->puerto); direccion.sin_addr.s_addr = INADDR_ANY; if(::bind(this->sockfd, (struct sockaddr*)&direccion, sizeof(direccion))!=-1) return true; else { return false; } } bool Socket::escuchar() { bool resul = false; if (abrir()) { if (bindear()) { if(::listen(this->sockfd, this->cantConexiones)!=-1) resul = true; else { this->msgError = "Se produjo un error al intentar escuchar el socket"; } } else this->msgError = "Se produjo un error al intentar bindear el socket"; } else this->msgError = "Se produjo un error al intentar abrir el socket"; return resul; } Socket* Socket::aceptar() { int clientefd; int longCliente; struct sockaddr_in dirCliente; Socket* sockCliente = NULL; longCliente = sizeof(dirCliente); clientefd = ::accept(this->sockfd, (struct sockaddr*)&dirCliente, &longCliente); if (clientefd != -1) { this->valido = true; sockCliente = new Socket(clientefd); } return sockCliente; } bool Socket::conectar(const string& host) { struct hostent* he; struct sockaddr_in direccion; bool resul = false; WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 0), &wsaData) == 0) { if ((he=gethostbyname(host.c_str()))!=NULL) { if (abrir()) { direccion.sin_family = AF_INET; direccion.sin_port = htons(this->puerto); direccion.sin_addr.s_addr = ((struct in_addr*)(he->h_addr))->s_addr; if(::connect(this->sockfd,(struct sockaddr *)&direccion, sizeof (direccion))!=-1) { resul = true; } } else { this->msgError = "Se produjo un error al intentar abrir el socket"; } } else { this->msgError = "Se produjo un error al intentar obtener el nombre del host"; } } else { this->msgError = "Se produjo un error: WSAStartup() failed"; } return resul; } bool Socket::enviar(const string msg, const int longMsg) { int cantEnviado = 0; int Aux = 0; bool resul = true; while ((resul)&&(cantEnviado < longMsg)) { Aux = ::send(this->sockfd, msg.data(), longMsg, 0); if (Aux < 0) { resul = false; this->msgError = "Se produjo una interrupcion en el envio de los datos"; } else cantEnviado += Aux; } return resul; } bool Socket::recibir(string& msg) { msg = ""; char buf[MAXRECV+1]; int cantRecibido = 0; int Aux = 0; bool resul = true; while ((resul)&&(msg.find('\n') == string::npos)) { Aux = ::recv(this->sockfd, buf, MAXRECV, 0); if (Aux < 0) { resul = false; this->msgError = "Se produjo una interrupcion en la recepcion de los datos"; } else if (Aux > 0) { cantRecibido += Aux; msg.append(buf, cantRecibido); } else { resul = false; } } return resul; } bool Socket::cerrar() { if(::closesocket(this->sockfd)!=-1) { WSACleanup(); return true; } else { return false; } } /*bool Socket::shutdown() { if(::shutdown(this->sockfd, SHUT_RDWR)!=-1) return true; else { return false; } }*/ bool Socket::esValido() { return this->valido; }
[ "natlehmann@3808f2ed-48a9-d503-52e9-f466b087feb1" ]
[ [ [ 1, 229 ] ] ]
7ab760d2b41dffd0c5a149241d0faff5c4b1d995
d5cdedc500fb5b8ff490fb8e6c04e946b9bd323c
/libs/wowmapper/src/obj0.cpp
bebf0be0e23beb0c9dfc302bc824ec07396e4d2e
[]
no_license
jjiezheng/Pocket-Pather
753dad95d9277d78d4026d5e4297527a5eb15a16
de541d38c8ef7b66f6b7b2441c5b7fd1565c5da5
refs/heads/master
2021-01-25T02:37:49.241798
2010-12-27T14:35:11
2010-12-27T14:35:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,316
cpp
#include "obj0.h" Obj0::Obj0( const BufferS_t &obj_buf ) { // create an istream of our buffer std::stringbuf str_buf( obj_buf ); std::istream i_str( &str_buf ); uint32_t chunk_size = 0; // read MVER chunk chunk_size = readChunkHead( i_str, "MVER", (char*)&_mverChunk, sizeof( MverChunk_s ) ); // read MMDX chunk chunk_size = readChunkHead( i_str, "MMDX", (char*)&_mmdxChunk ); if ( _mmdxChunk.size ) { _doodadNames.resize( _mmdxChunk.size ); i_str.read( (char*)&_doodadNames[0], _mmdxChunk.size ); } // read MMID chunk chunk_size = readChunkHead( i_str, "MMID", (char*)&_mmidChunk ); if ( _mmidChunk.size ) { _mmdxIndices.resize( _mmidChunk.size / 4 ); i_str.read( (char*)&_mmdxIndices[0], _mmidChunk.size ); } // read MWMO chunk chunk_size = readChunkHead( i_str, "MWMO", (char*)&_mwmoChunk ); if ( _mwmoChunk.size ) { _wmoNames.resize( _mwmoChunk.size ); i_str.read( (char*)&_wmoNames[0], _mwmoChunk.size ); } // read MMID chunk chunk_size = readChunkHead( i_str, "MWID", (char*)&_mwidChunk ); if ( _mwidChunk.size ) { _mwmoIndices.resize( _mwidChunk.size / 4 ); i_str.read( (char*)&_mwmoIndices[0], _mwidChunk.size ); } // read MDDF chunk chunk_size = readChunkHead( i_str, "MDDF", (char*)&_mddfChunk ); if ( _mddfChunk.size ) { _doodadInfo.resize( _mddfChunk.size / sizeof( MddfChunk_s::DoodadInfo_s ) ); i_str.read( (char*)&_doodadInfo[0], _mddfChunk.size ); } // read MODF chunk chunk_size = readChunkHead( i_str, "MODF", (char*)&_modfChunk ); if ( _modfChunk.size ) { _wmoInfo.resize( _modfChunk.size / sizeof( ModfChunk_s::WmoInfo_s ) ); i_str.read( (char*)&_wmoInfo[0], _modfChunk.size ); } parseObjectReferences( i_str ); } //------------------------------------------------------------------------------ void Obj0::parseObjectReferences( std::istream &i_str ) { // the same amount of MCNKs as in the usual *.adt files _objectRefs.resize( 256 ); size_t zero_mem_size = sizeof( ObjMcnkChunk_s ) + sizeof( McrdChunk_s ) + sizeof( McrwChunk_s ); // get all object reference MCNKs for ( int i = 0; i < 256; i++ ) { memset( &_objectRefs[i], 0, zero_mem_size ); // set all chunks to zero // there is always a MCNK chunk first ObjMcnkChunk_s &mcnk_chunk = _objectRefs[0].mcnkChunk; i_str.read( (char*)&mcnk_chunk, sizeof( ObjMcnkChunk_s ) ); size_t data_off = i_str.tellg(); // I believe there is no MCRW without MCRD chunks, but MCRD is always first if ( mcnk_chunk.size ) { McrdChunk_s &mcrd_chunk = _objectRefs[i].mcrdChunk; i_str.read( (char*)&mcrd_chunk, sizeof( McrdChunk_s ) ); // read doodad indices _objectRefs[i].doodadIndices.resize( mcrd_chunk.size / 4 ); i_str.read( (char*)&_objectRefs[i].doodadIndices[0], mcrd_chunk.size ); // check if there's a MCRW chunk left to read if ( (data_off + mcnk_chunk.size) > i_str.tellg() ) { McrwChunk_s &mcrw_chunk = _objectRefs[i].mcrwChunk; i_str.read( (char*)&mcrw_chunk, sizeof( McrwChunk_s ) ); // read WMO indices _objectRefs[i].wmoIndices.resize( mcrw_chunk.size / 4 ); i_str.read( (char*)&_objectRefs[i].wmoIndices[0], mcrw_chunk.size ); } } } } //------------------------------------------------------------------------------ const ObjectReferences_t& Obj0::getObjectRefs() const { return _objectRefs; } //------------------------------------------------------------------------------ const WmoInformations_t& Obj0::wmoInfo() const { return _wmoInfo; } //------------------------------------------------------------------------------ void Obj0::getDoodad( uint32_t index, Doodad_s *doodad ) const { if ( index+1 > _doodadInfo.size() ) return; const MddfChunk_s::DoodadInfo_s &doodad_info = _doodadInfo[index]; uint32_t mmid = doodad_info.id; // index into the doodad indices uint32_t name_off = _mmdxIndices[mmid]; // name offset std::stringbuf str_buf( _doodadNames ); std::istream i_str( &str_buf ); char dn_buf[256]; // buffer to hold the name returned by getline i_str.seekg( name_off ); // position stream at the right position i_str.getline( dn_buf, 256, '\0' ); std::string doodad_name( dn_buf ); // I like strings :) // return data memcpy( &doodad->info, &doodad_info, sizeof( MddfChunk_s::DoodadInfo_s ) ); doodad->name = doodad_name; } //------------------------------------------------------------------------------ void Obj0::getWmo( uint32_t index, Wmo_s *wmo ) const { if ( index+1 > _wmoInfo.size() ) return; // pretty much the same as in getDoodad() const ModfChunk_s::WmoInfo_s &wmo_info = _wmoInfo[index]; uint32_t mwid = wmo_info.id; uint32_t name_off = _mwmoIndices[mwid]; std::stringbuf str_buf( _wmoNames ); std::istream i_str( &str_buf ); char dn_buf[256]; i_str.seekg( name_off ); i_str.getline( dn_buf, 256, '\0' ); std::string wmo_name( dn_buf ); // return data memcpy( &wmo->info, &wmo_info, sizeof( ModfChunk_s::WmoInfo_s ) ); wmo->name = wmo_name; }
[ [ [ 1, 146 ] ] ]
d278cdf8d1b800540876f62aba809672f26752ca
95a3e8914ddc6be5098ff5bc380305f3c5bcecb2
/src/FusionForever_lib/MiniBolt.cpp
939ba083e773c5eab9f36b45d47e33c8a4976d16
[]
no_license
danishcake/FusionForever
8fc3b1a33ac47177666e6ada9d9d19df9fc13784
186d1426fe6b3732a49dfc8b60eb946d62aa0e3b
refs/heads/master
2016-09-05T16:16:02.040635
2010-04-24T11:05:10
2010-04-24T11:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,262
cpp
#include "StdAfx.h" #include "MiniBolt.h" #include "Puff.h" bool MiniBolt::initialised_ = false; int MiniBolt::fill_dl_ = 0; int MiniBolt::fill_verts_index_ = 0; MiniBolt::MiniBolt(Vector3f _position) :Projectile() { if(!initialised_) { InitialiseGraphics(); initialised_ = true; } fill_.GetFillVerts() = Datastore::Instance().GetVerts(fill_verts_index_); fill_.SetDisplayList(fill_dl_); fill_.SetFillColor(GLColor(255, 0, 0)); damage_ = 75; lifetime_ = 6.0; velocity_.y = 320; position_ = _position; mass_ = 25; } MiniBolt::~MiniBolt(void) { } void MiniBolt::InitialiseGraphics() { boost::shared_ptr<std::vector<Vector3f>> temp_fill = boost::shared_ptr<std::vector<Vector3f>>(new std::vector<Vector3f>()); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( 0, 2, 0)); temp_fill->push_back(Vector3f( 1.414, 1.414, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( 1.414, 1.414, 0)); temp_fill->push_back(Vector3f( 2, 0, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( 2, 0, 0)); temp_fill->push_back(Vector3f( 1.414, -1.414, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( 1.414, -1.414, 0)); temp_fill->push_back(Vector3f( 0, 2, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( 0, 2, 0)); temp_fill->push_back(Vector3f( -1.414, -1.414, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( -1.414, -1.414, 0)); temp_fill->push_back(Vector3f( -2, 0, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( -2, 0, 0)); temp_fill->push_back(Vector3f( -1.414, 1.414, 0)); temp_fill->push_back(Vector3f( 0, 0, 0)); temp_fill->push_back(Vector3f( -1.414, 1.414, 0)); temp_fill->push_back(Vector3f( 0, 2, 0)); fill_verts_index_ = Datastore::Instance().AddVerts(temp_fill); fill_dl_ = Filled::CreateFillDisplayList(temp_fill); } void MiniBolt::Hit(std::vector<Decoration_ptr>& _spawn, std::vector<Projectile_ptr>& /*_projectile_spawn*/) { Decoration_ptr puff = Decoration_ptr(new Puff()); puff->SetPosition(position_); _spawn.push_back(puff); }
[ "EdwardDesktop@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7", "[email protected]" ]
[ [ [ 1, 71 ], [ 73, 78 ] ], [ [ 72, 72 ] ] ]
81dbf69b5e1248f51593de1ff9e26881276ef174
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/demo/demo_model/ModelApp.h
5f24fbd92cf0c8a7a376949bb781cc42c8b3f256
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
587
h
/*! * \file ModelApp.h * \date 1-3-2010 21:43:12 * * * \author zjhlogo ([email protected]) */ #ifndef __MODELAPP_H__ #define __MODELAPP_H__ #include "../common/BaseApp.h" #include <OECore/IOEModel.h> #include <vector> class CModelApp : public CBaseApp { public: CModelApp(); virtual ~CModelApp(); virtual bool UserDataInit(); virtual void UserDataTerm(); virtual void Update(float fDetailTime); private: void Init(); void Destroy(); private: IOEModel* m_pModel; IOENode* m_pNode1; IOENode* m_pNode2; }; #endif // __MODELAPP_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 36 ] ] ]
231f09c0c32924db48d850dd680bbd06bfd0f384
e192cc5a9f9dc057cc6e84c755f69f73f6cb1a8b
/PyramidNode.cpp
229d45f211725db68a68d5bf48af7f8ec28d54c9
[]
no_license
jnv/fit-swoopers
2177f91a190fa6c1dcd9cb7a816f1d07711ef9c4
4cf2fd2c57ba4c5809524a12d510a56cc614cc23
refs/heads/master
2021-01-12T06:02:33.360673
2011-12-06T17:59:24
2018-12-13T10:14:12
77,281,895
0
0
null
null
null
null
UTF-8
C++
false
false
4,494
cpp
#include "PyramidNode.h" GLuint PyramidNode::m_vertexBufferObject = 0; GLuint PyramidNode::m_program = 0; GLint PyramidNode::m_PVMmatrixLoc = -1; GLint PyramidNode::m_posLoc = -1; GLint PyramidNode::m_colLoc = -1; static const float vertexData[] = { // vertices for the base of the pyramid 0.0f, 0.0f, 0.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0, 0.5f, 0.866f, 0.0f, 1.0, 0.0f, 0.0f, 0.0f, 1.0, 0.5f, 0.866f, 0.0f, 1.0, -0.5f, 0.866f, 0.0f, 1.0, 0.0f, 0.0f, 0.0f, 1.0, -0.5f, 0.866f, 0.0f, 1.0, -1.0f, 0.0f, 0.0f, 1.0, 0.0f, 0.0f, 0.0f, 1.0, -1.0f, 0.0f, 0.0f, 1.0, -0.5f, -0.866f, 0.0f, 1.0, 0.0f, 0.0f, 0.0f, 1.0, -0.5f, -0.866f, 0.0f, 1.0, 0.5f, -0.866f, 0.0f, 1.0, 0.0f, 0.0f, 0.0f, 1.0, 0.5f, -0.866f, 0.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0, // vertices for the sides of the pyramid 0.0f, 0.0f, 1.0f, 1.0, 0.5f, 0.866f, 0.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0, -0.5f, 0.866f, 0.0f, 1.0, 0.5f, 0.866f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0, -1.0f, 0.0f, 0.0f, 1.0, -0.5f, 0.866f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0, -0.5f, -0.866f, 0.0f, 1.0, -1.0f, 0.0f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0, 0.5f, -0.866f, 0.0f, 1.0, -0.5f, -0.866f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0, 0.5f, -0.866f, 0.0f, 1.0, // color for the bottom of the pyramid 1.0f, 1.0f, 1.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // color for the sides of the pyramid 1.0f, 1.0f, 1.0f, 1.0, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, }; /** * Load shaders, bind variables locations * @param name * @param parent */ PyramidNode::PyramidNode(const char * name, SceneNode * parent): SceneNode(name, parent) { if(m_program == 0) { std::vector<GLuint> shaderList; // Push vertex shader and fragment shader shaderList.push_back(CreateShader(GL_VERTEX_SHADER, "PyramidNode.vert")); shaderList.push_back(CreateShader(GL_FRAGMENT_SHADER, "PyramidNode.frag")); // Create the program with two shaders m_program = CreateProgram(shaderList); m_PVMmatrixLoc = glGetUniformLocation(m_program, "PVMmatrix"); m_posLoc = glGetAttribLocation(m_program, "position"); m_colLoc = glGetAttribLocation(m_program, "color"); } if(m_vertexBufferObject == 0) { glGenBuffers(1, &m_vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } } /** * Draw the pyramid * @param scene_params */ void PyramidNode::draw(SceneParams * scene_params) { // inherited draw - draws all children SceneNode::draw(scene_params); glm::mat4 matrix = scene_params->projection_mat * scene_params->view_mat * globalMatrix(); glUseProgram(m_program); glUniformMatrix4fv(m_PVMmatrixLoc, 1, GL_FALSE, glm::value_ptr(matrix)); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferObject); glEnableVertexAttribArray(m_posLoc); glEnableVertexAttribArray(m_colLoc); // vertices of triangles glVertexAttribPointer(m_posLoc, 4, GL_FLOAT, GL_FALSE, 0, 0); // 8 = 4 + 4 floats per vertex - color glVertexAttribPointer(m_colLoc, 4, GL_FLOAT, GL_FALSE, 0, (void*)(4*sizeof(vertexData)/(8))); glDrawArrays(GL_TRIANGLES, 0, sizeof(vertexData)/(8*sizeof(float))); // 8 = 4+4 floats per vertex glDisableVertexAttribArray(m_posLoc); glDisableVertexAttribArray(m_colLoc); }
[ [ [ 1, 171 ] ] ]
625e211430117ebb5697f5a089db8b57a772cc2c
cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0
/http/async_client_connection.hpp
bc1d16b3dc9f003cabeafccdc794c39bda31fe68
[ "BSL-1.0" ]
permissive
ssiloti/http
a15fb43c94c823779f11fb02e147f023ca77c932
9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e
refs/heads/master
2021-01-01T19:10:36.886248
2011-11-07T19:29:22
2011-11-07T19:29:22
1,021,325
0
1
null
null
null
null
UTF-8
C++
false
false
4,716
hpp
// // async_client_connection.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2011 Steven Siloti ([email protected]) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_ASYNC_CLIENT_CONNECTION_HPP #define HTTP_ASYNC_CLIENT_CONNECTION_HPP #include <http/async_connection.hpp> #include <http/parsers/message_state.hpp> #include <boost/asio/write.hpp> #include <boost/bind/protect.hpp> #include <boost/make_shared.hpp> namespace http { template <typename Stream> class async_client_connection : public async_connection<Stream> { typedef async_client_connection<Stream> this_type; typedef async_connection<Stream> base_type; typedef std::deque<boost::function<void()> > send_queue_t; typedef std::deque<boost::function<void()> > receive_queue_t; typedef std::vector<boost::uint8_t> send_buffer_t; public: async_client_connection(boost::asio::io_service& io_service) : async_connection<Stream>(io_service) { } template <typename Request, typename Response, typename Handler> void write_request(const Request& request, Response& response, Handler handler) { send_queue_.push_back( boost::bind( &this_type::write_next_request<Request, Response, Handler>, this, // does not need to be a shared_ptr since the container we're storing it in is a member of this boost::cref(request), boost::ref(response), handler ) ); if (send_queue_.size() == 1) send_queue_.front()(); } boost::shared_ptr<this_type> shared_from_this() { return boost::static_pointer_cast<this_type>(async_connection<Stream>::shared_from_this()); } boost::shared_ptr<const this_type> shared_from_this() const { return boost::static_pointer_cast<const this_type>(async_connection<Stream>::shared_from_this()); } private: template <typename Request, typename Response, typename Handler> void write_next_request(const Request& request, Response& response, Handler handler) { using namespace boost::asio; typename base_type::generation_iterator sink(this->start_generation()); generators::generate_message(sink, request); async_write( this->socket_, this->vectorize(sink), boost::bind( &this_type::request_written<Response, Handler>, this->shared_from_this(), placeholders::error, placeholders::bytes_transferred, boost::ref(response), handler ) ); } template <typename Response, typename Handler> void request_written(const boost::system::error_code& error, std::size_t bytes_transfered, Response& response, Handler handler) { if (error) { this->socket_.close(); handler(error); return; } send_queue_.pop_front(); if (!send_queue_.empty()) send_queue_.front()(); receive_queue_.push_back( boost::bind( &this_type::read_next_response<Response, Handler>, this, // does not need to be a shared_ptr since the container we're storing it in is a member of this boost::ref(response), handler ) ); if (receive_queue_.size() == 1) receive_queue_.front()(); } template <typename Response, typename Handler> void read_next_response(Response& response, Handler handler) { read_message(boost::system::error_code(), 0, boost::make_shared<parsers::message_state<Response, typename base_type::recv_buffer_t::iterator> >(response), boost::protect(boost::bind(&this_type::response_read<Handler>, shared_from_this(), boost::asio::placeholders::error, handler))); } template <typename Handler> void response_read(const boost::system::error_code& error, Handler handler) { if (!error) { receive_queue_.pop_front(); if (!receive_queue_.empty()) receive_queue_.front()(); } handler(error); } send_queue_t send_queue_; receive_queue_t receive_queue_; }; } #endif
[ [ [ 1, 145 ] ] ]
4a7e8d053633d167fab786c52cc12319fc76cda1
c0e409a05077ef54cf356044686d6858e302e303
/Assignment3/3DDrawing/gyroscope.cpp
37e8ae125eb6249bcc6ff30fd6e8152c3fbfac7d
[]
no_license
mcd8604/cg1
e4bc4c9e00f05ff773837fbddf4615956dc6f203
e4bb436d3dc737b9f968388164c5bbfc2198d02a
refs/heads/master
2018-12-28T02:06:04.157991
2008-11-06T18:05:09
2008-11-06T18:05:09
40,638,417
0
0
null
null
null
null
UTF-8
C++
false
false
9,058
cpp
// gyroscope.cpp : Defines the entry point for the console application. // author: Mike DeMauro #include "stdafx.h" #include <stdlib.h> #include <cstdio> #include <cmath> #include "GL/glut.h" using namespace std; // Screen size #define RES_WIDTH 800.0 #define RES_HEIGHT 800.0 // Number of gyroscope rings int numRings = 1; #define MIN_RINGS 1 #define MAX_RINGS 14 // Speed of gyroscope rotation float rot = 0.0; float rotSpeed = 0.0; #define ROT_ACCEL 0.001; #define PI 3.14159265 // Holds values for the View transform struct Camera { int ID; GLdouble eyeX; GLdouble eyeY; GLdouble eyeZ; GLdouble centerX; GLdouble centerY; GLdouble centerZ; GLdouble upX; GLdouble upY; GLdouble upZ; void CreateLookAt() { gluLookAt ( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } }; // Camera structs Camera cam1; Camera cam2; Camera *curCam; bool light0; bool light1; bool light2; bool light3; // array of texture id's GLuint textures[2]; // Sets up lighting for 4 light sources void InitLighting() { glEnable(GL_LIGHTING); glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE ); glEnable(GL_LIGHT0); light0 = true; glEnable(GL_LIGHT1); light1 = true; glEnable(GL_LIGHT2); light2 = true; glEnable(GL_LIGHT3); light3 = true; glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); } // Sets up two cameras void InitCameras() { cam1 = *new Camera(); cam1.eyeY = 0.0; cam1.eyeZ = 5.0; cam1.upY = 1.0; cam1.ID = 0; cam2 = *new Camera(); cam2.upY = 1.0; cam2.ID = 1; curCam = &cam1; } /* * LoadTexturePPM - copied from Nan's directory. Originally * written by: Blaine Hodge */ int LoadTexturePPM( const char * filename, int w, int h, int color ) { GLubyte *data; FILE * file; /* open texture data */ file = fopen( filename, "rb" ); if ( file == NULL ) return 0; /* allocate buffer */ data = (GLubyte*)malloc( w * h * 3 * (sizeof(GLubyte))); /* read texture data */ fread( data, w * h * 3, 1, file ); fclose( file ); /* build our tex image */ glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); if (color) { glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); } else { glTexImage2D( GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data ); } /* free buffer */ free( data ); return 1; } // Loads textures void LoadTextures() { glPixelStorei( GL_UNPACK_ALIGNMENT, 1); glGenTextures(2, textures); glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); glBindTexture(GL_TEXTURE_2D, textures[0]); if (!LoadTexturePPM("metal.bmp", 256, 256, 1)) { printf("Error loading texture!"); } glBindTexture(GL_TEXTURE_2D, textures[1]); if (!LoadTexturePPM("metalFloor.bmp", 256, 256, 1)) { printf("Error loading texture!"); } } //Initializes OpenGL and ... void Initialize() { // Init GL glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); // Init lighting InitLighting(); // Init cameras InitCameras(); // Init Textures glEnable( GL_TEXTURE_2D ); LoadTextures(); // clear the matrix glLoadIdentity (); } // Updates the scene void update() { // increment rotation to animate gyroscope rot += rotSpeed; if(rot > 360) rot = 0.0; // update camera 2 // TODO: optimize float x1, y1, z1, x2, y2, z2; float rad = (rot) * PI / 180; // y-axis x1 = cos(rad); y1 = 0; z1 = sin(rad); // x-axis x2 = 0; y2 = cos(rad); z2 = sin(rad); cam2.eyeX = x1 + x2; cam2.eyeY = y1 + y2; cam2.eyeZ = z1 + z2; glutPostRedisplay(); } // Ring material params GLfloat mat_ambient[] = { 0.1, 0.1, 0.1, 1.0 }; GLfloat mat_diffuse[] = { 0.5, 0.5, 0.5, 1.0 }; GLfloat mat_specular[] = { 0.7, 0.7, 0.7, 1.0 }; GLfloat mat_shine[] = {30}; // Draws the gyroscope void drawGyroscope() { glPushMatrix(); glBindTexture(GL_TEXTURE_2D, textures[0]); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shine); // center sphere glutSolidSphere(.25, 64 , 64); // torus1 glRotatef(rot, 0.0, 1.0, 0.0); glScalef (1.2, 1.2, 1.2); //gluCylinder(gluNewQuadric(), 1.0, 1.0, 0.1, 64, 8); //gluDisk(gluNewQuadric(), 0.9, 1.0, 64, 16); //glRotatef(rot, 0.0, 1.0, 0.0); glutSolidTorus(0.05, 1.5, 16, 64); for(int i = 0; i < numRings - 1; ++i) { if(i % 2 == 0) { glRotatef(rot, 0.0, 1.0, 0.0); } else { glRotatef(rot, 1.0, 0.0, 0.0); } //glRotatef(rot, 1.0 * (i % 2), 1.0 * (i % 1), 0.0); glScalef (0.9, 0.9, 0.9); glutSolidTorus(0.05, 1.5, 16, 64); } glPopMatrix(); } GLfloat floorAmbient[] = { 1.0, 1.0, 1.0, 1.0 }; // Draws the base of the scene void drawBase() { glBindTexture(GL_TEXTURE_2D, textures[1]); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, floorAmbient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shine); glPushMatrix(); glTranslatef(0.0, -1.9, 0.0); glRotatef(90.0, 1.0, 0.0, 0.0); gluDisk(gluNewQuadric(), 0.0, 4.0, 64, 32); glPopMatrix(); } // lighting parameters GLfloat position1[] = { 2.0, -2.0, 2.0, 1.0 }; GLfloat ambient[] = { 0.2, 0.2, 0.2, 1.0 }; GLfloat position2[] = { -2.0, 2.0, 2.0, 1.0 }; GLfloat diffuse[] = { 0.7, 0.7, 0.3, 1.0 }; GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat position3[] = { 0.0, 5.0, 0.0 }; GLfloat down[] = { 0.0, -1.0, 0.0 }; // Sets the lighting for draw void lighting() { glLightfv(GL_LIGHT0, GL_POSITION, position1); glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT1, GL_POSITION, position2); glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT2, GL_POSITION, position2); glLightfv(GL_LIGHT2, GL_SPECULAR, specular); glLightfv(GL_LIGHT3, GL_POSITION, position3); glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, down); glLightfv(GL_LIGHT3, GL_DIFFUSE, diffuse); } // Draws the graphics void Draw() { glPushMatrix(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glColor3f (1.0, 1.0, 1.0); // view transform curCam->CreateLookAt(); // lighting lighting(); // world transforms drawBase(); drawGyroscope(); glFlush(); glutSwapBuffers(); glPopMatrix(); } // Handles keyboard input void keyboard(unsigned char key, int x, int y) { if(key == 113) { // q, quit exit(0); } else if(key == 99) { // c, switches camera curCam = curCam->ID == 0 ? &cam2 : &cam1; } else if(key == 97) { // a, speed up rotSpeed += ROT_ACCEL; } else if(key == 122) { // z, slow down rotSpeed -= ROT_ACCEL; } else if(key == 49) { // 1, toggle light 0 light0 ? glDisable(GL_LIGHT0) : glEnable(GL_LIGHT0); light0 = !light0; } else if(key == 50) { // 2, toggle light 1 light1 ? glDisable(GL_LIGHT1) : glEnable(GL_LIGHT1); light1 = !light1; } else if(key == 51) { // 3, toggle light 2 light2 ? glDisable(GL_LIGHT2) : glEnable(GL_LIGHT2); light2 = !light2; } else if(key == 52) { // 4, toggle light 3 light3 ? glDisable(GL_LIGHT3) : glEnable(GL_LIGHT3); light3 = !light3; } else if(key == 115) { // 115, add ring if(numRings < MAX_RINGS) { ++numRings; } } else if(key == 120) { // 120, remove ring if(numRings > MIN_RINGS) { --numRings; } } } // Handles window resizing void reshape (int w, int h) { glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(54.0, 1.0, 0.01, 20.0); glMatrixMode (GL_MODELVIEW); } // Free up allocated memory void Unload() { delete curCam; } // Entry point int _tmain(int argc, char** argv) { glEnable(GL_DOUBLEBUFFER); glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowPosition(10, 10); glutInitWindowSize(RES_WIDTH,RES_HEIGHT); glutCreateWindow("2D Drawing"); Initialize(); glutDisplayFunc(Draw); glutReshapeFunc(reshape); glutIdleFunc(update); glutKeyboardFunc(keyboard); glutMainLoop(); Unload(); return 0; }
[ [ [ 1, 398 ] ] ]
e563bafa7e104866b53d4fffec011f8264a2c6dc
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/Networking/ChatEntity.cpp
e65b2ebc6d8f7415ee9256d9ce2a47840b98aa43
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
2,236
cpp
#include "ChatEntity.h" #include "NetworkIDManager.h" #include "ChatEventParser.h" #include "TextEvent.h" #include "NotifyEvent.h" #include <iostream> namespace HovUni { std::string ChatEntity::getClassName() { return "ChatEntity"; } ChatEntity::ChatEntity() : NetworkEntity(0) { } ChatEntity::~ChatEntity() { } void ChatEntity::sendLine(const string& user, const string& line) { sendEvent(TextEvent(user, line)); } void ChatEntity::sendNotification(const std::string& notif) { if (mNode->getRole() == eZCom_RoleAuthority) { sendEvent(NotifyEvent(notif)); } } void ChatEntity::parseEvents(eZCom_Event type, eZCom_NodeRole remote_role, ZCom_ConnID conn_id, ZCom_BitStream* stream, float timeSince) { //if user event if (type == eZCom_EventUser) { ChatEventParser p; ChatEvent* cEvent = p.parse(stream); eZCom_NodeRole role = mNode->getRole(); switch (role) { case eZCom_RoleAuthority: processEventsServer(cEvent); break; default: processEventsClient(cEvent); break; } delete cEvent; } } void ChatEntity::processEventsServer(ChatEvent* cEvent) { // A text line TextEvent* text = dynamic_cast<TextEvent*> (cEvent); if (text) { // TODO Maybe some advanced checking for bad language? sendEvent(*text); } // Notification events are not processed because they // are sent by the server and should not pass this function } void ChatEntity::processEventsClient(ChatEvent* cEvent) { // A text line TextEvent* text = dynamic_cast<TextEvent*> (cEvent); if (text) { // Update all the listeners std::string user = text->getUser(); std::string line = text->getLine(); for (listener_iterator it = listenersBegin(); it != listenersEnd(); ++it) { (*it)->newMessage(user, line); } } // A notification NotifyEvent* notify = dynamic_cast<NotifyEvent*> (cEvent); if (notify) { // Update all the listeners std::string line = notify->getLine(); for (listener_iterator it = listenersBegin(); it != listenersEnd(); ++it) { (*it)->newNotification(line); } } } void ChatEntity::setupReplication() { } void ChatEntity::setAnnouncementData(ZCom_BitStream* stream) { } }
[ "berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "pintens.pieterjan@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c", "dirk.delahaye@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 34 ], [ 36, 36 ], [ 40, 41 ], [ 43, 44 ], [ 46, 46 ], [ 49, 51 ], [ 53, 53 ], [ 55, 63 ], [ 65, 65 ], [ 67, 76 ], [ 78, 95 ] ], [ [ 35, 35 ], [ 37, 37 ], [ 39, 39 ], [ 47, 47 ] ], [ [ 38, 38 ], [ 42, 42 ], [ 45, 45 ], [ 48, 48 ], [ 52, 52 ], [ 54, 54 ], [ 64, 64 ], [ 66, 66 ], [ 77, 77 ] ] ]
2350ea2e40990f09b846be7b4967a49a4fa5296b
c7fd308ee062c23e1b036b84bbf890c3f7e74fc4
/ExamenSegundoParcial/2doParcial_1163990_1162205.cpp
8abc27e97560584aa5f54d3759f75e422a114c16
[]
no_license
truenite/truenite-opengl
805881d06a5f6ef31c32235fb407b9a381a59ed9
157b0e147899f95445aed8f0d635848118fce8b6
refs/heads/master
2021-01-10T01:59:35.796094
2011-05-06T02:03:16
2011-05-06T02:03:16
53,160,700
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,083
cpp
/*************************************************** Materia: Gráficas Computacionales Examen Segundo Parcial Fecha: 3 de Marzo de 2011 Autor 1: 1162205 Diego Alfonso García Mendiburu Autor 2: 1163990 Andres Rocha Bravo ***************************************************/ #include <windows.h> #include <GL/glut.h> #include <stdio.h> #include "mesh.h" float rotationX=0.0; float rotationY=0.0; float prevX=0.0; float prevY=0.0; bool mouseDown=false; float viewer[]= {0.0, 0.0, 30.0}; int displayMode=2; mesh *object; void init(){ object = new mesh("box.obj"); } void display(void){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0); glRotatef(rotationX,1,0,0); glRotatef(rotationY,0,1,0); glColor3f(1.0, 1.0, 1.0); if(displayMode==1){ glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); //glBegin(GL_LINES);// wire } else{ glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); // solid } glBegin(GL_TRIANGLES); for (int i=0;i < object->fTotal; i++) { for(int j = 0; j < 3;j++){ glVertex3fv(object->vList[object->faceList[i][j].v].ptr); } } glEnd(); glutSwapBuffers(); } void reshape(int w, int h){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (GLdouble)w/(GLdouble)h, 0.0, 500.0); glViewport(0,0,w,h); } void mouse(int button, int state, int x, int y){ if(button == GLUT_LEFT_BUTTON && state==GLUT_DOWN){ mouseDown = true; prevX = x - rotationY; prevY = y - rotationX; }else{ mouseDown = false; } } void mouseMotion(int x, int y){ if(mouseDown){ rotationX = y - prevY; rotationY = x - prevX; glutPostRedisplay(); } } void key(unsigned char key, int x, int y) { if(key == 'x') viewer[0]-= 0.1; if(key == 'X') viewer[0]+= 0.1; if(key == 'y') viewer[1]-= 0.1; if(key == 'Y') viewer[1]+= 0.1; if(key == 'z') viewer[2]-= 0.1; if(key == 'Z') viewer[2]+= 0.1; glutPostRedisplay(); } void menu(int val){ displayMode=val; glutPostRedisplay(); } int addMenu(){ int mainMenu, subMenu1; mainMenu = glutCreateMenu(menu); subMenu1 = glutCreateMenu(menu); glutSetMenu(mainMenu); glutAddSubMenu("Display mode", subMenu1); glutSetMenu(subMenu1); glutAddMenuEntry("Wireframe", 1); glutAddMenuEntry("Solid", 2); glutSetMenu(mainMenu); glutAttachMenu(GLUT_RIGHT_BUTTON); } int main(int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Segundo Parcial"); glutInitWindowSize(500,500); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(mouseMotion); glutKeyboardFunc(key); gluPerspective(45.0,1.0,0,500); addMenu(); init(); glutMainLoop(); }
[ [ [ 1, 129 ] ] ]
8f11627e7dbb12d93b413db56bfb0c6043529cd9
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/OgreDemo/stdafx.cpp
85fa12b66d23597f41e63528997287ea225c77bb
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
GB18030
C++
false
false
268
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // OgreDemo.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f" ]
[ [ [ 1, 8 ] ] ]
5546ab20a0c6e1428e07588349d8320132cab73a
93eac58e092f4e2a34034b8f14dcf847496d8a94
/ncl30-cpp/ncl30-generator/src/BindExtraComNomeGrande.cpp
71ec87e715b79c8e0ead3f96fbba1d53d02e4db6
[]
no_license
lince/ginga-srpp
f8154049c7e287573f10c472944315c1c7e9f378
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
refs/heads/master
2020-05-27T07:54:24.324156
2011-10-17T13:59:11
2011-10-17T13:59:11
2,576,332
0
0
null
null
null
null
UTF-8
C++
false
false
3,346
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file BindGenerator.cpp * @author Caio Viel * @date 29-01-10 */ #include "../include/generables/BindGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generator { string BindGenerator::generateCode() { string ret = "<bind "; string componentId = this->getNode()->getId(); ret += "component=\"" + componentId + "\" "; InterfacePoint* interface = this->getInterfacePoint(); if (interface != NULL) { string interfaceId = interface->getId(); if (interfaceId != componentId) { ret += "interface=\"" + interface->getId() + "\" "; } } ret += "role=\"" + this->getRole()->getLabel() + "\" "; GenericDescriptor* descriptor = this->getDescriptor(); if (descriptor != NULL) { ret += "descriptor=\"" + descriptor->getId() + "\" "; } vector<Parameter*>* parameters = this->getParameters(); if (parameters != NULL) { vector<Parameter*>::iterator itParam = parameters->begin(); ret +=">\n"; while (itParam != parameters->end()) { Parameter* parameter = *itParam; ret += static_cast<ParameterGenerator*>(parameter)->generateCode("bindParam", "value"); itParam++; } ret+= "</bind>\n"; } else { ret += "/>\n"; } return ret; } } } } } }
[ [ [ 1, 102 ] ] ]
760defb06e1dec1b69f0559e568d66066252e16c
61352a7371397524fe7dcfab838de40d502c3c9a
/client/Headers/Utils/DataObserver.h
73965f0d17cd4322f37664a46a923c1501f1df55
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
UTF-8
C++
false
false
506
h
#ifndef DATAOBSERVER_H #define DATAOBSERVER_H #include "DataObserverData.h" /// /// DataObserver /// @brief Klasa bazowa dla obserwatorow danych. /// @author Wojciech Grzeskowiak /// @date 2009.01.13 /// class DataObserver { public: /// /// Kosntruktor. /// DataObserver(); /// /// Destruktor. /// virtual ~DataObserver(); /// /// Metoda referesh. /// virtual int Refresh(DataObserverData data) = 0; }; #endif
[ "coutoPL@c118a9a8-d993-11dd-9042-6d746b85d38b", "w.grzeskowiak@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 5 ], [ 12, 15 ], [ 19, 20 ], [ 24, 25 ], [ 29, 29 ], [ 31, 32 ] ], [ [ 6, 11 ], [ 16, 18 ], [ 21, 23 ], [ 26, 28 ], [ 30, 30 ] ] ]
861d3cbbf9bcf5178bbc6fc8f3179ed2c9d8b098
ad4efcf3f85fbce0f0d1ca0be7d2bc7016f68aad
/dijkstra.cpp
1664bf4201be3a5d1ff3f608655f1eb716c22f26
[]
no_license
HustLion/acm-snippets
362f53ad827e05b8626f453ac8da5a4e5064f24d
0d1b0727fd81105b47f07d052a310499ceab18c3
refs/heads/master
2021-01-24T04:20:41.019488
2011-09-04T14:00:49
2011-09-04T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
cpp
struct edge { int to,weight; edge() { } edge(int a,int b):to(a),weight(b) { } }; struct state { int node,distance; state() { } state(int a,int b):node(a),distance(b) { } }; bool operator<(const state &x,const state &y) { return x.distance>y.distance; // top of priority_queue is maximum } int dijkstra(vector<edge> [],int,int,int); int dijkstra(vector<edge> graph[],int n,int source,int destination) { int dist[n+2]; // distance from start vertex to each vertex memset(dist,0x3f,sizeof(dist)); priority_queue<state> Q; dist[source]=0; Q.push(state(source,0)); while(Q.empty()==false) { state now=Q.top(); Q.pop(); int curr_dist=now.distance; int curr_node=now.node; if(curr_node==destination) return curr_dist; if(curr_dist>dist[curr_node]) continue; int i,tmp,next_node; for(i=0;i<graph[curr_node].size();++i) { tmp=curr_dist+graph[curr_node][i].weight; next_node=graph[curr_node][i].to; if(tmp<dist[next_node]) { dist[next_node]=tmp; Q.push(state(next_node,tmp)); } } } return -1;//no connection exists }
[ [ [ 1, 72 ] ] ]
347f509400fe94a1652078f21cb39009f09c4954
fa609a5b5a0e7de3344988a135b923a0f655f59e
/Source/tokens/Text.h
967a1b0db0630036eab3de9362d4a5d380468bef
[ "MIT" ]
permissive
Sija/swift
3edfd70e1c8d9d54556862307c02d1de7d400a7e
dddedc0612c0d434ebc2322fc5ebded10505792e
refs/heads/master
2016-09-06T09:59:35.416041
2007-08-30T02:29:30
2007-08-30T02:29:30
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
984
h
/** * Swift Parser Library * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright (c) 2007 Sijawusz Pur Rahnama * @copyright Copyright (c) 2007 Paweł Złomaniec * @version $Revision: 89 $ * @modifiedby $LastChangedBy: Sija $ * @lastmodified $Date: 2007-07-22 21:38:08 +0200 (N, 22 lip 2007) $ */ #pragma once #ifndef __SWIFT_TEXT_TOKEN_H__ #define __SWIFT_TEXT_TOKEN_H__ #include "../iToken.h" namespace Swift { namespace Tokens { class Text: public iToken { public: Text(const StringRef& text = "") : _text(text) { } public: inline string getName() const { return "Text"; } void set(const StringRef& text) { _text = text; } public: inline String output() { return _text; } protected: String _text; }; }} #endif // __SWIFT_TEXT_TOKEN_H__
[ [ [ 1, 45 ] ] ]
a90e4ce5f7c015cee4b496d2ef3d4cfa86c0da76
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/stdlith/abstractio.h
4183d730281fb51071f52ffa74922a80054bf7bb
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
4,571
h
//------------------------------------------------------------------ // // FILE : AbstractIO.h // // PURPOSE : Defines the CAbstractIO class. // // CREATED : 1st May 1996 // // COPYRIGHT : Microsoft 1996 All Rights Reserved // //------------------------------------------------------------------ #ifndef __ABSTRACTIO_H__ #define __ABSTRACTIO_H__ #ifndef __STDLITHDEFS_H__ #include "stdlithdefs.h" #endif #ifndef __LITHEXCEPTION_H__ #include "lithexception.h" #endif #ifndef __MEMORY_H__ #include "memory.h" #endif // The exception that will be thrown on a read or write fail. typedef enum { MoWriteError=0, MoReadError=1, MoSeekError=2 } LithIOExceptionType; #define LITHIO_EXCEPTION 10 class CLithIOException : public CLithException { public: CLithIOException() { SetExceptionType(LITHIO_EXCEPTION); } CLithIOException(LithIOExceptionType code) { SetExceptionType(LITHIO_EXCEPTION); m_Code=code; } LithIOExceptionType m_Code; }; class CAbstractIO { public: // Member functions CAbstractIO(); ~CAbstractIO(); virtual LTBOOL Open(const char *pFilename, const char *pAccess) { return TRUE; } virtual void Close() {} void SetUserData1(uint32 data) { m_UserData1 = data; } uint32 GetUserData1() { return m_UserData1; } void EnableExceptions(LTBOOL bEnable); LTBOOL IsExceptionsEnabled(); // Functions to toWrite data virtual LTBOOL Write(const void *pBlock, uint32 blockSize)=0; CAbstractIO& operator << (unsigned short toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (short toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (unsigned char toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (char toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (float toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (double toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (unsigned int toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } CAbstractIO& operator << (int toWrite) { Write(&toWrite, sizeof(toWrite)); return *this; } // Functions to read data virtual LTBOOL Read(void *pBlock, uint32 blockSize)=0; CAbstractIO& operator >> (long &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (unsigned short &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (short &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (unsigned char &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (char &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (float &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (double &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (unsigned int &toRead) { Read(&toRead, sizeof(toRead)); return *this; } CAbstractIO& operator >> (int &toRead) { Read(&toRead, sizeof(toRead)); return *this; } LTBOOL WriteString(const char *pStr); LTBOOL ReadString(char *pStr, uint32 maxLen); LTBOOL ReadTextString(char *pStr, uint32 maxLen); virtual uint32 GetCurPos()=0; virtual uint32 GetLen()=0; virtual LTBOOL SeekTo(uint32 pos)=0; protected: // User data stuff. uint32 m_UserData1; // Tells whether or not it should throw exceptions. LTBOOL m_bExceptionsEnabled; // Throws an exception if they're enabled. void MaybeThrowIOException(LithIOExceptionType code); }; #endif
[ [ [ 1, 133 ] ] ]
0678dd1acf4d205970f62faca82039088795565b
17cebb7bfd4138c33eb826a5f8f94a6c660c9f67
/Parallel_kNN/DataStruct.h
37535710c5b55e71bbb72b797af87505eaa8060c
[]
no_license
alphjheon/mpi-parallel-knn
c90551e766cfdc2ab2e336f0805d76db0b14602a
baedb8705d4d7c97ba899503a38e3862cf320bfb
refs/heads/master
2021-01-10T14:24:05.545830
2010-01-22T12:26:41
2010-01-22T12:26:41
47,725,595
0
0
null
null
null
null
UTF-8
C++
false
false
4,068
h
#ifndef _DATA_STRUCT_H #define _DATA_STRUCT_H #include <vector> #include <string> #include <sstream> #include <algorithm> #include "Serializable.h" using namespace std; struct DimPair { int dim; double value; const bool operator<(const DimPair& _ot) const { return dim < _ot.dim; } }; typedef std::vector<DimPair> Vector; struct Document { // double label; int label; Vector vec; void parse(string _str) { stringstream ss(_str); ss >> label; char cc; int d; double v; while (ss >> d >> cc >> v){ DimPair dp; dp.dim = d; dp.value = v; vec.push_back(dp); } sort(vec.begin(), vec.end()); } }; struct NN : public Serializable { // double label; int label; double similar; bool operator < (const NN& _n) const { return similar < _n.similar; } int Length() { // return sizeof(double) * 2; return sizeof(double) + sizeof(int); } void Serialize(unsigned char* _out, int& _len) { _len = Length(); // memcpy(_out, &label, sizeof(double)); memcpy(_out, &label, sizeof(int)); // memcpy(_out + sizeof(double), &similar, sizeof(double)); memcpy(_out + sizeof(int), &similar, sizeof(double)); } void Deserialize(unsigned char* _in, int& _len) { _len = Length(); // memcpy(&label, _in, sizeof(double)); memcpy(&label, _in, sizeof(int)); // memcpy(&similar, _in + sizeof(double), sizeof(double)); memcpy(&similar, _in + sizeof(int), sizeof(double)); } }; template <typename _Type> struct priorityQueue : public Serializable { int size; int curSize; vector<_Type> que; priorityQueue(int _size) { size = _size; curSize = 0; que.resize(size); } void Push(_Type _val) { int i; for (i = 0; i < curSize; ++i) { if (que[i] < _val) { break; } } if (i >= size) { return; } for (int j = curSize; j >= i; --j) { if (j + 1 >= size) { continue; } que[j + 1] = que[j]; } que[i] = _val; if (curSize < size) { curSize++; } } _Type& operator[](int _id) { return que[_id]; } void merge(priorityQueue<_Type>& _o) { for (int i = 0; i < _o.size; ++i) { Push(_o[i]); } } int Length() { int ret = 0; ret += sizeof(int); //size ret += sizeof(int); //curSize for (int i = 0; i < curSize; ++i) { ret += ((NN)que[i]).Length(); } return ret; } void Serialize(unsigned char* _out, int& length) { int offset = 0; memcpy(_out + offset, &size, sizeof(int)); offset += sizeof(int); memcpy(_out + offset, &curSize, sizeof(int)); offset += sizeof(int); for (int i = 0; i < curSize; ++i) { int vlen; ((NN)que[i]).Serialize(_out + offset, vlen); offset += vlen; } length = offset; } void Deserialize(unsigned char* _in, int& length) { int offset = 0; memcpy(&size, _in + offset, sizeof(int)); offset += sizeof(int); memcpy(&curSize, _in + offset, sizeof(int)); offset += sizeof(int); que.clear(); for (int i = 0; i < curSize; ++i) { int vlen; NN tpy; tpy.Deserialize(_in + offset, vlen); offset += vlen; que.push_back(tpy); } length = offset; } }; #endif
[ "huicong88126@8e47c856-0750-11df-8e78-e7f5014194b1" ]
[ [ [ 1, 190 ] ] ]
3fdf40feef7320810d80d8d64cb656f6e66ff475
6caf1a340711c6c818efc7075cc953b2f1387c04
/client/DlgReporting.h
149919414c3a99171165157382a11abcdc575c82
[]
no_license
lbrucher/timelis
35c68061bea68cc31ce1c68e3adbc23cb7f930b1
0fa9f8f5ef28fe02ca620c441783a1ff3fc17bde
refs/heads/master
2021-01-01T18:18:37.988944
2011-08-18T19:39:19
2011-08-18T19:39:19
2,229,915
2
1
null
null
null
null
UTF-8
C++
false
false
1,977
h
// $Id: DlgReporting.h,v 1.2 2005/01/13 12:23:20 lbrucher Exp $ // #if !defined(AFX_DLGREPORTING_H__06A2EB8A_8B8D_4F28_94C5_FF16E1100A47__INCLUDED_) #define AFX_DLGREPORTING_H__06A2EB8A_8B8D_4F28_94C5_FF16E1100A47__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CReporting; class CDlgReporting : public CDialog { // Construction public: CDlgReporting(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDlgReporting) enum { IDD = IDD_REPORTING }; CComboBox m_Templates; CComboBox m_MonthNames; CListBox m_Activities; int m_nFilter; COleDateTime m_PeriodFrom; COleDateTime m_PeriodTo; BOOL m_bShowDisabledActivities; int m_nMonthYear; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDlgReporting) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDlgReporting) virtual BOOL OnInitDialog(); afx_msg void OnSetfocusPeriodFrom(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnSetfocusPeriodTo(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnShowdisabledactivities(); afx_msg void OnView(); afx_msg void OnSave(); afx_msg void OnSetfocusMonthName(); afx_msg void OnSetfocusMonthYear(); afx_msg void OnManage(); //}}AFX_MSG DECLARE_MESSAGE_MAP() CStringArray m_itemDatas; void RefreshActivities(); boolean BuildReport( CReporting& report ); bool GetSelectedPeriod( COleDateTime& from, COleDateTime& to ); bool GetSelectedActivities( CDWordArray& selectedActivityIDs ); bool GetSelectedTemplate( CString& filename ); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLGREPORTING_H__06A2EB8A_8B8D_4F28_94C5_FF16E1100A47__INCLUDED_)
[ [ [ 1, 70 ] ] ]
929ab64754308640e9b9d8d4427c90c119fd798c
62207628c4869e289975cc56be76339a31525c5d
/Source/Star Foxes Skeleton/medicShipClass.h
caaf6fbc5d7ac9773963bcb68e732557b8a1e00e
[]
no_license
dieno/star-foxes
f596e5c6b548fa5bb4f5d716b73df6285b2ce10e
eb6a12c827167fd2b7dd63ce19a1f15d7b7763f8
refs/heads/master
2021-01-01T16:39:47.800555
2011-05-29T03:51:35
2011-05-29T03:51:35
32,129,303
0
0
null
null
null
null
UTF-8
C++
false
false
807
h
#ifndef STANDARDSHIPCLASS_H #define STANDARDSHIPCLASS_H #include "mainShipClass.h" class MedicShipClass : public MainShipClass { public: MedicShipClass(LPD3DXMESH mesh, D3DMATERIAL9* meshMat, LPDIRECT3DTEXTURE9* meshTex, DWORD meshNumMat, LPDIRECT3DDEVICE9 newg_pDevice) :MainShipClass(mesh, meshMat, meshTex, meshNumMat, newg_pDevice){ setMaxHealth(100); setCurrentHealth(100); } MedicShipClass(PMESHSTRUCT meshStruct, LPDIRECT3DDEVICE9 newg_pDevice) :MainShipClass(meshStruct, newg_pDevice){ setMaxHealth(100); setCurrentHealth(100); } static float getAfterburnerSpeed() { return afterburnerSpeed_; } static float getDamagePerShot() { return damagePerShot; } private: static float afterburnerSpeed_; static float damagePerShot; }; #endif
[ "[email protected]@2f9817a0-ed27-d5fb-3aa2-4a2bb642cc6a" ]
[ [ [ 1, 32 ] ] ]
c6c45ed388aea99a83c22cc511b7437c9e75f9b4
867f5533667cce30d0743d5bea6b0c083c073386
/jingxian-network/src/jingxian/networks/commands/AcceptCommand.cpp
37c7d3966984d9f3bb9ee500fad02859132124a6
[]
no_license
mei-rune/jingxian-project
32804e0fa82f3f9a38f79e9a99c4645b9256e889
47bc7a2cb51fa0d85279f46207f6d7bea57f9e19
refs/heads/master
2022-08-12T18:43:37.139637
2009-12-11T09:30:04
2009-12-11T09:30:04
null
0
0
null
null
null
null
GB18030
C++
false
false
5,616
cpp
# include "pro_config.h" # include "jingxian/networks/commands/AcceptCommand.h" # include "jingxian/networks/ConnectedSocket.h" _jingxian_begin AcceptCommand::AcceptCommand(IOCPServer* core , int family , SOCKET listenHandle , const tstring& listenAddr , OnBuildConnectionComplete onComplete , OnBuildConnectionError onError , void* context) : core_(core) , onComplete_(onComplete) , onError_(onError) , context_(context) , listener_(listenHandle) , listenAddr_(listenAddr) , socket_(WSASocket(family, SOCK_STREAM, IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED)) , ptr_((char*)my_malloc(sizeof(SOCKADDR_STORAGE)*2 + sizeof(SOCKADDR_STORAGE)*2 + 100)) , len_(sizeof(SOCKADDR_STORAGE)*2 + sizeof(SOCKADDR_STORAGE)*2 + 100) { memset(ptr_, 0, len_); } AcceptCommand::~AcceptCommand() { my_free(ptr_); ptr_ = null_ptr; if (INVALID_SOCKET != socket_) { closesocket(socket_); socket_ = INVALID_SOCKET; } } void AcceptCommand::on_complete(size_t bytes_transferred , bool success , void *completion_key , errcode_t error) { if (!success) { ErrorCode err(error, concat<tstring>(_T("接受器 '") , listenAddr_ , _T("' 获取连接请求失败 - ") , lastError(error))); onError_(err, context_); return; } //if (!acceptor_->isListening()) //{ // ErrorCode err(_T("接受器 '") // + listenAddr_ // + _T("' 获取连接请求返回,但已经停止监听!")); // onError_(err, context_); // return; //} sockaddr *local_addr = 0; sockaddr *remote_addr = 0; int local_size = 0; int remote_size = 0; /// 超级奇怪!如果直接用 GetAcceptExSockaddrs 会失败,通过调 /// 用 GetAcceptExSockaddrs 的函数指针就没有问题. networking::getAcceptExSockaddrs(ptr_, 0, sizeof(SOCKADDR_STORAGE) + sizeof(SOCKADDR_STORAGE), sizeof(SOCKADDR_STORAGE) + sizeof(SOCKADDR_STORAGE), &local_addr, &local_size, &remote_addr, &remote_size); tstring peer; if (!networking::addressToString(remote_addr, remote_size, _T("tcp"), peer)) { int errCode = ::WSAGetLastError(); ErrorCode err(errCode, concat<tstring, tchar*, tstring, tchar*, tstring>(_T("接受器 '") , listenAddr_ , _T("' 获取连接请求返回,获取远程地址失败 -") , lastError(errCode))); onError_(err, context_); return; } tstring host; if (!networking::addressToString(local_addr, local_size, _T("tcp"), host)) { int errCode = ::WSAGetLastError(); ErrorCode err(errCode, concat<tstring>(_T("接受器 '") , listenAddr_ , _T("' 获取连接请求返回,获取本地地址失败 -") , lastError(errCode))); onError_(err, context_); return; } if (SOCKET_ERROR == setsockopt(socket_, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char *) &listener_, sizeof(listener_))) { int errCode = ::WSAGetLastError(); ErrorCode err(errCode, _T("接受器 '") + listenAddr_ + _T("' 获取连接请求返回,在对 socket 句柄设置 SO_UPDATE_ACCEPT_CONTEXT 选项时发生错误 - ") + lastError(errCode)); onError_(err, context_); return; } std::auto_ptr<ConnectedSocket> connectedSocket(new ConnectedSocket(core_, socket_, host, peer)); socket_ = INVALID_SOCKET; if (!core_->bind((HANDLE)(connectedSocket->handle()), connectedSocket.get())) { int errCode = ::WSAGetLastError(); ErrorCode err(errCode, concat<tstring>(_T("初始化来自 '") , peer , _T("' 的连接时,绑定到iocp发生错误 - ") , lastError(errCode))); onError_(err, context_); return; } onComplete_(connectedSocket.get(), context_); connectedSocket->initialize(); connectedSocket.release(); } bool AcceptCommand::execute() { DWORD bytesTransferred; if (networking::acceptEx(listener_ , socket_ , ptr_ , 0 //必须为0,否则会有大量的连接处于accept中,因为客户端只 //建立连接,没有发送数据。 , sizeof(SOCKADDR_STORAGE) + sizeof(SOCKADDR_STORAGE) , sizeof(SOCKADDR_STORAGE) + sizeof(SOCKADDR_STORAGE) , &bytesTransferred , this)) return true; if (WSA_IO_PENDING == ::WSAGetLastError()) return true; return false; } _jingxian_end
[ "runner.mei@0dd8077a-353d-11de-b438-597f59cd7555" ]
[ [ [ 1, 157 ] ] ]
b71bd1c28f3efccf4b4db6b26898d74e320bb7ca
1b2f699e2299c66ef41e261ffe27bdf5602805f7
/tags/3.1.82/libs_air/jp/progression/core/includes/CastButtonContextMenu.inc
0d5dcd350ba904b97b6a942bbdf4fa20864e416d
[]
no_license
Dsnoi/progression-flash
aefd0c9405f437f0afbc34a0e4566805a9d9c709
5472c983c4ddfed998a7852277d2e72ffbb9e2c6
refs/heads/master
2016-09-05T20:04:32.875776
2011-12-05T04:21:22
2011-12-05T04:21:22
39,943,479
0
0
null
null
null
null
UTF-8
C++
false
false
3,246
inc
import flash.events.ContextMenuEvent; import flash.net.navigateToURL; import flash.net.URLRequest; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import jp.nium.core.errors.ErrorMessageConstants; import jp.progression.casts.ICastObject; import jp.progression.Progression; import jp.progression.ProgressionActivatedLicenseType; /** * パッケージ内からの呼び出しかどうかを取得します。 */ private static var _internallyCalled:Boolean = false; /** * ICastObject インスタンスを取得します。 */ private var _target:ICastObject; /** * ContextMenu インスタンスを取得します。 */ private var _menu:ContextMenu; /** * @private */ public function CastButtonContextMenu( target:ICastObject, menu:* ) { // パッケージ外から呼び出されたらエラーを送出する if ( !_internallyCalled ) { throw new ArgumentError( ErrorMessageConstants.getMessage( "ERROR_2012", "CastButtonContextMenu" ) ); }; // 引数を設定する _target = target; _menu = menu; // ビルトインメニューを非表示にする _menu.hideBuiltInItems(); // 初期化する _internallyCalled = false; // イベントリスナーを登録する _menu.addEventListener( ContextMenuEvent.MENU_SELECT, _menuSelect, false, 0, true ); } /** * @private */ progression_internal static function __createInstance( target:ICastObject, menu:* ):CastButtonContextMenu { _internallyCalled = true; return new CastButtonContextMenu( target, menu ); } /** * */ private function _hideBuiltInItems():void { } /** * */ private function _hideProgressionItems():void { } /** * ユーザーが最初にコンテキストメニューを生成したときに、コンテキストメニューの内容が表示される前に送出されます。 */ private function _menuSelect( e:ContextMenuEvent ):void { var items:Array = _menu.customItems = []; var item:ContextMenuItem; // Built on ... switch ( Progression.activatedLicenseType ) { case ProgressionActivatedLicenseType.BUSINESS_APPLICATION_LICENSE : case ProgressionActivatedLicenseType.BUSINESS_WEB_LICENSE : { break; } case ProgressionActivatedLicenseType.BASIC_LIBRARY_LICENSE : { items.push( item = new ContextMenuItem( "Built on " + Progression.NAME + " " + Progression.VERSION.majorVersion, false ) ); item.addEventListener( ContextMenuEvent.MENU_ITEM_SELECT, _menuSelectBuiltOn, false, int.MAX_VALUE, true ); break; } } // 先頭の要素のセパレータを有効化する if ( customItems.length > 0 ) { ContextMenuItem( items[0] ).separatorBefore = true; } // カスタムメニューを追加する var l:int = Math.min( _customItems.length, 15 - items.length ); for ( var i:int = 0; i < l; i++ ) { items.unshift( _customItems[l - i - 1] ); } } /** * ユーザーがコンテキストメニューからアイテムを選択したときに送出されます。 */ private function _menuSelectBuiltOn( e:ContextMenuEvent ):void { navigateToURL( new URLRequest( "http://progression.jp/built_on/" ), "http://progression.jp/built_on/" ); }
[ "niumjp@afee6dea-b6cd-11dd-893d-d98698f66bbf" ]
[ [ [ 1, 118 ] ] ]
e210a4dbf8fc484b807f925f76184121baf8222b
2e3518a5507a35efafa32d5c14f990a2ba8efc64
/Utilities.h
61d89d4028f1d4c279003ef8a9b5c942cebbf159
[]
no_license
alur/AlbumArt
8ea5383c565e198293ad31c0722f79d193ba872d
d8e429a1621b0b4f1865964c3eca6c5683d52b05
refs/heads/master
2020-12-24T13:36:26.791806
2011-01-17T07:19:49
2011-01-17T07:19:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
534
h
#ifndef UTILITIES_H #define UTILITIES_H #include <windows.h> namespace Utilities { typedef struct extendedFileInfoStruct { LPCSTR filename; LPCSTR metadata; LPSTR ret; size_t retlen; } extendedFileInfoStruct; bool GetExtendedWinampFileInfo(LPCSTR pszFile, LPCSTR pszField, LPSTR pszOut, UINT cchLength); void URLEncode(LPCSTR pszString, LPSTR pszEncoded, UINT cchLength); bool File_Exists (LPCSTR pszFilePath); UCHAR StringToParseType(LPCSTR szParse); bool String2Bool(LPCSTR pszBool); } #endif
[ [ [ 1, 22 ] ] ]
38c8ea982427f8593178fe499c545c12a841542a
6581dacb25182f7f5d7afb39975dc622914defc7
/easyMule/easyMule/src/UILayer/Commands/CmdGotoPage.h
1d001decb849d93f906dee58281790dc4ecf9762
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
h
/* * $Id: CmdGotoPage.h 4483 2008-01-02 09:19:06Z soarchin $ * * this file is part of easyMule * Copyright (C)2002-2008 VeryCD Dev Team ( strEmail.Format("%s@%s", "emuledev", "verycd.com") / http: * www.easymule.org ) * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #pragma once class CCmdGotoPage { public: CCmdGotoPage(void); ~CCmdGotoPage(void); void GotoDownloading(void); };
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 30 ] ] ]
f5b26c51766c261eb0a27508f5bb6e06b4fa8c59
8bbbcc2bd210d5608613c5c591a4c0025ac1f06b
/nes/mapper/180.cpp
858ca909780485bc955765a938e54a89ca0477a8
[]
no_license
PSP-Archive/NesterJ-takka
140786083b1676aaf91d608882e5f3aaa4d2c53d
41c90388a777c63c731beb185e924820ffd05f93
refs/heads/master
2023-04-16T11:36:56.127438
2008-12-07T01:39:17
2008-12-07T01:39:17
357,617,280
1
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
#ifdef _NES_MAPPER_CPP_ ///////////////////////////////////////////////////////////////////// // Mapper 180 void NES_mapper180_Init() { g_NESmapper.Reset = NES_mapper180_Reset; g_NESmapper.MemoryWrite = NES_mapper180_MemoryWrite; } void NES_mapper180_Reset() { // set CPU bank pointers g_NESmapper.set_CPU_banks4(0,1,2,3); // set PPU bank pointers if(g_NESmapper.num_1k_VROM_banks) { g_NESmapper.set_PPU_banks8(0,1,2,3,4,5,6,7); } if(NES_crc32() == 0xc68363f6) // Crazy Climber { g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ); } } void NES_mapper180_MemoryWrite(uint32 addr, uint8 data) { g_NESmapper.set_CPU_bank6((data & 0x07)*2+0); g_NESmapper.set_CPU_bank7((data & 0x07)*2+1); } ///////////////////////////////////////////////////////////////////// #endif
[ "takka@e750ed6d-7236-0410-a570-cc313d6b6496" ]
[ [ [ 1, 35 ] ] ]
dfb607d4f8612d32fe9d3cae44eaa8750e157535
2ff4099407bd04ffc49489f22bd62996ad0d0edd
/Project/Code/inc/SShapedCurveToneMapper.h
29bfb871140e138438cf98eb4ab44d7fe76ef416
[]
no_license
willemfrishert/imagebasedrendering
13687840a8e5b37a38cc91c3c5b8135f9c1881f2
1cb9ed13b820b791a0aa2c80564dc33fefdc47a2
refs/heads/master
2016-09-10T15:23:42.506289
2007-06-04T11:52:13
2007-06-04T11:52:13
32,184,690
0
1
null
null
null
null
UTF-8
C++
false
false
1,510
h
#pragma once // forward declarations class ShaderObject; class ShaderProgram; template <class T> class ShaderUniformValue; class GPUParallelReductor; class SShapedCurveToneMapper { public: SShapedCurveToneMapper(GLuint aOriginalTexture, GLuint aLuminanceTexture, int aWidth, int aHeight); ~SShapedCurveToneMapper(void); void toneMap(GLuint aOriginalTexture, GLuint aLuminanceTexture); void setExposure(float aValue); float getExposure(); void InvalidateExposure(); // methods private: void enableMultitexturing(GLuint aOriginalTexture, GLuint aLuminanceTexture); void disableMultitexturing(); void renderSceneOnQuad(GLuint aOriginalTexture, GLuint aLuminanceTexture); void setupTexture(GLuint textureId); void initShaders( string fragmentShaderFilename ); float computeCurrentExposure(float aLogLAverage, float aLogLMin, float aLogLMax); // attributes private: GLuint iOriginalTexture; GLuint iLuminanceTexture; int iWidth; int iHeight; // shader stuff ShaderProgram* iShaderProgram; ShaderObject* iFragmentShader; ShaderUniformValue<int>* iOriginalTextureUniform; ShaderUniformValue<int>* iLuminanceTextureUniform; ShaderUniformValue<float>* iLogAverageUniform; ShaderUniformValue<float>* iExposureUniform; ShaderUniformValue<float>* iSensitivityUniform; // Parallel reduction GPUParallelReductor* iLogAverageCalculator; // Exposure settings float iPreviousExposure; bool iInvalidateExposure; };
[ "jpjorge@15324175-3028-0410-9899-2d1205849c9d" ]
[ [ [ 1, 62 ] ] ]
723fc3dad7e6cf5e4c635c6f2d4bffc41214da18
de98f880e307627d5ce93dcad1397bd4813751dd
/3libs/ut/include/COPYTREE.h
ca327049ccacd3bdaffd99dbd27251755c0b6b12
[]
no_license
weimingtom/sls
7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8
d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd
refs/heads/master
2021-01-10T22:20:55.638757
2011-03-19T06:23:49
2011-03-19T06:23:49
44,464,621
2
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,675
h
// ========================================================================== // Class Specification : COXCopyTree // ========================================================================== // Header file : copytree.h // Version: 9.3 // This software along with its related components, documentation and files ("The Libraries") // is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is // governed by a software license agreement ("Agreement"). Copies of the Agreement are // available at The Code Project (www.codeproject.com), as part of the package you downloaded // to obtain this file, or directly from our office. For a copy of the license governing // this software, you may contact us at [email protected], or by calling 416-849-8900. // ////////////////////////////////////////////////////////////////////////// // Properties: // NO Abstract class (does not have any objects) // YES Derived from CObject // NO Is a Cwnd. // NO Two stage creation (constructor & Create()) // NO Has a message map // NO Needs a resource (template) // NO Persistent objects (saveable on disk) // NO Uses exceptions // ////////////////////////////////////////////////////////////////////////// // Desciption : // This class allows the copying of the contents of one directory to another // Remark: // // Prerequisites (necessary conditions): // ///////////////////////////////////////////////////////////////////////////// #ifndef __COPYTREE_H__ #define __COPYTREE_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "OXDllExt.h" #include "path.h" #include "dstrlist.h" class OX_CLASS_DECL COXCopyTree : public CObject { DECLARE_DYNAMIC(COXCopyTree) // Data members ------------------------------------------------------------- public: protected: COXDoubleStringList m_dsFiles; // Files created during copy process COXDoubleStringList m_dsDirs; // Dirs created during copy process short m_nStatus; // Status of the copy process COXDirSpec m_SourceDir; COXDirSpec m_DestDir; COXDirSpec m_BufferDir; COXPathSpec m_SourcePath; COXPathSpec m_DestPath; COXCopyStatusDialog* m_pCpyStatDlg; private: HCURSOR m_hCursor; // Member functions --------------------------------------------------------- public: COXCopyTree(); // --- In : // --- Out : // --- Returns : // --- Effect : Contructor of object // It will initialize the internal state BOOL DoCopyTree(COXDirSpec SourceDir, COXDirSpec DestDir, BOOL bOnlyContents = TRUE, BOOL bCleanUp = FALSE,COXCopyStatusDialog* pCpyStatDlg = NULL); // --- In : SourceDir : the directory to copy the contents from // DestDir : the directory to copy the contents to // bOnlyContents : whether to copy the name of the source directory first // pCpyStatDlg : pointer to Status dlg. MUST ONLY BE ALLOCATED(new) AND // NOT YET CREATED!!!!! // --- Out : // --- Returns : suceeded or not // --- Effect : copies the contents of one directory to another void WalkTree(WORD wLevel); // --- Input : wLevel : bookmark, when wLevel is greater than 0, then the // current working directory is a subdirectory of the original // directory. If wLevel is equal to 0, then the directory is the // original directory and the recursive calls stop // --- Out : // --- Returns : // --- Effect : finds a subdirectory in the current working directory, // changes the current working directory to this subdirectory, // and recusively calls itself until there are no more // subdirectories void CleanUp(); // --- In : // --- Out : // --- Returns : // --- Effect : clean up the dirs and files double list and check for // required removal of files based on status. void SetHourGlass(); // --- In : // --- Out : // --- Returns : // --- Effect : Set an hourglass cursor void SetArrow(); // --- In : // --- Out : // --- Returns : // --- Effect : Set an arrow cursor #ifdef _DEBUG virtual void Dump(CDumpContext&) const; virtual void AssertValid() const; #endif //_DEBUG virtual ~COXCopyTree(); // --- In : // --- Out : // --- Returns : // --- Effect : Destructor of object protected: private: }; #endif // ==========================================================================
[ [ [ 1, 150 ] ] ]
a98422e3fdd89e3945908a8a8b8fc4072517f6e5
51e4aeb0d5e29ae1e8a9d8cf467797da2054b0f1
/src/shipView.hpp
99253662a33901f7b4c3721ab8f655a6116f5a9e
[]
no_license
vashero/tachyon-game
b3340272ee58c11077eef077485f8a01e4c81881
5fc2daac314c0b3b19b7336f8eb29d81a5e05729
refs/heads/master
2016-09-09T23:47:14.315285
2009-05-10T17:47:53
2009-05-10T17:47:53
32,647,791
0
0
null
null
null
null
UTF-8
C++
false
false
1,753
hpp
/*============================================================== * Copyright (c) 2009 Blake Fisher. All Rights Reserved. * * This software is released under the BSD License * <http://www.opensource.org/licenses/bsd-license.php> *============================================================== */ #pragma once #include <Ogre.h> using namespace Ogre; class ShipViewManager; /** Different ship types */ typedef enum { SHIP_VIEW_CRUISER, SHIP_VIEW_SUPERIORITY, SHIP_VIEW_NONE /**< Used to count the number of ship views; must always be the final enum */ } ShipViewType; const String SHIP_VIEW_TYPE_NAMES[] = {"Cruiser", "Superiority"}; /** Handles the appearance of a ship. */ class ShipView { public: // Methods -------------------- /** The default constructor @param type The type of ship to create @param sceneMgr The scene manager to add the ship to */ ShipView(ShipViewType type, SceneManager *sceneMgr, ShipViewManager *shipViewMgr, Vector3 pos, Radian yaw); /** The destructor */ ~ShipView(); /** Create the relevant ogre objects for this ship @param sceneMgr The scene manager to add this ship to @param pos The initial position of the ship @param rot The initial rotation of the ship */ void initialize(SceneManager *sceneMgr, Vector3 pos, Radian yaw); /** Remove this ship from the scene */ void destroy(); private: /** The node holding our ship */ SceneNode *mShipNode; /** Used to get static ship information */ ShipViewManager *mShipViewMgr; /** Used to identify ourselves with our ship manager */ int mId; /** The scene manager we add ourselves to */ SceneManager *mSceneMgr; };
[ "[email protected]@b90cb52e-2f47-11de-8816-6191455234fe" ]
[ [ [ 1, 64 ] ] ]
e9b342a975ef2efd1a5e3d2e577e89efe844670b
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/stdlith/lithexception.cpp
35025734d6a26bcc4817767336b70d342ae9cc96
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
//------------------------------------------------------------------ // // FILE : LithException.cpp // // PURPOSE : // // CREATED : February 9 1997 // // COPYRIGHT : Microsoft 1996 All Rights Reserved // //------------------------------------------------------------------ // Includes.... #include "lithexception.h" int g_LithExceptionType=LITH_EXCEPTION;
[ [ [ 1, 17 ] ] ]
318a6c80d6c9924c824e99554f93dd293c32e75f
611fc0940b78862ca89de79a8bbeab991f5f471a
/src/Settings/Settings.cpp
c71c0fdf647da35fb1d55626038fd3c029d6c6cb
[]
no_license
LakeIshikawa/splstage2
df1d8f59319a4e8d9375b9d3379c3548bc520f44
b4bf7caadf940773a977edd0de8edc610cd2f736
refs/heads/master
2021-01-10T21:16:45.430981
2010-01-29T08:57:34
2010-01-29T08:57:34
37,068,575
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,166
cpp
#include "Settings.h" #include "EntryFloat.h" #include "EntryString.h" #include "Entry.h" #include "windows.h" #include <iostream> #include <fstream> #include <string> using namespace std; Settings::Settings() {} Settings::~Settings() {} /* 設定ファイルをパース */ int Settings::ParseSettings(string rFName) { ifstream set_file( rFName.c_str() ); if( !set_file.is_open() ) return 1; // ファイル未発見 string line; // 行バッファー // 読み込み while( getline( set_file, line ) ){ if( (line.length() > 1 && line.substr( 0, 2 ).compare("//") == 0) || line.compare("") == 0) continue; char* tokp = strtok( (char*)line.c_str(), "{ :" ); string key = tokp; tokp = strtok( NULL, ": }"); string entry = tokp; Entry* ent; if( entry.substr(0, 1).compare("\"") == 0 ){ //文字列 ent = new EntryString(entry.substr(1, entry.length()-2)); } else{ //フロート int base = entry.substr(0, 2).compare("0x") == 0?16:10; if( base == 16 ){ ent = new EntryFloat(strtol(entry.c_str(), NULL, base)); } else{ ent = new EntryFloat(atof(entry.c_str())); } } lstSets.insert(pair<string, Entry*>(key, ent)); continue; }// while set_file.close(); return 0; } /* フロートを取得 */ float Settings::GetFloat(string key) { stdext::hash_map<string, Entry*>::iterator fnd = lstSets.find(key); if( fnd == lstSets.end() ){ char err[200] = "致命的なエラー:設定項目未発見:"; strcat(err, key.c_str()); MessageBox(NULL, err, "エラー", MB_OK); exit(1); } EntryFloat* flt = static_cast<EntryFloat*>(fnd->second); return flt->GetFloat(); } /* 文字列を取得 */ string Settings::GetString(string key) { stdext::hash_map<string, Entry*>::iterator fnd = lstSets.find(key); if( fnd == lstSets.end() ){ char err[200] = "致命的なエラー:設定項目未発見:"; strcat(err, key.c_str()); MessageBox(NULL, err, "エラー", MB_OK); exit(1); } EntryString* str = static_cast<EntryString*>(fnd->second); return str->GetString(); }
[ "lakeishikawa@c9935178-01ba-11df-8f7b-bfe16de6f99b" ]
[ [ [ 1, 98 ] ] ]
629039085b9f457de418534059af913955cc7d10
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/examples/Castles/include/Network.h
407b103aa6f5dae647beeb16951ac27f0f20c67d
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
9,796
h
#ifndef SLON_ENGINE_CASTLES_NETWORK_H #define SLON_ENGINE_CASTLES_NETWORK_H #include <sgl/math/Matrix.hpp> #include <iostream> #include <boost/array.hpp> #include <boost/asio.hpp> namespace net { using boost::asio::ip::tcp; namespace asio = boost::asio; /// port for the game static const int castles_port = 6882; static const char* castles_service = "6882"; /// synchronization primitive static const int sync_stamp = 0xBB00; inline void read_string(tcp::socket& socket, std::string& str) { size_t size; asio::read( socket, asio::buffer( &size, sizeof(size_t) ) ); str.resize(size); asio::read( socket, asio::buffer( &str[0], str.size() ) ); } inline void write_string(tcp::socket& socket, const std::string& str) { size_t size = str.size(); asio::write( socket, asio::buffer( &size, sizeof(size_t) ) ); asio::write( socket, asio::buffer( str.data(), str.size() ) ); } template<class POD_T> std::string make_message(POD_T value) { std::string result; result.resize( sizeof(POD_T) ); memcpy( &result[0], &value, sizeof(POD_T) ); return result; } inline std::string make_message(const std::string& str) { std::string result; result.resize( str.size() + sizeof(size_t) ); size_t size = str.size(); memcpy( &result[0], &size, sizeof(size_t) ); memcpy( &result[sizeof(size_t)], &str[0], str.size() ); return result; } inline int read_header(tcp::socket& socket) { int value; asio::read( socket, asio::buffer(&value, sizeof(int)) ); return value; } inline void read_sync_stamp(tcp::socket& socket) { int value; asio::read( socket, asio::buffer(&value, sizeof(int)) ); if ( value != sync_stamp ) { throw std::runtime_error("Received invalid synchronization stamp"); } } inline void write_sync_stamp(tcp::socket& socket) { asio::write( socket, asio::buffer(&sync_stamp, sizeof(int)) ); } /** struct to transfer mesh desc */ struct object_desc { static const int header = 0xAA01; int id; bool clone; std::string nodeName; sgl::math::Matrix4f matrix; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); buffer += make_message(clone); buffer += make_message(nodeName); buffer += make_message(matrix); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); asio::write( socket, asio::buffer( &clone, sizeof(bool) ) ); write_string(socket, nodeName); asio::write( socket, asio::buffer( &matrix, sizeof(gmath::Matrix4f) ) ); return sizeof(object_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &id, sizeof(int) ) ); asio::read( socket, asio::buffer( &clone, sizeof(bool) ) ); read_string(socket, nodeName); asio::read( socket, asio::buffer( &matrix, sizeof(gmath::Matrix4f) ) ); return sizeof(object_desc); } }; /** struct to transfer mesh desc */ struct mesh_desc { static const int header = 0xAA02; std::string fileName; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(fileName); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); write_string(socket, fileName); return sizeof(mesh_desc) + sizeof(header); } size_t read(tcp::socket& socket) { read_string(socket, fileName); return sizeof(mesh_desc); } }; /** struct to transfer skyBox desc */ struct sky_box_desc { static const int header = 0xAA03; std::string maps[6]; std::string message() const { std::string buffer; buffer += make_message(header); for(int i = 0; i<6; ++i) { buffer += make_message(maps[i]); } return buffer; } size_t write(tcp::socket& socket) { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); size_t size = sizeof(header); for(int i = 0; i<6; ++i) { write_string(socket, maps[i]); size += maps[i].size(); } return size; } size_t read(tcp::socket& socket) { size_t size = 0; for(int i = 0; i<6; ++i) { read_string(socket, maps[i]); size += maps[i].size(); } return size; } }; /** struct to transfer object transform */ struct object_transform_desc { static const int header = 0xAA04; int id; gmath::Matrix4f matrix; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); buffer += make_message(matrix); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); asio::write( socket, asio::buffer( &matrix, sizeof(gmath::Matrix4f) ) ); return sizeof(object_transform_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &id, sizeof(int) ) ); asio::read( socket, asio::buffer( &matrix, sizeof(gmath::Matrix4f) ) ); return sizeof(object_transform_desc); } }; /** struct to transfer player state */ struct player_state_desc { static const int header = 0xAA06; enum action { CREATE, READY, LOOSE, TURN, WIN, EXIT }; int id; action state; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); buffer += make_message(state); return buffer; } size_t write(tcp::socket& socket) { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); asio::write( socket, asio::buffer( &state, sizeof(action) ) ); return sizeof(player_state_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &id, sizeof(int) ) ); asio::read( socket, asio::buffer( &state, sizeof(action) ) ); return sizeof(player_state_desc); } }; /** struct to transfer player health */ struct player_damage_desc { static const int header = 0xAA0A; int id; int health; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); buffer += make_message(health); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); asio::write( socket, asio::buffer( &health, sizeof(int) ) ); return sizeof(player_damage_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer(&id, sizeof(int)) ); asio::read( socket, asio::buffer(&health, sizeof(int)) ); return sizeof(player_damage_desc); } }; /** struct to transfer canon desc */ struct canon_desc { static const int header = 0xAA07; int id; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); return sizeof(canon_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &id, sizeof(int) ) ); return sizeof(canon_desc); } }; /** struct to transfer kernel desc */ struct kernel_desc { static const int header = 0xAA08; int id; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(id); return buffer; } size_t write(tcp::socket& socket) const { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &id, sizeof(int) ) ); return sizeof(kernel_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &id, sizeof(int) ) ); return sizeof(kernel_desc); } }; /** struct to transfer canon firing */ struct fire_canon_desc { static const int header = 0xAA0B; int playerId; float impulse; std::string message() const { std::string buffer; buffer += make_message(header); buffer += make_message(playerId); buffer += make_message(impulse); return buffer; } size_t write(tcp::socket& socket) { asio::write( socket, asio::buffer( &header, sizeof(int) ) ); asio::write( socket, asio::buffer( &playerId, sizeof(int) ) ); asio::write( socket, asio::buffer( &impulse, sizeof(float) ) ); return sizeof(fire_canon_desc) + sizeof(header); } size_t read(tcp::socket& socket) { asio::read( socket, asio::buffer( &playerId, sizeof(int) ) ); asio::read( socket, asio::buffer( &impulse, sizeof(float) ) ); return sizeof(fire_canon_desc); } }; } // namespace net #endif // SLON_ENGINE_CASTLES_NETWORK_H
[ "devnull@localhost" ]
[ [ [ 1, 390 ] ] ]
4befec0a0526a2a8d973f1e17ee5e2a3f47f2c19
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/DOMInputSource.hpp
d99f567398977111899d208091aa08d2d791ccc9
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
9,893
hpp
#ifndef DOMInputSource_HEADER_GUARD_ #define DOMInputSource_HEADER_GUARD_ /* * Copyright 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMInputSource.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN class BinInputStream; /** * This interface represents a single input source for an XML entity. * * <p>This interface allows an application to encapsulate information about * an input source in a single object, which may include a public identifier, * a system identifier, a byte stream (possibly with a specified encoding), * and/or a character stream.</p> * * <p>There are two places that the application will deliver this input source * to the parser: as the argument to the parse method, or as the return value * of the DOMEntityResolver.resolveEntity method.</p> * * <p>The DOMBuilder will use the DOMInputSource object to determine how to * read XML input. If there is a character stream available, the parser will * read that stream directly; if not, the parser will use a byte stream, if * available; if neither a character stream nor a byte stream is available, * the parser will attempt to open a URI connection to the resource identified * by the system identifier.</p> * * <p>A DOMInputSource object belongs to the application: the parser shall * never modify it in any way (it may modify a copy if necessary).</p> * * @see DOMBuilder#parse * @see DOMEntityResolver#resolveEntity * @since DOM Level 3 */ class CDOM_EXPORT DOMInputSource { protected: // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Hidden constructors */ //@{ DOMInputSource() {}; //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- /** @name Unimplemented constructors and operators */ //@{ DOMInputSource(const DOMInputSource &); DOMInputSource & operator = (const DOMInputSource &); //@} public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~DOMInputSource() {}; //@} // ----------------------------------------------------------------------- // Virtual DOMInputSource interface // ----------------------------------------------------------------------- /** @name Functions introduced in DOM Level 3 */ //@{ // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- /** * An input source can be set to force the parser to assume a particular * encoding for the data that input source reprsents, via the setEncoding() * method. This method returns name of the encoding that is to be forced. * If the encoding has never been forced, it returns a null pointer. * * <p><b>"Experimental - subject to change"</b></p> * * @return The forced encoding, or null if none was supplied. * @see #setEncoding * @since DOM Level 3 */ virtual const XMLCh* getEncoding() const = 0; /** * Get the public identifier for this input source. * * <p><b>"Experimental - subject to change"</b></p> * * @return The public identifier, or null if none was supplied. * @see #setPublicId * @since DOM Level 3 */ virtual const XMLCh* getPublicId() const = 0; /** * Get the system identifier for this input source. * * <p><b>"Experimental - subject to change"</b></p> * * <p>If the system ID is a URL, it will be fully resolved.</p> * * @return The system identifier. * @see #setSystemId * @since DOM Level 3 */ virtual const XMLCh* getSystemId() const = 0; /** * Get the base URI to be used for resolving relative URIs to absolute * URIs. If the baseURI is itself a relative URI, the behavior is * implementation dependent. * * <p><b>"Experimental - subject to change"</b></p> * * @return The base URI. * @see #setBaseURI * @since DOM Level 3 */ virtual const XMLCh* getBaseURI() const = 0; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- /** * Set the encoding which will be required for use with the XML text read * via a stream opened by this input source. * * <p>This is usually not set, allowing the encoding to be sensed in the * usual XML way. However, in some cases, the encoding in the file is known * to be incorrect because of intermediate transcoding, for instance * encapsulation within a MIME document. * * <p><b>"Experimental - subject to change"</b></p> * * @param encodingStr The name of the encoding to force. * @since DOM Level 3 */ virtual void setEncoding(const XMLCh* const encodingStr) = 0; /** * Set the public identifier for this input source. * * <p>The public identifier is always optional: if the application writer * includes one, it will be provided as part of the location information.</p> * * <p><b>"Experimental - subject to change"</b></p> * * @param publicId The public identifier as a string. * @see #getPublicId * @since DOM Level 3 */ virtual void setPublicId(const XMLCh* const publicId) = 0; /** * Set the system identifier for this input source. * * <p>The system id is always required. The public id may be used to map * to another system id, but the system id must always be present as a fall * back.</p> * * <p>If the system ID is a URL, it must be fully resolved.</p> * * <p><b>"Experimental - subject to change"</b></p> * * @param systemId The system identifier as a string. * @see #getSystemId * @since DOM Level 3 */ virtual void setSystemId(const XMLCh* const systemId) = 0; /** * Set the base URI to be used for resolving relative URIs to absolute * URIs. If the baseURI is itself a relative URI, the behavior is * implementation dependent. * * <p><b>"Experimental - subject to change"</b></p> * * @param baseURI The base URI. * @see #getBaseURI * @since DOM Level 3 */ virtual void setBaseURI(const XMLCh* const baseURI) = 0; //@} // ----------------------------------------------------------------------- // Non-standard Extension // ----------------------------------------------------------------------- /** @name Non-standard Extension */ //@{ /** * Makes the byte stream for this input source. * * <p>The derived class must create and return a binary input stream of an * appropriate type for its kind of data source. The returned stream must * be dynamically allocated and becomes the parser's property. * </p> * * <p><b>"Experimental - subject to change"</b></p> * * @see BinInputStream */ virtual BinInputStream* makeStream() const = 0; /** * Indicates if the parser should issue fatal error if this input source * is not found. If set to false, the parser issue warning message instead. * * <p><b>"Experimental - subject to change"</b></p> * * @param flag True if the parser should issue fatal error if this input source is not found. * If set to false, the parser issue warning message instead. (Default: true) * * @see #getIssueFatalErrorIfNotFound */ virtual void setIssueFatalErrorIfNotFound(const bool flag) = 0; /** * Get the flag that indicates if the parser should issue fatal error if this input source * is not found. * * <p><b>"Experimental - subject to change"</b></p> * * @return True if the parser should issue fatal error if this input source is not found. * False if the parser issue warning message instead. * @see #setIssueFatalErrorIfNotFound */ virtual bool getIssueFatalErrorIfNotFound() const = 0; /** * Called to indicate that this DOMInputSource is no longer in use * and that the implementation may relinquish any resources associated with it. * * Access to a released object will lead to unexpected result. */ virtual void release() = 0; //@} }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 279 ] ] ]
db82ce4177440c7872f029ec1d5cb8dbd8a5f11c
fbe2cbeb947664ba278ba30ce713810676a2c412
/iptv_root/iptv_kernel/include/iptv_kernel/IrmQueryNotify.h
3dda5ef8486d51f5a1eca43119c68eba008de077
[]
no_license
abhipr1/multitv
0b3b863bfb61b83c30053b15688b070d4149ca0b
6a93bf9122ddbcc1971dead3ab3be8faea5e53d8
refs/heads/master
2020-12-24T15:13:44.511555
2009-06-04T17:11:02
2009-06-04T17:11:02
41,107,043
0
0
null
null
null
null
UTF-8
C++
false
false
6,845
h
#ifndef IRM_QUERY_NOTIFY_H #define IRM_QUERY_NOTIFY_H #include "VBLib/VBLib.h" #include "iptv_kernel/IrmMessage.h" #include "iptv_kernel/IrmUser.h" #include "iptv_kernel/IrmConnection.h" enum IrmQueryNotifyCode { IQNC_INVALID_CODE, IQNC_IRM_MESSAGE, // Parameter class: IrmQueryIrmMessageParam IQNC_CONNECTED_HOST, // Parameter class: IrmQueryParam IQNC_CONNECTED_CHAT, // Parameter class: IrmQueryParam IQNC_DISCONNECTED, // Parameter class: IrmQueryParam IQNC_UDP_CONNECTION_AVAILABLE, // Parameter class: IrmQueryParam IQNC_AUTHENTICATED, // Parameter class: IrmQueryParam IQNC_AUTHENTICATION_REQUESTED, // Parameter class: IrmQueryParam IQNC_AUTHENTICATION_ERROR, // Parameter class: IrmQueryParam IQNC_USER_QUIT, // Parameter class: IrmQueryUserParam IQNC_CHANNEL_JOIN, // Parameter class: IrmQueryUserParam IQNC_CHANNEL_PART, // Parameter class: IrmQueryUserParam IQNC_CHANNEL_QUERY_ITEM, // Parameter class: IrmQueryChannelParam IQNC_CHANNEL_QUERY_END, // Parameter class: IrmQueryParam IQNC_CHANNEL_PASSWD_INVALID, // Parameter class: IrmQueryParam IQNC_USER_QUERY_ITEM, // Parameter class: IrmQueryUserParam IQNC_USER_QUERY_END, // Parameter class: IrmQueryChannelParam IQNC_PRIV_MSG, // Parameter class: IrmQueryMessageParam IQNC_CHANNEL_PRIV_MSG, // Parameter class: IrmQueryMessageParam IQNC_NEW_MEDIA_TRANSMISSION, // Parameter class: IrmQueryMediaParam IQNC_MEDIA_CONFERENCE_READY, // Parameter class: IrmQueryMediaParam IQNC_MEDIA_VIEWER_READY, // Parameter class: IrmQueryMediaParam IQNC_CHANNEL_VOICE, // Parameter class: IrmQueryUserParam IQNC_VOICE_REQUEST, // Parameter class: IrmQueryUserParam IQNC_VOICE_REQUEST_CANCEL, // Parameter class: IrmQueryUserParam IQNC_VOICE_REQUEST_REMOVE_ALL, // Parameter class: IrmQueryUserParam IQNC_CHANNEL_MODE_OPERATOR, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_PRIVATE, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_SECRET, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_INVITE_ONLY, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_OP_CHANGE_TOPIC, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_NO_EXTERNAL_MESSAGES, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_MODERATED, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_USER_LIMIT, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_BAN, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_MEDIA_COLLABORATOR, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_KEY, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_BIT_RATE, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_AUTO_CHANGE_BIT_RATE, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_MULTIPLE_TRANSMISSION, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_ONE_AUDIO, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_AUDIO_MUTE, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_BAND_SHARE_LIMIT, // Parameter class: IrmQueryModeParam IQNC_CHANNEL_MODE_TRANSMISSION_LIMIT, // Parameter class: IrmQueryModeParam IQNC_USER_MODE_INVISIBLE, // Parameter class: IrmQueryModeParam IQNC_USER_MODE_REGISTERED, // Parameter class: IrmQueryModeParam IQNC_USER_MODE_CAMERA_ON, // Parameter class: IrmQueryModeParam IQNC_USER_MODE_MIC_MUTE, // Parameter class: IrmQueryModeParam IQNC_USER_MODE_AWAY, // Parameter class: IrmQueryModeParam IQNC_ERROR_IRM_STUB_INIT, // Parameter class: IrmQueryParam IQNC_ERROR_CONN_STATE, // Parameter class: IrmQueryParam IQNC_ERROR_CONN_QUERY, // Parameter class: IrmQueryParam IQNC_ERROR_CONN_PARAM_BLANK, // Parameter class: IrmQueryParam IQNC_ERROR_VIEWER_PARAM_BLANK, // Parameter class: IrmQueryParam IQNC_ERROR_VIEWER_STATE, // Parameter class: IrmQueryParam IQNC_ERROR_VIEWER_INIT, // Parameter class: IrmQueryParam }; /** @brief Base structure to send an IRM Query notification. * */ struct IrmQueryParam { IrmQueryNotifyCode m_code; // Should be removed. The App shouldn't display this message as error information. br::com::sbVB::VBLib::VBString m_irmMessage; bool IsNotificationCodeValid(); }; /** @brief IRM Query notification structure. * */ struct IrmQueryIrmMessageParam : public IrmQueryParam { IrmMessage m_message; IrmUser m_user; IrmConnection m_connection; }; /** @brief IRM Query notification structure. * */ struct IrmQueryChannelParam : public IrmQueryParam { br::com::sbVB::VBLib::VBString m_channelName; br::com::sbVB::VBLib::VBString m_channelTopic; int m_userCount; }; /** @brief IRM Query notification structure. * */ struct IrmQueryUserParam : public IrmQueryParam { br::com::sbVB::VBLib::VBString m_userName; br::com::sbVB::VBLib::VBString m_channelName; }; /** @brief IRM Query notification structure. * */ struct IrmQueryMessageParam : public IrmQueryParam { br::com::sbVB::VBLib::VBString m_sender; br::com::sbVB::VBLib::VBString m_channelName; br::com::sbVB::VBLib::VBString m_message; }; /** @brief IRM Query notification structure. * */ struct IrmQueryModeParam : public IrmQueryParam { char m_name; bool m_value; br::com::sbVB::VBLib::VBString m_target; br::com::sbVB::VBLib::VBString m_parameter; }; /** @brief IRM Query notification structure. * */ struct IrmQueryMediaParam : public IrmQueryParam { unsigned m_mediaId; br::com::sbVB::VBLib::VBString m_userNickName; br::com::sbVB::VBLib::VBString m_channelName; br::com::sbVB::VBLib::VBString m_mediaClass; br::com::sbVB::VBLib::VBString m_netProtocol; br::com::sbVB::VBLib::VBString m_host; unsigned m_port; }; /** @brief Receives notifications from IRM Query. * * Any class that needs to receive IRM Query notifications should * be derived of this class. * */ class IrmQueryNotify { public: virtual void OnIrmQueryNotify(IrmQueryParam &param) = 0; }; #endif
[ "heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89" ]
[ [ [ 1, 162 ] ] ]
15e777ca5043926e733996a68ea647c7de36b46d
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteikbctrl/src/bctesteikbctrlapp.cpp
e808b3d7b037f32e01a11bf69f5a20d5b197e749
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
cpp
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Avkon eikbctrl test app * */ #include <eikstart.h> #include "BCTesteikbctrlApp.h" #include "BCTesteikbctrlDocument.h" // ================= MEMBER FUNCTIONS ========================================= // ---------------------------------------------------------------------------- // TUid CBCTesteikbctrlApp::AppDllUid() // Returns application UID. // ---------------------------------------------------------------------------- // TUid CBCTesteikbctrlApp::AppDllUid() const { return KUidBCTesteikbctrl; } // ---------------------------------------------------------------------------- // CApaDocument* CBCTesteikbctrlApp::CreateDocumentL() // Creates CBCTesteikbctrlDocument object. // ---------------------------------------------------------------------------- CApaDocument* CBCTesteikbctrlApp::CreateDocumentL() { return CBCTesteikbctrlDocument::NewL( *this ); } // ================= OTHER EXPORTED FUNCTIONS ================================= // // ---------------------------------------------------------------------------- // CApaApplication* NewApplication() // Constructs CBCTesteikbctrlApp. // Returns: CApaDocument*: created application object // ---------------------------------------------------------------------------- // LOCAL_C CApaApplication* NewApplication() { return new CBCTesteikbctrlApp; } GLDEF_C TInt E32Main() { return EikStart::RunApplication(NewApplication); } // End of File
[ "none@none" ]
[ [ [ 1, 65 ] ] ]
e5e3e1135d27aa263ba22db41f40f2c8efa85d5a
a6d5d811222889c750c786ef5487f9b49edb2de1
/motion/RST/GUI/RSTFrame.cpp
e3bb38a834edeb013eaecdc2db87b98ffa345dae
[]
no_license
oarslan3/gt-cs-rip-projects
1f29f979b5ca57f87cd154bfa1c88b93fb09ccb9
0b8f470679d5c107c7f10dbe9a67cdda392a9329
refs/heads/master
2021-01-10T05:50:57.921487
2009-12-13T16:48:49
2009-12-13T16:48:49
52,402,944
0
0
null
null
null
null
UTF-8
C++
false
false
18,870
cpp
//--------------------------------------------------------------------- // Copyright (c) 2009 Mike Stilman // All Rights Reserved. // // Permission to duplicate or use this software in whole or in part // is only granted by consultation with the author. // // Mike Stilman [email protected] // // Robotics and Intelligent Machines // Georgia Tech //-------------------------------------------------------------------- #include "GUI.h" #include "RSTFrame.h" #include "Viewer.h" #include "TreeView.h" #include "../Tabs/AllTabs.h" #include "../Tabs/RSTTab.h" #include "RSTSlider.h" #include "../Tools/World.h" #include "RSTimeSlice.h" #include "RSTFrame.h" #include "icons/open.xpm" #include "icons/save.xpm" #include "icons/redo.xpm" #include "icons/up.xpm" #include "icons/anchor.xpm" #include "icons/asterisk.xpm" #include "icons/camera.xpm" #include "icons/film.xpm" #include "icons/clock.xpm" #include <iostream> #include <fstream> using namespace std; #define ID_TOOLBAR 1257 #define ID_TIMESLIDER 1258 enum toolNums{ Tool_open= 1262, Tool_save= 1263, Tool_quickload = 1264, Tool_linkorder = 1265, Tool_checkcollisions = 1266, Tool_screenshot = 1267, Tool_movie = 1268 }; extern bool check_for_collisions; //wxSTD_MDIPARENTFRAME ICON wxICON(ROBOT_xpm) RSTFrame::RSTFrame(const wxString& title) : wxFrame(NULL, wxID_ANY, title) { tPrecision = 1000; tMax = 5; tMax = 0; InitTimer("",0); wxMenu *fileMenu = new wxMenu; wxMenu *helpMenu = new wxMenu; wxMenu *settingsMenu = new wxMenu; wxMenu *bgMenu = new wxMenu; //wxMenu *saveMenu = new wxMenu; fileMenu->Append(MenuLoad, wxT("L&oad\tAlt-O")); fileMenu->Append(MenuQuickLoad, wxT("Q&uickLoad\tAlt-Shift-Q")); fileMenu->Append(MenuSaveScene, wxT("Save Scene")); //saveMenu->Append(MenuSaveRobot, wxT("Save Robot")); //fileMenu->AppendSubMenu(saveMenu, wxT("S&ave\tAlt-S")); fileMenu->Append(MenuClose, wxT("C&lose\tAlt-C")); fileMenu->AppendSeparator(); fileMenu->Append(MenuQuit, wxT("E&xit\tAlt-Q")); bgMenu->Append(MenuBgWhite, wxT("White")); bgMenu->Append(MenuBgBlack, wxT("Black")); settingsMenu->AppendSubMenu(bgMenu, wxT("Background")); helpMenu->Append(MenuAbout, wxT("&About...\tF1"), wxT("Show about dialog")); wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(fileMenu, wxT("&File")); menuBar->Append(settingsMenu, wxT("&Settings")); menuBar->Append(helpMenu, wxT("&Help")); SetMenuBar(menuBar); toolBarBitmaps[0] = wxIcon(open_xpm); toolBarBitmaps[1] = wxIcon(save_xpm); toolBarBitmaps[2] = wxIcon(redo_xpm); toolBarBitmaps[3] = wxIcon(anchor_xpm); toolBarBitmaps[4] = wxIcon(asterisk_xpm); toolBarBitmaps[5] = wxIcon(camera_xpm); toolBarBitmaps[6] = wxIcon(film_xpm); wxBitmap clockBmp = wxBitmap(clock_xpm); filebar = new wxToolBar(this,ID_TOOLBAR,wxPoint(0, 0), wxSize(prefTreeViewWidth+50, toolBarHeight), wxTB_HORIZONTAL); filebar->SetToolBitmapSize(wxSize(16, 16)); filebar->AddTool(wxID_OPEN, _T("Open"),toolBarBitmaps[0], toolBarBitmaps[0], wxITEM_NORMAL, _T("Open .rscene file (Alt-O)")); filebar->AddTool(wxID_SAVE, _T("Save"),toolBarBitmaps[1], toolBarBitmaps[1], wxITEM_NORMAL, _T("Save world to .rscene file (Alt-S)")); filebar->AddSeparator(); filebar->AddTool(Tool_quickload, _T("Quick Load"),toolBarBitmaps[2], toolBarBitmaps[2], wxITEM_NORMAL, _T("Load last viewed scene (Alt-Shift-Q)")); filebar->AddSeparator(); filebar->AddTool(Tool_screenshot, _T("Screenshot"),toolBarBitmaps[5], toolBarBitmaps[5], wxITEM_NORMAL, _T("Export screenshot")); filebar->AddTool(Tool_movie, _T("Movie"),toolBarBitmaps[6], toolBarBitmaps[6], wxITEM_NORMAL, _T("Export film sequence")); //timeSlider = new RSTSlider(clockBmp,0,1000,100,0,100,500,this,ID_TIMESLIDER,true); wxPanel* timePanel = new wxPanel(this, -1, wxDefaultPosition, wxDefaultSize, 0); #ifdef WIN32 // For windows use a thicker slider - it looks nice timeTrack = new wxSlider(timePanel,1009,0,0,1000,wxDefaultPosition, wxSize(30,100), wxSL_BOTH | wxSL_VERTICAL | wxALIGN_CENTRE); #else timeTrack = new wxSlider(timePanel,1009,0,0,1000,wxDefaultPosition, wxSize(16,100), wxSL_BOTH | wxSL_VERTICAL | wxALIGN_CENTRE); #endif wxStaticBitmap *timeButton = new wxStaticBitmap(timePanel, -1, clockBmp, wxDefaultPosition, wxSize(16,16), wxALIGN_CENTRE); wxSizer *sizerTime = new wxBoxSizer(wxVERTICAL); sizerTime->Add(timeButton,0 , wxALIGN_CENTRE | wxEXPAND | wxALL, 2); sizerTime->Add(timeTrack,1 , wxALIGN_CENTRE | wxEXPAND | wxALL, 2); optionbar = new wxToolBar(this,ID_TOOLBAR,wxPoint(0, 0), wxSize(prefTreeViewWidth, toolBarHeight), wxTB_HORIZONTAL); wxBitmap optionBarBitmaps[2]; optionbar->SetToolBitmapSize(wxSize(16, 16)); optionbar->AddTool(Tool_linkorder, _T("Link Order"),toolBarBitmaps[3], toolBarBitmaps[3], wxITEM_CHECK, _T("Fix link position")); optionbar->AddTool(Tool_checkcollisions, _T("Check Collisions"),toolBarBitmaps[4], toolBarBitmaps[4], wxITEM_CHECK, _T("Click to toggle collision detection")); timeText = new wxTextCtrl(optionbar,1008,wxT(" 0.00"),wxDefaultPosition,wxSize(50,20),wxTE_PROCESS_ENTER | wxTE_RIGHT); optionbar->AddSeparator(); optionbar->AddControl(timeText); CreateStatusBar(2); SetStatusText(wxT("RST Loading...")); // Create sizers - these will manage the layout/resizing of the frame elements wxSizer *sizerFull = new wxBoxSizer(wxVERTICAL); wxSizer *sizerTop = new wxBoxSizer(wxHORIZONTAL); wxSizer *sizerRight = new wxBoxSizer(wxVERTICAL); wxSizer *sizerRightH = new wxBoxSizer(wxHORIZONTAL); wxSizer *sizerBottom = new wxBoxSizer(wxHORIZONTAL); treeView = new TreeView(this, TreeViewHandle, wxPoint(0, 0), wxSize(prefTreeViewWidth, prefViewerHeight-2*toolBarHeight), wxTR_LINES_AT_ROOT | wxTR_HAS_BUTTONS | wxTR_HIDE_ROOT | wxSUNKEN_BORDER); // Adding a backPanel to the lower half of the window covers the generic "inner grey" // with a forms-like control color. The tabView is added to the backPanel backPanel = new wxPanel(this, -1, wxDefaultPosition, wxDefaultSize, 0); tabView = new wxNotebook(backPanel, wxID_ANY, wxPoint(0, 0), wxSize(prefTreeViewWidth+prefViewerWidth, prefTabsHeight), wxNB_NOPAGETHEME | wxNB_TOP); addAllTabs(); // Start OpenGL and do various hacks to make it work cross platform #ifndef WIN32 // Weird hack to make wxWidgets work in Linux Show(); #endif viewer = new Viewer(this, -1, wxPoint(0, 0), wxSize(prefViewerWidth, prefViewerHeight), wxFULL_REPAINT_ON_RESIZE | wxSUNKEN_BORDER); #ifdef WIN32 // Weird hack to make wxWidgets work with VC++ debug viewer->MSWSetOldWndProc((WXFARPROC)DefWindowProc); #endif // Add elements to the sizers, setting the proportion flag to 1 and using the // wxEXPAND flag to ensure that the Viewer fills the entire sizer (subject to constraints) sizerFull->Add(sizerTop, 1, wxEXPAND | wxALL, 0 ); sizerTop->Add(viewer, 1, wxALIGN_LEFT | wxEXPAND | wxALL, 0); // Set the proportion flag to 0 (for wxHORIZONTAL sizer) to fix the width to its minimal size sizerTop->Add(sizerRight, 0, wxALIGN_RIGHT | wxEXPAND | wxALL, 0); sizerRight->Add(filebar,0, wxALL, 0); sizerRight->Add(sizerRightH, 1 , wxEXPAND | wxALL, 0); sizerRight->Add(optionbar,0, wxALIGN_LEFT | wxEXPAND | wxALL, 0); sizerRightH->Add((wxTreeCtrl*)treeView, 1, wxALIGN_CENTRE | wxALL | wxEXPAND, 0); sizerRightH->Add(timePanel,0, wxALIGN_LEFT | wxEXPAND | wxALL, 0); // Place the back panel on the lower part of the window (0 fixes the height for wxVERTICAL sizer) sizerFull->Add(backPanel, 0, wxEXPAND | wxALL, 0); // Add another sizer to stretch the tabs over the back panel while keeping a 3 pixel border sizerBottom->Add(tabView, 1, wxALIGN_LEFT | wxEXPAND | wxALL, 3); backPanel->SetSizer(sizerBottom); timePanel->SetSizer(sizerTime); SetSizer(sizerFull); sizerFull->SetSizeHints( this ); filebar->Realize(); optionbar->Realize(); Show(); viewer->Freeze(); viewer->InitGL(); viewer->Thaw(); viewer->setClearColor(1,1,1,1); viewer->UpdateCamera(); } // Checks if the input file is a .rscene file or not and then writes the scene to it. void RSTFrame::OnSaveScene(wxCommandEvent& event) { wxString filepath; string filename; size_t endpath; wxFileDialog *SaveDialog = new wxFileDialog(this, _("Save File As"), wxT("../scene/"), wxT(""), _("*.rscene"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition); if (SaveDialog->ShowModal() == wxID_OK) { filepath = SaveDialog->GetPath(); filename = string(filepath.mb_str()); endpath = filename.find(".rscene"); if(endpath == -1) filename += ".rscene"; world->Save(filename); wxString filename_string(filename.c_str(), wxConvUTF8); saveText(filename_string,".lastload"); } } void RSTFrame::OnSaveRobot(wxCommandEvent& event) { } void RSTFrame::OnLoad(wxCommandEvent& event){ wxString filename = wxFileSelector(wxT("Choose a file to open"),wxT("../scene/"),wxT(""),wxT(""), // -- default extension wxT("*.rscene"), 0); if ( !filename.empty() ) DoLoad(string(filename.mb_str())); } void RSTFrame::OnQuickLoad(wxCommandEvent& event){ ifstream lastloadFile; lastloadFile.open(".lastload", ios::in); if(lastloadFile.fail()){ cout << "No previously loaded files" << endl; return; } string line; getline(lastloadFile,line); lastloadFile.close(); DoLoad(line); } void RSTFrame::DoLoad(string filename){ DeleteWorld(); world = new World(); world->Load(string(filename)); //UpdateTreeView(); cout << "Done Loading." << endl; treeView->CreateFromWorld(); cout << "Done Updating TreeView." << endl; viewer->ResetGL(); SetStatusText(wxT("Done Loading")); //Extract path to executable & save "lastload" there cout << "Saving " << filename << " to .lastload file" << endl; wxString filename_string(filename.c_str(), wxConvUTF8); saveText(filename_string,".lastload"); viewer->ResetGL(); selectedTreeNode = 0; treeView->ExpandAll(); updateAllTabs(); } void RSTFrame::DeleteWorld(){ InitTimer("",0); for(size_t i=0; i<timeVector.size(); i++){ if(timeVector[i]!=NULL) delete timeVector[i]; } timeVector.clear(); if(world !=NULL){ World* w = world; world = 0; selectedTreeNode = 0; treeView->DeleteAllItems(); w->DeleteModels(); delete w; } } void RSTFrame::OnToolOrder(wxCommandEvent& event){ reverseLinkOrder = !reverseLinkOrder; } void RSTFrame::OnToolCheckColl(wxCommandEvent& event){ // toggle collision detection check_for_collisions = !check_for_collisions; } void RSTFrame::OnToolMovie(wxCommandEvent& event){ wxString dirname = wxDirSelector(wxT("Choose input directory")); // , "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST if ( dirname.empty() ){ // filename cout << "No Directory Selected" << endl; return; } string path = string(dirname.mb_str()); char *buf = new char[1000]; int w,h; double step = .03333/tIncrement; int count = 0; #ifdef WIN32 ::CreateDirectory(path.c_str(),NULL); #else #endif for(double s=0; s<timeVector.size(); s+= step){ int i = (int)s; timeVector[i]->SetToWorld(world); viewer->UpdateCamera(); wxYield(); wxClientDC dc(viewer); dc.GetSize(&w, &h); wxMemoryDC memDC; wxBitmap memBmp(w, h); memDC.SelectObject(memBmp); #ifdef WIN32 // The fast way (currently only works in windowsXP) : memDC.Blit(0,0, w,h, &dc, 0,0); #else // The slow way: unsigned char* imageData = (unsigned char*)malloc(w*h*3); glReadPixels(0, 0, w-1, h-1, GL_RGB, GL_UNSIGNED_BYTE, imageData); int wIndex = 0; int hIndex = 0; for (int i=0; i < w*h*3; i+=3, ++wIndex) { if(wIndex >= w) { wIndex=0; hIndex++; } // vertically flip the image int hout = -hIndex+h-1; memDC.SetPen(wxPen(wxColor((int)imageData[i], (int)imageData[i+1], (int)imageData[i+2]), 1)); memDC.DrawCircle(wIndex, hout, 1); } free(imageData); #endif memDC.SelectObject(wxNullBitmap); sprintf(buf, "%s/%06d.png",path.c_str(),count); wxString fname = wxString(buf,wxConvUTF8); cout << "Saving:" << buf << ":" << endl; memBmp.SaveFile(fname, wxBITMAP_TYPE_PNG); count++; } delete buf; event.Skip(); } void RSTFrame::OnToolScreenshot(wxCommandEvent& event){ wxYield(); int w,h; // Draw Full window pixels first wxClientDC dc2(this); dc2.GetSize(&w, &h); wxMemoryDC memDC2; wxBitmap memBmp2(w, h); memDC2.SelectObject(memBmp2); memDC2.Blit(0,0, w,h, &dc2, 0,0); // Then draw viewer pixels, in case we're looping wxClientDC dc(viewer); dc.GetSize(&w, &h); wxMemoryDC memDC; wxBitmap memBmp(w, h); memDC.SelectObject(memBmp); #ifdef WIN32 // The fast way (currently only works in windowsXP) : memDC.Blit(0,0, w,h, &dc, 0,0); #else // The slow way: unsigned char* imageData = (unsigned char*) malloc(w * h * 3); glReadPixels(0, 0, w - 1, h - 1, GL_RGB, GL_UNSIGNED_BYTE, imageData); int wIndex = 0; int hIndex = 0; for (int i = 0; i < w * h * 3; i += 3, ++wIndex) { if (wIndex >= w) { wIndex = 0; hIndex++; } // vertically flip the image int hout = -hIndex + h - 1; memDC.SetPen(wxPen(wxColor((int) imageData[i], (int) imageData[i + 1], (int) imageData[i + 2]), 1)); memDC.DrawCircle(wIndex, hout, 1); memDC2.SetPen(wxPen(wxColor((int) imageData[i], (int) imageData[i + 1], (int) imageData[i + 2]), 1)); memDC2.DrawCircle(wIndex, hout, 1); } free(imageData); #endif memDC.SelectObject(wxNullBitmap); memDC2.SelectObject(wxNullBitmap); wxString fname(wxT("screenGL.png")); memBmp.SaveFile(fname, wxBITMAP_TYPE_PNG); wxString fname2(wxT("screen.png")); memBmp2.SaveFile(fname2, wxBITMAP_TYPE_PNG); SetStatusText(wxT("Screenshot saved in: screen.png, screenGL.png")); event.Skip(); } int RSTFrame::saveText(wxString scenepath, const char* llfile) { try { ofstream lastloadFile(llfile, ios::out); if (lastloadFile) { lastloadFile << string(scenepath.mb_str()) << endl; lastloadFile.close(); cout << "Saved" << endl; return 0; } else { cout << "Error opening file: " << llfile << endl; return -1; } }catch (const std::exception& e) { cout << "Shouldn't see this catch after migrating to wxWidgets... tell jon: " << e.what() << endl; return 0; } return 1; } void RSTFrame::OnClose(wxCommandEvent& event){ DeleteWorld(); viewer->UpdateCamera(); //exit(0); //DeleteWorld(); } void RSTFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { exit(0); //Close(true); } void RSTFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { wxMessageBox(wxString::Format(wxT("RST: Humanoids @ GT \ \n\n Mike Stilman\ \n Saul Reynolds-Haertl\ \n Jon Scholz\ \n Pushkar Kolhe\ \n Venkat Subramanian\ \n Jiuguang Wang\ \n Misha Novitzky\ \n Neil Dantam"), wxVERSION_STRING, wxGetOsDescription().c_str() ),wxT("Info"), wxOK | wxICON_INFORMATION,this); } void RSTFrame::onTVChange(wxTreeEvent& event){ updateAllTabs(); } // Go through all the tabs and indicate a state change void RSTFrame::updateAllTabs(){ int type = 0; wxCommandEvent evt(wxEVT_RST_STATE_CHANGE,GetId()); evt.SetEventObject(this); evt.SetClientData((void*)&type); size_t numPages = tabView->GetPageCount(); for(size_t i=0; i< numPages; i++){ RSTTab* tab = (RSTTab*)tabView->GetPage(i); tab->RSTStateChange(); } } void RSTFrame::setTimeValue(double value, bool sendSignal){ tCurrent = value; timeTrack->SetValue(value * tPrecision); updateTimeValue(value, sendSignal); } void RSTFrame::updateTimeValue(double value, bool sendSignal){ if(tIncrement == 0) return; char buf[100]; sprintf(buf, "%6.2f", tCurrent); wxString posString = wxString(buf,wxConvUTF8); timeText->ChangeValue(posString); unsigned int timeIndex = (int)((tCurrent/tMax)*((double)timeVector.size())); if(timeIndex > timeVector.size()-1) timeIndex = timeVector.size()-1; timeVector[timeIndex]->SetToWorld(world); viewer->UpdateCamera(); if(sendSignal) updateAllTabs(); } void RSTFrame::OnTimeScroll(wxScrollEvent &evt){ tCurrent = (double)(evt.GetPosition())/(double)tPrecision; //updateTimeValue(tCurrent); updateTimeValue(tCurrent,true); } void RSTFrame::AddWorld(World* world){ RSTimeSlice* tsnew = new RSTimeSlice(world); timeVector.push_back(tsnew); tMax += tIncrement; timeTrack->SetRange(0, tMax * tPrecision); } void RSTFrame::InitTimer(string title, double period){ for(size_t i=0; i<timeVector.size(); i++){ delete timeVector[i]; } tMax = 0; timeVector.clear(); tIncrement = period; } void RSTFrame::OnTimeEnter(wxCommandEvent &evt){ double p; timeText->GetValue().ToDouble(&p); if(p < 0) p = 0; if(p > tMax) p = tMax; setTimeValue(p); setTimeValue(p,true); } void RSTFrame::OnWhite(wxCommandEvent &evt){ viewer->setClearColor(0,0,0,1); viewer->UpdateCamera(); } void RSTFrame::OnBlack(wxCommandEvent &evt){ viewer->setClearColor(1,1,1,1); viewer->UpdateCamera(); } BEGIN_EVENT_TABLE(RSTFrame, wxFrame) EVT_COMMAND_SCROLL(1009, RSTFrame::OnTimeScroll) EVT_TEXT_ENTER(1008, RSTFrame::OnTimeEnter) EVT_MENU(MenuSaveScene, RSTFrame::OnSaveScene) EVT_MENU(MenuSaveRobot, RSTFrame::OnSaveRobot) EVT_MENU(MenuLoad, RSTFrame::OnLoad) EVT_MENU(MenuQuickLoad, RSTFrame::OnQuickLoad) EVT_MENU(wxID_CLOSE, RSTFrame::OnClose) EVT_MENU(MenuClose, RSTFrame::OnClose) EVT_MENU(MenuQuit, RSTFrame::OnQuit) EVT_MENU(MenuAbout, RSTFrame::OnAbout) EVT_MENU(MenuBgWhite, RSTFrame::OnBlack) EVT_MENU(MenuBgBlack, RSTFrame::OnWhite) EVT_MENU(wxID_OPEN, RSTFrame::OnLoad) EVT_MENU(Tool_quickload, RSTFrame::OnQuickLoad) EVT_MENU(wxID_SAVE, RSTFrame::OnSaveScene) EVT_MENU(Tool_linkorder, RSTFrame::OnToolOrder) EVT_MENU(Tool_checkcollisions, RSTFrame::OnToolCheckColl) EVT_MENU(Tool_screenshot, RSTFrame::OnToolScreenshot) EVT_MENU(Tool_movie, RSTFrame::OnToolMovie) EVT_TREE_SEL_CHANGED(TreeViewHandle,RSTFrame::onTVChange) // EVT_BUTTON (BUTTON_Hello, RSTFrame::OnQuit ) END_EVENT_TABLE()
[ "spinflip@e642834e-98c8-11de-b255-e1213ca11573", "alexgcunningham@e642834e-98c8-11de-b255-e1213ca11573" ]
[ [ [ 1, 200 ], [ 204, 276 ], [ 281, 302 ], [ 304, 304 ], [ 309, 309 ], [ 314, 314 ], [ 317, 318 ], [ 320, 323 ], [ 367, 367 ], [ 370, 371 ], [ 373, 378 ], [ 388, 392 ], [ 397, 397 ], [ 421, 421 ], [ 424, 501 ], [ 513, 513 ], [ 555, 556 ], [ 560, 561 ], [ 565, 599 ] ], [ [ 201, 203 ], [ 277, 280 ], [ 303, 303 ], [ 305, 308 ], [ 310, 313 ], [ 315, 316 ], [ 319, 319 ], [ 324, 366 ], [ 368, 369 ], [ 372, 372 ], [ 379, 387 ], [ 393, 396 ], [ 398, 420 ], [ 422, 423 ], [ 502, 512 ], [ 514, 554 ], [ 557, 559 ], [ 562, 564 ] ] ]
eed61644f7dd43a98438aeae8bfe4d94a49bc529
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/knet/tcp/TcpCommunicator.h
b2e5f12483e8dc40611fa43bd8fc6670fcf213f4
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
3,183
h
#pragma once #include <knet/aio/IoService.h> #include <knet/message/Message.h> #include <knet/message/MessageListener.h> #include <knet/tcp/impl/TcpConnection.h> #include <knet/tcp/impl/Acceptor.h> #include <knet/tcp/impl/Connector.h> #include <knet/socket/Socket.h> #include <knet/NetSecurity.h> #include <map> namespace gk { /** * @class TcpCommunicator * * Maintains a list of connected connections * and communicates with those connections. */ class TcpCommunicator { public: TcpCommunicator(); virtual ~TcpCommunicator(); /** * Initialize with upper layer and io service * * @param listener The listener to notify messages * @param ios IoService for this communicator for underlying IO * @return true if successful */ bool Init( MessageListener* listener, IoService* ios ); /** * Start listen on addr * * @param addr The ip:port to listen on * @param sl The security level. * @return true if successful */ bool Listen( const IpAddress& addr, SecurityLevel sl ); /** * Stop listen on addr * * @param addr The ip:port to stop listen */ void StopListen( const IpAddress& addr ); /** * Connect to remote. The result is notified with a NetStateMessage * * @param remote The ip:port to connect to */ void Connect( const IpAddress& remote ); /** * Close a connection * * @param connectionId The connection id to close. */ void Close( uint connectionId ); /** * Send a message to the connection. * * @param connectionId The tcp connection id * @param m The message to send */ void Send( uint connectionId, MessagePtr m ); /** * Send a message to several connections * * @param connections The list of connection ids to send to * @param m The message to send */ void Send( const std::vector<uint> connections, MessagePtr m ); /** * Tick function. Not a thread function. */ void Run(); /** * Called when to notify message. * * Used by connections to notify message to communicator * * @param m The message to notify */ void Notify( MessagePtr m ); /** * Clean up */ void Fini(); /** * Find connection. Used only by NetClient or NetServer * * @param id The connection id to find * @return The TcpConnection found. 0 if not found. */ TcpConnection* FindById( uint id ); private: typedef std::map<uint, TcpConnection*> ConnectionMap; typedef std::map<uint, Acceptor*> AcceptorMap; void processConnections(); void processMessages(); void onStateMessage( MessagePtr m ); void onRelayMessage( MessagePtr m ); void onNewConnection( Socket* s, SecurityLevel sl, bool accepted ); void cleanupMessages(); void cleanupConnections(); void cleanupAcceptors(); private: MessageListener* m_listener; IoService* m_ios; ConnectionMap m_connections; // normal connections including udp AcceptorMap m_acceptors; Connector m_connector; // A threaded connector MessageQ m_messages; uint m_nextConnectionId; }; } // gk
[ "darkface@localhost" ]
[ [ [ 1, 140 ] ] ]
e48bf6394b12cccd4e148b8fb70f37eb5056e1b0
94d9e8ec108a2f79068da09cb6ac903c16b77730
/sociarium/module/layout_high_dimensional_embedding.cpp
ab9cdef0960c381265056e85bd136ac8a2e8a890
[]
no_license
kiyoya/sociarium
d375c0e5abcce11ae4b087930677483d74864d09
b26c2c9cbd23c2f8ef219d0059e42370294865d1
refs/heads/master
2021-01-25T07:28:25.862346
2009-10-22T05:57:42
2009-10-22T05:57:42
318,115
1
0
null
null
null
null
UTF-8
C++
false
false
8,805
cpp
// s.o.c.i.a.r.i.u.m: module/layout_high_dimensional_embedding.cpp // HASHIMOTO, Yasuhiro (E-mail: hy @ sys.t.u-tokyo.ac.jp) /* Copyright (c) 2005-2009, HASHIMOTO, Yasuhiro, All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the University of Tokyo nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <map> #include <boost/format.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/symmetric.hpp> #define BOOST_NUMERIC_BINDINGS_USE_CLAPACK /* "BOOST_NUMERIC_BINDINGS_USE_CLAPACK" if you use clapack, * When you also want to use the "Reference BLAS" implementation that comes with clapack, * you probably have to define "BIND_FORTRAN_LOWERCASE_UNDERSCORE" instead of * "BOOST_NUMERIC_BINDINGS_USE_CLAPACK" and link against the "*_nowrap.lib" libraries. */ #include <boost/numeric/bindings/lapack/geev.hpp> #include <boost/numeric/bindings/traits/std_vector.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #undef BOOST_NUMERIC_BINDINGS_USE_CLAPACK #include "layout.h" #include "../graph_utility.h" #include "../menu_and_message.h" #include "../../shared/mtrand.h" #include "../../shared/thread.h" #include "../../graph/util/traverser.h" #ifdef _MSC_VER #ifdef NDEBUG #pragma comment(lib, "libf2c.lib") #pragma comment(lib, "BLAS.lib") #pragma comment(lib, "clapack.lib") #else #pragma comment(lib, "libf2cd.lib") #pragma comment(lib, "BLASd.lib") #pragma comment(lib, "clapackd.lib") #pragma comment(linker, "/NODEFAULTLIB:LIBCMTD.lib") #endif BOOL WINAPI DllMain (HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvReserved) { return TRUE; } #endif namespace hashimoto_ut { using std::vector; using std::deque; using std::wstring; using std::multimap; using std::complex; using std::make_pair; using std::swap; using std::greater; using std::tr1::shared_ptr; using namespace sociarium_project_module_layout; using namespace sociarium_project_menu_and_message; namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; #ifdef _MSC_VER extern "C" __declspec(dllexport) void __cdecl layout( #else extern "C" void layout( #endif Thread& parent, wstring& status, Message const& message, vector<Vector2<double> >& position, shared_ptr<Graph const> graph, vector<double> const& hint) { size_t const nsz = graph->nsize(); size_t const esz = graph->esize(); assert(nsz==position.size()); if (nsz<4) return; if (esz==0) return; status = (boost::wformat(L"%s") %message.get(Message::HDE)).str(); size_t const number_of_centers_ = 50>nsz?nsz:50; // Select the center nodes randomly. vector<size_t> center(number_of_centers_); { vector<size_t> v(nsz); for (size_t i=0; i<nsz; ++i) v[i] = i; for (size_t i=0; i<number_of_centers_; ++i) swap(v[i], v[size_t(mt::rand()*(nsz-i))+i]); center.assign(v.begin(), v.begin()+number_of_centers_); } // Calculate distance between each node and the center nodes. ublas::matrix<double, ublas::column_major> distance(ublas::zero_matrix<double, ublas::column_major>(number_of_centers_, nsz)); ublas::vector<double> mean_distance(number_of_centers_, 0.0); vector<int> count(number_of_centers_, 0); for (size_t i=0; i<number_of_centers_; ++i) { // ********** Catch a termination signal ********** if (parent.cancel_check()) return; status = (boost::wformat(L"%s: %d%%") %message.get(Message::HDE_CALCULATING_GRAPH_DISTANCE) %int(100.0*(i+1)/number_of_centers_)).str(); shared_ptr<BFSTraverser> t = BFSTraverser::create<bidirectional_tag>(graph); for (t->start(graph->node(center[i]), 0.0); !t->end(); t->advance()) { ++count[i]; distance(i, t->node()->index()) = t->distance(); } for (size_t j=0; j<nsz; ++j) mean_distance[i] += distance(i, j); } for (size_t i=0; i<number_of_centers_; ++i) { mean_distance[i] /= count[i]; for (size_t j=0; j<nsz; ++j) distance(i, j) -= mean_distance[i]; } // Calculate variance-covariance matrix of distance from the center nodes. ublas::matrix<double, ublas::column_major> distanceT(trans(distance)); ublas::matrix<double, ublas::column_major> m(prod(distance, distanceT)); for (size_t i=0; i<number_of_centers_; ++i) { // ********** Catch a termination signal ********** if (parent.cancel_check()) return; status = (boost::wformat(L"%s: %d%%") %message.get(Message::HDE_CALCULATING_MATRIX) %int(100.0*(i+1)/number_of_centers_)).str(); for (size_t j=0; j<number_of_centers_; ++j) m(i, j) /= nsz; } status = (boost::wformat(L"%s") %message.get(Message::HDE_CALCULATING_PRINCIPAL_COMPONENTS)).str(); // Calculate eigen values and eigen vectors of variance-covariance matrix. ublas::matrix<complex<double>, ublas::column_major> eigv(number_of_centers_, number_of_centers_); ublas::vector<complex<double> > eig(number_of_centers_); int const err = lapack::geev( m, eig, (ublas::matrix<complex<double>, ublas::column_major>*)0, &eigv, lapack::optimal_workspace()); BOOST_UBLAS_CHECK(err==0, ublas::internal_logic()); // X and Y coordinates are weighted by the eigenvector. multimap<double, size_t, greater<double> > pca; for (size_t i=0; i<number_of_centers_; ++i) { //assert(eig[i].imag()!=0.0); //pca.insert(make_pair(eig[i].real(), i)); pca.insert(make_pair(sqrt(eig[i].real()*eig[i].real() +eig[i].imag()*eig[i].imag()), i)); } multimap<double, size_t, greater<double> >::const_iterator mit = pca.begin(); assert(mit!=pca.end()); size_t const c1 = mit->second; ++mit; assert(mit!=pca.end()); size_t const c2 = mit->second; ++mit; assert(mit!=pca.end()); size_t const c3 = mit->second; size_t const cc1 = hint[0]==3?c2:c1; size_t const cc2 = hint[0]==1?c2:c3; /* If hint[0]==1, use 1st and 2nd principal eigenvectors. * If hint[0]==2, use 1st and 3rd principal eigenvectors. * If hint[0]==3, use 2nd and 3rd principal eigenvectors. */ for (size_t i=0; i<nsz; ++i) { // ********** Catch a termination signal ********** if (parent.cancel_check()) return; status = (boost::wformat(L"%s: %d%%") %message.get(Message::HDE_CALCULATING_POSITION) %int(100.0*(i+1)/nsz)).str(); position[i].x = 0.0; position[i].y = 0.0; for (size_t j=0; j<number_of_centers_; ++j) { position[i].x += distance(j, i)*eigv(j, cc1).real(); position[i].y += distance(j, i)*eigv(j, cc2).real(); } } } } // The end of the namespace "hashimoto_ut"
[ [ [ 1, 239 ] ] ]
88a5765b7ced21b28431ae89a0b2926452313af8
a2ba072a87ab830f5343022ed11b4ac365f58ef0
/ urt-bumpy-q3map2 --username [email protected]/libs/jpeg6/jdcolor.cpp
5c1735972b0d5cf2ad28e38f4b81b7f587d87fd4
[]
no_license
Garey27/urt-bumpy-q3map2
7d0849fc8eb333d9007213b641138e8517aa092a
fcc567a04facada74f60306c01e68f410cb5a111
refs/heads/master
2021-01-10T17:24:51.991794
2010-06-22T13:19:24
2010-06-22T13:19:24
43,057,943
0
0
null
null
null
null
UTF-8
C++
false
false
13,200
cpp
/* * jdcolor.c * * Copyright (C) 1991-1995, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains output colorspace conversion routines. */ #define JPEG_INTERNALS #include "jinclude.h" #include "radiant_jpeglib.h" /* Private subobject */ typedef struct { struct jpeg_color_deconverter pub; /* public fields */ /* Private state for YCC->RGB conversion */ int * Cr_r_tab; /* => table for Cr to R conversion */ int * Cb_b_tab; /* => table for Cb to B conversion */ INT32 * Cr_g_tab; /* => table for Cr to G conversion */ INT32 * Cb_g_tab; /* => table for Cb to G conversion */ } my_color_deconverter; typedef my_color_deconverter * my_cconvert_ptr; /**************** YCbCr -> RGB conversion: most common case **************/ /* * YCbCr is defined per CCIR 601-1, except that Cb and Cr are * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5. * The conversion equations to be implemented are therefore * R = Y + 1.40200 * Cr * G = Y - 0.34414 * Cb - 0.71414 * Cr * B = Y + 1.77200 * Cb * where Cb and Cr represent the incoming values less CENTERJSAMPLE. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.) * * To avoid floating-point arithmetic, we represent the fractional constants * as integers scaled up by 2^16 (about 4 digits precision); we have to divide * the products by 2^16, with appropriate rounding, to get the correct answer. * Notice that Y, being an integral input, does not contribute any fraction * so it need not participate in the rounding. * * For even more speed, we avoid doing any multiplications in the inner loop * by precalculating the constants times Cb and Cr for all possible values. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table); * for 12-bit samples it is still acceptable. It's not very reasonable for * 16-bit samples, but if you want lossless storage you shouldn't be changing * colorspace anyway. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the * values for the G calculation are left scaled up, since we must add them * together before rounding. */ #define SCALEBITS 16 /* speediest right-shift on some machines */ #define ONE_HALF ((INT32) 1 << (SCALEBITS-1)) #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5)) /* * Initialize tables for YCC->RGB colorspace conversion. */ LOCAL void build_ycc_rgb_table (j_decompress_ptr cinfo) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; int i; INT32 x; SHIFT_TEMPS cconvert->Cr_r_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cb_b_tab = (int *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(int)); cconvert->Cr_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); cconvert->Cb_g_tab = (INT32 *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE+1) * SIZEOF(INT32)); for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) { /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */ /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */ /* Cr=>R value is nearest int to 1.40200 * x */ cconvert->Cr_r_tab[i] = (int) RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS); /* Cb=>B value is nearest int to 1.77200 * x */ cconvert->Cb_b_tab[i] = (int) RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS); /* Cr=>G value is scaled-up -0.71414 * x */ cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x; /* Cb=>G value is scaled-up -0.34414 * x */ /* We also add in ONE_HALF so that need not do it in inner loop */ cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF; } } /* * Convert some rows of samples to the output colorspace. * * Note that we change from noninterleaved, one-plane-per-component format * to interleaved-pixel format. The output buffer is therefore three times * as wide as the input buffer. * A starting row offset is provided only for the input buffer. The caller * can easily adjust the passed output_buf value to accommodate any row * offset required on that side. */ METHODDEF void ycc_rgb_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register int y, cb, cr; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; register int * Crrtab = cconvert->Cr_r_tab; register int * Cbbtab = cconvert->Cb_b_tab; register INT32 * Crgtab = cconvert->Cr_g_tab; register INT32 * Cbgtab = cconvert->Cb_g_tab; SHIFT_TEMPS while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { y = GETJSAMPLE(inptr0[col]); cb = GETJSAMPLE(inptr1[col]); cr = GETJSAMPLE(inptr2[col]); /* Range-limiting is essential due to noise introduced by DCT losses. */ outptr[RGB_RED] = range_limit[y + Crrtab[cr]]; outptr[RGB_GREEN] = range_limit[y + ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS))]; outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]]; outptr += RGB_PIXELSIZE; } } } /**************** Cases other than YCbCr -> RGB **************/ /* * Color conversion for no colorspace change: just copy the data, * converting from separate-planes to interleaved representation. */ METHODDEF void null_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { register JSAMPROW inptr, outptr; register JDIMENSION count; register int num_components = cinfo->num_components; JDIMENSION num_cols = cinfo->output_width; int ci; while (--num_rows >= 0) { for (ci = 0; ci < num_components; ci++) { inptr = input_buf[ci][input_row]; outptr = output_buf[0] + ci; for (count = num_cols; count > 0; count--) { *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */ outptr += num_components; } } input_row++; output_buf++; } } /* * Color conversion for grayscale: just copy the data. * This also works for YCbCr -> grayscale conversion, in which * we just copy the Y (luminance) component and ignore chrominance. */ METHODDEF void grayscale_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0, num_rows, cinfo->output_width); } /* * Adobe-style YCCK->CMYK conversion. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same * conversion as above, while passing K (black) unchanged. * We assume build_ycc_rgb_table has been called. */ METHODDEF void ycck_cmyk_convert (j_decompress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION input_row, JSAMPARRAY output_buf, int num_rows) { my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert; register int y, cb, cr; register JSAMPROW outptr; register JSAMPROW inptr0, inptr1, inptr2, inptr3; register JDIMENSION col; JDIMENSION num_cols = cinfo->output_width; /* copy these pointers into registers if possible */ register JSAMPLE * range_limit = cinfo->sample_range_limit; register int * Crrtab = cconvert->Cr_r_tab; register int * Cbbtab = cconvert->Cb_b_tab; register INT32 * Crgtab = cconvert->Cr_g_tab; register INT32 * Cbgtab = cconvert->Cb_g_tab; SHIFT_TEMPS while (--num_rows >= 0) { inptr0 = input_buf[0][input_row]; inptr1 = input_buf[1][input_row]; inptr2 = input_buf[2][input_row]; inptr3 = input_buf[3][input_row]; input_row++; outptr = *output_buf++; for (col = 0; col < num_cols; col++) { y = GETJSAMPLE(inptr0[col]); cb = GETJSAMPLE(inptr1[col]); cr = GETJSAMPLE(inptr2[col]); /* Range-limiting is essential due to noise introduced by DCT losses. */ outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */ outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */ ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS)))]; outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */ /* K passes through unchanged */ outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */ outptr += 4; } } } /* * Empty method for start_pass. */ METHODDEF void start_pass_dcolor (j_decompress_ptr cinfo) { /* no work needed */ } /* * Module initialization routine for output colorspace conversion. */ GLOBAL void jinit_color_deconverter (j_decompress_ptr cinfo) { my_cconvert_ptr cconvert; int ci; cconvert = (my_cconvert_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_color_deconverter)); cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert; cconvert->pub.start_pass = start_pass_dcolor; /* Make sure num_components agrees with jpeg_color_space */ switch (cinfo->jpeg_color_space) { case JCS_GRAYSCALE: if (cinfo->num_components != 1) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; case JCS_RGB: case JCS_YCbCr: if (cinfo->num_components != 3) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; case JCS_CMYK: case JCS_YCCK: if (cinfo->num_components != 4) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; default: /* JCS_UNKNOWN can be anything */ if (cinfo->num_components < 1) ERREXIT(cinfo, JERR_BAD_J_COLORSPACE); break; } /* Set out_color_components and conversion method based on requested space. * Also clear the component_needed flags for any unused components, * so that earlier pipeline stages can avoid useless computation. */ switch (cinfo->out_color_space) { case JCS_GRAYSCALE: cinfo->out_color_components = 1; if (cinfo->jpeg_color_space == JCS_GRAYSCALE || cinfo->jpeg_color_space == JCS_YCbCr) { cconvert->pub.color_convert = grayscale_convert; /* For color->grayscale conversion, only the Y (0) component is needed */ for (ci = 1; ci < cinfo->num_components; ci++) cinfo->comp_info[ci].component_needed = FALSE; } else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; case JCS_RGB: cinfo->out_color_components = RGB_PIXELSIZE; if (cinfo->jpeg_color_space == JCS_YCbCr) { cconvert->pub.color_convert = ycc_rgb_convert; build_ycc_rgb_table(cinfo); } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) { cconvert->pub.color_convert = null_convert; } else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; case JCS_CMYK: cinfo->out_color_components = 4; if (cinfo->jpeg_color_space == JCS_YCCK) { cconvert->pub.color_convert = ycck_cmyk_convert; build_ycc_rgb_table(cinfo); } else if (cinfo->jpeg_color_space == JCS_CMYK) { cconvert->pub.color_convert = null_convert; } else ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; default: /* Permit null conversion to same output space */ if (cinfo->out_color_space == cinfo->jpeg_color_space) { cinfo->out_color_components = cinfo->num_components; cconvert->pub.color_convert = null_convert; } else /* unsupported non-null conversion */ ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL); break; } if (cinfo->quantize_colors) cinfo->output_components = 1; /* single colormapped output component */ else cinfo->output_components = cinfo->out_color_components; }
[ [ [ 1, 734 ] ] ]
2d43618625c974128f66c12d40cd3f0cfab8ba0c
324f89c0e9d8691aac184149786dff012a7f6e92
/src/MbBitfield.h
31067bd78ea9f1674ff15883aeea60c8445d8f32
[]
no_license
ttriche/rStructurama
498d646600af7eb3a06c5f31b52df7c7a398264c
9aa068fa6ae933653e9cb38a7103ccbbba6558ee
refs/heads/master
2021-01-01T15:50:33.752359
2010-12-30T01:30:27
2010-12-30T01:30:27
1,182,456
1
0
null
null
null
null
UTF-8
C++
false
false
11,382
h
/*! * \file * This file declares MbBitfield, which is used to hold bitfields. * * \brief Declaration of MbBitfield * * MrBayes version 4.0 beta * * (c) Copyright 2005. * \version 4.0 Beta * \date Last modified: $Date: 2006/06/04 16:25:45 $ * \author John Huelsenbeck (1) * \author Bret Larget (2) * \author Paul van der Mark (3) * \author Fredrik Ronquist (3) * \author Donald Simon (4) * \author (authors listed in alphabetical order) * (1) Division of Biological Science, University of California, San Diego * (2) Departments of Botany and of Statistics, University of Wisconsin - Madison * (3) School of Computational Science, Florida State University * (4) Department of Mathematics/Computer Science, Duquesne University * * 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 (the file gpl.txt included with this * distribution or http: *www.gnu.org/licenses/gpl.txt) for more * details. * * $Id: $ */ #ifndef MbBitfield_H #define MbBitfield_H #include <iostream> #include <climits> /*! * This is a class for bitfields. It stores the bits * in unsigned long ints. * * The class is inspired by the Template Numerical Toolkit * and implements garbage collection as well as shallow * assignment for the assignment operator and copy constructor. * * The class uses two const static members: bpl, which is the * number of bits in an unsigned long (bits per long); and hb, * which is an unsigned long with the highest bit set (high bit). * * The most common operations on bitfields have been inlined. * * \brief Bitfield class */ class MbBitfield { public: MbBitfield(void); //!< null constructor MbBitfield(int numBits); //!< constructs bitfield of length n inline MbBitfield(const MbBitfield &A); //!< constructs shallow copy of bitfield A ~MbBitfield(void); //!< destructor with garbage collection unsigned long &operator[](int i) { return v[i]; } //!< indexing of unsigned longs unsigned long &operator[](int i) const { return v[i]; }; //!< indexing of unsigned longs (const bitfield) MbBitfield &operator=(const MbBitfield &A) { return ref(A); } //!< assignment operator (shallow copy, elements share bits) bool operator==(const MbBitfield &A) const; //!< equality operator bool operator>(const MbBitfield &A) const; //!< larger than operator inline MbBitfield operator&(const MbBitfield &A) const; //!< operator & inline MbBitfield operator|(const MbBitfield &A) const; //!< operator | inline MbBitfield operator^(const MbBitfield &A) const; //!< operator ^ inline MbBitfield &ref(const MbBitfield &A); //!< creates a reference to another bitfield (shallow copy) MbBitfield copy(void) const; //!< creates a copy of another bitfield (deep copy, with separate bits) MbBitfield &inject(const MbBitfield & A); //!< copy the bits from one bitfield to another int dim(void) const { return n; } //!< get the dimension (number of bits) int dim_(void) const { return m; } //!< get the dimension (number of longs) int getRefCount(void) const {return *refCount; } //!< get the number of bitfields that share the same data bool isBitSet(int i) const {return ((v[i/bpl]&(hb>>(i%bpl)))!=0); }//!< is bit i set (on)? inline int numOnBits (void) const; //!< return number of bits that are on inline int firstOnBit (void) const; //!< return index of first bit that is on inline void setBits(void); //!< set all bits inline void clearBits(void); //!< clear all bits inline void flipBits(void); //!< flip all bits void setBit(int i) { v[i/bpl]|=(hb>>(i%bpl)); } //!< set bit i void clearBit(int i) { v[i/bpl]&=((hb>>(i%bpl))^ULONG_MAX); } //!< clear bit i void flipBit(int i) { v[i/bpl]^=((hb>>(i%bpl))); } //!< flip bit i private: const static int bpl = (int) sizeof (unsigned long) * 8; //!< number of bits per long (assumes 8 bits per char) const static unsigned long hb = (1UL << (bpl-1)); //!< highest bit in an unsigned long for shift ops unsigned long *v; //!< pointer to unsigned longs (ie, bitfield) int m; //!< number of unsigned longs int n; //!< number of bits unsigned long mask; //!< mask to control trailing bits in some operations int *refCount; //!< number of instances of the vector void destroy(void); //!< garbage collection }; std::ostream& operator<<(std::ostream &s, const MbBitfield &A); //!< operator << std::istream& operator>>(std::istream &s, MbBitfield &A); //!< operator >> MbBitfield operator!(const MbBitfield &A); //!< operator ! MbBitfield &operator&=(MbBitfield &A, const MbBitfield &B); //!< operator &= MbBitfield &operator|=(MbBitfield &A, const MbBitfield &B); //!< operator |= MbBitfield &operator^=(MbBitfield &A, const MbBitfield &B); //!< operator ^= bool operator!=(const MbBitfield &A, const MbBitfield &B); //!< inequality operator bool operator< (const MbBitfield &A, const MbBitfield &B); //!< operator < bool operator<=(const MbBitfield &A, const MbBitfield &B); //!< operator <= bool operator>=(const MbBitfield &A, const MbBitfield &B); //!< operator >= // Function definitions for inlined functions /*! * Copy constructor, which creates a shallow copy of the * bitfield argument. Bitfield data are not copied but shared. * Thus, in MbBitfield B(A), subsequent changes to A will be * reflected by changes in B. For an independent copy, use * MbBitfield B(A.copy()), or B = A.copy(), instead. Note * the use of garbage collection in this class, through the * refCount argument * * \brief Shallow copy constructor * \param A Bitfield to copy */ inline MbBitfield::MbBitfield(const MbBitfield &A) : v(A.v), m(A.m), n(A.n), mask(A.mask), refCount(A.refCount) { (*refCount)++; } /*! * Create a reference (shallow assignment) to another existing bitfield. * In B.ref(A), B and A share the same data and subsequent changes * to the bits of one will be reflected in the other. Note that * the reference counter is always allocated, even for null bitfields, * so we need not test whether refCount is NULL. * * This is what operator= calls, and B=A and B.ref(A) are equivalent * operations. * * \brief Make this reference to A */ inline MbBitfield &MbBitfield::ref(const MbBitfield &A) { if (this != &A) { (*refCount)--; if ( *refCount < 1) destroy(); m = A.m; n = A.n; v = A.v; mask = A.mask; refCount = A.refCount; (*refCount)++; } return *this; } /*! * This function performs bitwise AND (&) of two bitfields * and returns the resulting bitfield. * * \brief operator& * \param A Bitfield to AND with this * \return Resulting bitfield */ MbBitfield MbBitfield::operator&(const MbBitfield &A) const { if (A.dim() != n ) return MbBitfield(); else { MbBitfield B(n); for (int i=0; i<m; i++) B[i] = v[i] & A[i]; return B; } } /*! * This function performs bitwise OR (|) of two bitfields * and returns the resulting bitfield. * * \brief operator| * \param A Bitfield to OR with this * \return Resulting bitfield */ MbBitfield MbBitfield::operator|(const MbBitfield &A) const { if (A.dim() != n ) return MbBitfield(); else { MbBitfield B(n); for (int i=0; i<m; i++) B[i] = v[i] | A[i]; return B; } } /*! * This function performs bitwise XOR (^) of two bitfields * and returns the resulting bitfield. * * \brief operator^ * \param A Bitfield to XOR with this * \return Resulting bitfield */ MbBitfield MbBitfield::operator^(const MbBitfield &A) const { if (A.dim() != n ) return MbBitfield(); else { MbBitfield B(n); for (int i=0; i<m; i++) B[i] = v[i] ^ A[i]; return B; } } /*! * Set all bits. * * \brief Set bits */ inline void MbBitfield::setBits(void) { for (int i=0; i<m; i++) v[i] = ULONG_MAX; v[m-1] &= mask; // ensure clear trailing bits } /*! * Clear all bits. * * \brief Set bits */ inline void MbBitfield::clearBits(void) { for (int i=0; i<m; i++) v[i] = 0; } /*! * Flip all bits. * * \brief Set bits */ inline void MbBitfield::flipBits(void) { for (int i=0; i<m; i++) v[i] = v[i] ^ ULONG_MAX; v[m-1] &= mask; // ensure clear trailing bits } /*! * Return number of on bits. * * \brief Number on bits * \return Number on bits */ inline int MbBitfield::numOnBits(void) const { # if 1 int count = 0; for (int i=0; i<n; i++) if ( (v[i/bpl] & (hb >> (i % bpl))) != 0 ) count++; return count; # else int count = 0; for (int i=0; i<m; i++) { unsigned long x = v[i]; while (x != 0) { count++; x &= (x-1); } } return count; # endif } /*! * Return 0-based index of first bit that * is on. If no bits are on, return -1. * * \brief First on bit * \return Index of first on bit or -1 if no bits are on */ inline int MbBitfield::firstOnBit(void) const { int i, j; for (i=0; i<m; i++) { if (v[i] != 0) break; } if (i == m) return -1; for (j=0; j<bpl; j++) { if ((v[i]&(hb>>j))!=0) break; } return (i*bpl + j); } #endif
[ [ [ 1, 316 ] ] ]
0ee3d2dd04ff53b6c0405e6b8805fdca158b4c67
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/game/BTurnAnimEvent.h
dff285a6106b66b611ce848613b62df9cf438986
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
h
// BTurnAnimEvent.h // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert 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, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #ifndef BTURNANIMEVENT_H #define BTURNANIMEVENT_H #include "SDL/SDL_types.h" #include "BuildingAnimEvent.h" #include "Structure.h" /** * The animation that turns structures to face a given direction. This is only used when attacking. * * @version 1.0 * @since r378 */ class BTurnAnimEvent : public BuildingAnimEvent { public: /** * @param p the priority of this event * @param str the structure to which this animation is to be applied * @param face the direction the structure is to face */ BTurnAnimEvent(Uint32 p, Structure * str, Uint8 face); void anim_func(anim_nfo * data); private: Uint8 frame; Uint8 targetface; Sint8 turnmod; Structure * str; }; #endif //BTURNANIMEVENT_H
[ [ [ 1, 50 ] ] ]
cc559043345784e54eedde324eb553b5a5234f78
b2462932074a3d395d2125cec6265612d1b2ebe8
/Source/Util.cpp
5c98207444c9dc58a8f0919694550026bb617bce
[]
no_license
olegp/neural
8d3b3e8ba1af546d27c537b361e906ee4e1d823d
a0e04dd3cb2dfc857e23c2d9b22b24dcfece6031
refs/heads/master
2020-05-27T11:59:46.195413
2010-07-14T13:07:33
2010-07-14T13:07:33
774,510
2
3
null
null
null
null
UTF-8
C++
false
false
5,412
cpp
#include "Util.h" #include <stdlib.h> #include <memory.h> #include <time.h> //*** Element Element::Element() : container(null), prev(null), next(null) { } Element::~Element() { Free(); } void Element::Free() { if(container) container->Detach(this); } //*** Container Container::Container() : elements(null), size(0) { } Container::~Container() { DetachAll(); } Element* Container::Elements() { return elements; } bool Container::Find(const Element *element) { Element *c = elements; while(c != null) { if(c == element) return true; c = c->next; } return false; } int Container::GetIndex(const Element *element) { Element *c = elements; int i = 0; while(c != null) { if(c == element) return i; c = c->next; i ++; } return -1; } bool Container::Attach(Element *element) { if(!Find(element)) { element->Free(); if(elements != null) elements->prev = element; element->prev = null; element->next = elements; elements = element; element->container = this; size ++; return true; } return false; } bool Container::AttachLast(Element *element) { if(!Find(element)) { element->Free(); if(elements == null) { element->prev = null; element->next = elements; elements = element; element->container = this; } else { Element *last; for(last = elements; last->next != null; last = last->next); last->next = element; element->prev = last; element->next = null; element->container = this; } size ++; return true; } return false; } bool Container::AttachAfter(Element *element, Element *after) { if(!Find(element) && Find(after)) { element->Free(); Element *next = after->next; element->next = next; if(next != null) next->prev = element; element->prev = after; after->next = element; element->container = this; size ++; return true; } return false; } bool Container::AttachBefore(Element *element, Element *before) { if(!Find(element) && Find(before)) { element->Free(); Element *prev = before->prev; element->next = before; before->prev = element; element->prev = prev; if(prev != null) { prev->next = element; } else elements = element; element->container = this; size ++; return true; } return false; } bool Container::AttachAt(Element *element, int index) { if(!Find(element)) { Element *before = Get(index); if(before != null) { element->Free(); Element *prev = before->prev; element->next = before; before->prev = element; element->prev = prev; if(prev != null) { prev->next = element; } else elements = element; element->container = this; size ++; return true; } } return false; } bool Container::Detach(Element *element) { if(Find(element)) { if(element->prev == null) elements = element->next; else element->prev->next = element->next; if(element->next != null) element->next->prev = element->prev; element->prev = element->next = null; element->container = null; size --; return true; } return false; } void Container::DetachAll() { while(elements != null) Detach(elements); } void Container::Empty() { while(elements != null) delete elements; } void Container::ReleaseAll() { /* Element *element = elements; while(element != null) { Element *next = element->next; ((Object *)element)->Release(); element = next; } */ } int Container::GetSize() { return size; } Element* Container::Get(int number) { int i = 0; Element *c = elements; while(c != null) { if(i == number) return c; c = c->next; i ++; } return null; } //*** CleanContainer CleanContainer::~CleanContainer() { Empty(); } //*** MemoryBuffer int MemoryBuffer::GetSize() { return size; } void* MemoryBuffer::GetBuffer() { return buffer; } // expands the buffer if necessary and returns the pointer to the bytes void* MemoryBuffer::GetBuffer(int bytesize) { if(bytesize > size) { safe_delete(buffer); size = bytesize; buffer = new unsigned char[size]; } return buffer; } void* MemoryBuffer::Realloc(int bytesize) { int copysize = min(bytesize,size); unsigned char *newbuffer = new unsigned char[bytesize]; memcpy(newbuffer, buffer, copysize); safe_delete_array(buffer); buffer = newbuffer; size = bytesize; return buffer; } void MemoryBuffer::Clear() { safe_delete_array(buffer); size = 0; } MemoryBuffer::MemoryBuffer() : buffer(null), size(0) { } MemoryBuffer::MemoryBuffer(int bytesize) { size = bytesize; buffer = new unsigned char[size]; } MemoryBuffer::~MemoryBuffer() { Clear(); } //*** Random Random Random::initializer; Random::Random() { srand((unsigned int)time(null)); } double Random::GetDouble(double min, double max) { double r = (double)rand()/(double)RAND_MAX; return (max - min) * r + min; } int Random::GetInt(int min, int max) { return rand() % (max - min) + min; }
[ [ [ 1, 340 ] ] ]
9dc04a30caa01bccaed14ae370743e7bd8027576
aef214d9d61c9802d7b0627fa23c95a08a505d0e
/easyunit/easyunit/testprinter.h
5e36fb750fd66161d3d7d5579b427360fa775ecd
[]
no_license
lojo/Strongtalk
a19ab800be89a6be3a19e8a5a33277e3e284ab15
382a12935c975ec79949b4e337fd546c01c11f3b
refs/heads/master
2021-01-16T22:29:48.373751
2011-01-31T22:25:57
2011-01-31T22:25:57
1,153,049
1
0
null
null
null
null
UTF-8
C++
false
false
1,573
h
/* EasyUnit : Simple C++ Unit testing framework Copyright (C) 2004 Barthelemy Dagenais This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Barthelemy Dagenais [email protected] */ #ifndef TESTPRINTER_H #define TESTPRINTER_H #include "testresult.h" namespace easyunit { /** * A TestPrinter is a class used by the TestRegistry to print results * of executed TestCases. This is an abstract class, so no default behavior * for the print method is provided. * * @see easyunit::DefaultTestPrinter */ class TestPrinter: public CHeap { public: /** * Print the details of a given TestResult instance. This * method must be overridden by subclasses since it is * abstract. * * @param testResult TestResult instance that the user wish to print */ virtual void print(const TestResult *testResult) = 0; }; } // EasyUnit ns #endif // TESTPRINTER_H
[ "StephenLRees@0765cc13-ff1d-0410-8584-d7a1c31ec48e" ]
[ [ [ 1, 52 ] ] ]
053374617641336d95d6cf5b05cd67fa9129599f
c3531ade6396e9ea9c7c9a85f7da538149df2d09
/Param/src/Common/Rotation.cpp
57f4b65f5a4dda7d2ed23172b24517b2823aa6a5
[]
no_license
feengg/MultiChart-Parameterization
ddbd680f3e1c2100e04c042f8f842256f82c5088
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
refs/heads/master
2020-03-28T16:43:51.242114
2011-04-19T17:18:44
2011-04-19T17:18:44
null
0
0
null
null
null
null
GB18030
C++
false
false
18,437
cpp
/*_____________________________________________________ | | Intra3D Layer1 : Algebra 构件组成之一 | | 文件:Rotation.cpp | | 功能:四元组运算 | | 开发:林锐 ,1999/01/10 | | 源程序测试:进行了单步跟踪测试 | |_____________________________________________________*/ /*_____________________________________________________ | | 基于 OpenGL 的交互式三维图形软件开发工具 | | ** Intra3D 2.0 for Windows 9X/NT ** | | 著作权人:林锐 | | 浙江大学 CAD&CG 国家重点实验室 (310027) |_____________________________________________________*/ #include <math.h> #include <assert.h> #include "Rotation.h" /*_____________________________________________________ | | Quaternion & Rotation Functions | | 已进行逐步跟踪测试,林锐,1999/01/16 |_____________________________________________________*/ /*_____________________________________________________________ | | 有关 Quaternion 与 Rotation 的原理请参考: | | (1) Laura Downs, Using Quaternions to Represent Rotation, | CS184 at UC Berkeley | http://www.cs.berkeley.edu/~laura | | (2) Nick Bobick, Rotating Objects Using Quaternions, | Game Developer, July 3, 1998 | http://www.gamasutra.com/features/programming/19980703 |_____________________________________________________________*/ // 旋转误差 //const double DELTA_ROT=0.000001f; const double DELTA_ROT=1.0E-10; // ROTATION 相乘,返回值 = R1 * R2 // 旋转变换顺序:先执行 R1 旋转,后执行 R2 旋转 // 要求 R1 R2 先归一化 ROTATION RotationMultiply( ROTATION R1, ROTATION R2) { // 原始角度为 0 if( (R1.angle>-DELTA_ROT) && (R1.angle<DELTA_ROT) ) { return R2; } else if( (R2.angle>-DELTA_ROT) && (R2.angle<DELTA_ROT) ) { return R1; } // 原始角度不为 0 ROTATION R; QUATERNION Q1=RotationToQuaternion(R1); QUATERNION Q2=RotationToQuaternion(R2); QUATERNION Q = Q2*Q1; // 注意顺序 R=QuaternionToRotation(Q); return R; } ROTATION operator * ( ROTATION R1, ROTATION R2) { return RotationMultiply(R1, R2); } // V 经过 R 变换后为 V', 函数返回 V' // 要求 R 先归一化 Coord VectorTransform(const Coord V, const ROTATION R) { if( (R.angle>-DELTA_ROT) && (R.angle<DELTA_ROT) ) return V; QUATERNION Q; Q=RotationToQuaternion(R); return VectorTransform(V, Q); } // 将 ROTATION 结构表示成 Matrix // 要求 R 先归一化 void RotationToMatrix(double M[16], const ROTATION R) { if( (R.angle>-DELTA_ROT) && (R.angle<DELTA_ROT) ) { M[0] = M[5] = M[10] = M[15] = 1.0; M[1] = M[2] = M[3] = M[4] = M[6] = M[7] = M[8] = M[9] = M[11] = M[12] = M[13] = M[14] = 0.0; return ; } else QuaternionToMatrix(M, RotationToQuaternion(R)); } /*_______________ 不想了解四元组细节的程序员不必往下看 _____________________*/ // 四元组求模,返回值 = |A| double QuaternionMagnitude(const QUATERNION A) { return double(sqrt(A.x*A.x + A.y*A.y + A.z*A.z +A.w*A.w)); } // 四元组归一化 // 如果 |A|=0,输出值 = A;输出值 = A/(|A|) void QuaternionNormalize(QUATERNION *A) { double magnitude = double(sqrt(A->x*A->x + A->y*A->y + A->z*A->z +A->w*A->w)); if(magnitude >= DELTA_ROT) { A->x = A->x/magnitude; A->y = A->y/magnitude; A->z = A->z/magnitude; A->w = A->w/magnitude; } } // 四元组求逆 // 如果 |A|=0,输出值 = A;否则输出值 = A 的逆 void QuaternionInverse(QUATERNION *A) { double magnitude2 = A->x*A->x + A->y*A->y + A->z*A->z + A->w*A->w; if(magnitude2 >= DELTA_ROT) { A->x = -A->x/magnitude2; A->y = -A->y/magnitude2; A->z = -A->z/magnitude2; A->w = A->w/magnitude2; } } // 四元组共扼,输出值 = A 的共扼 void QuaternionConjugate(QUATERNION *A) { A->x = -A->x; A->y = -A->y; A->z = -A->z; } // 四元组相加,返回值 = A + B QUATERNION QuaternionAdd(const QUATERNION A, const QUATERNION B) { QUATERNION Q; Q.x = A.x + B.x; Q.y = A.y + B.y; Q.z = A.z + B.z; Q.w = A.w + B.w; return Q; } QUATERNION operator+(const QUATERNION A, const QUATERNION B) { QUATERNION Q; Q.x = A.x + B.x; Q.y = A.y + B.y; Q.z = A.z + B.z; Q.w = A.w + B.w; return Q; } // 四元组相减,返回值 = A - B QUATERNION QuaternionSub(const QUATERNION A, const QUATERNION B) { QUATERNION Q; Q.x = A.x - B.x; Q.y = A.y - B.y; Q.z = A.z - B.z; Q.w = A.w - B.w; return Q; } QUATERNION operator-(const QUATERNION A, const QUATERNION B) { QUATERNION Q; Q.x = A.x - B.x; Q.y = A.y - B.y; Q.z = A.z - B.z; Q.w = A.w - B.w; return Q; } // 四元组缩放,返回值 = s * A QUATERNION QuaternionScale(const QUATERNION A, const double s) { QUATERNION Q; Q.x = s * A.x; Q.y = s * A.y; Q.z = s * A.z; Q.w = s * A.w; return Q; } QUATERNION operator * (const QUATERNION A, const double s) { QUATERNION Q; Q.x = s * A.x; Q.y = s * A.y; Q.z = s * A.z; Q.w = s * A.w; return Q; } QUATERNION QuaternionScale(const double s, const QUATERNION A) { QUATERNION Q; Q.x = s * A.x; Q.y = s * A.y; Q.z = s * A.z; Q.w = s * A.w; return Q; } QUATERNION operator * (const double s, const QUATERNION A) { QUATERNION Q; Q.x = s * A.x; Q.y = s * A.y; Q.z = s * A.z; Q.w = s * A.w; return Q; } // 四元组相乘,返回值 = q1 * q2 QUATERNION QuaternionMultiply(const QUATERNION q1, const QUATERNION q2) { // 林锐编写,已测试正确 QUATERNION Q; Q.x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y; Q.y = q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z; Q.z = q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x; Q.w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z; return Q; } // 四元组相乘,返回值 = q1 * q2 QUATERNION operator * (const QUATERNION q1, const QUATERNION q2) { // 林锐编写,已测试正确 QUATERNION Q; Q.x = q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y; Q.y = q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z; Q.z = q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x; Q.w = q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z; return Q; /* // 林锐编写,已测试正确 double s, s1, s2; Coord v, v1, v2; s1 = q1.w; s2 = q2.w; v1.x=q1.x; v1.y=q1.y; v1.z=q1.z; v2.x=q2.x; v2.y=q2.y; v2.z=q2.z; s = s1*s2 - v1^v2; v = s1*v2 + s2*v1 + v1*v2; QUATERNION Q; Q.w= s; Q.x= v.x; Q.y= v.y; Q.z= v.z; return Q; */ /* // Jeff Lander 编写,变成了 Q2*Q1 QUATERNION Q; Q.x = q2.w * q1.x + q2.x * q1.w + q2.y * q1.z - q2.z * q1.y; Q.y = q2.w * q1.y + q2.y * q1.w + q2.z * q1.x - q2.x * q1.z; Q.z = q2.w * q1.z + q2.z * q1.w + q2.x * q1.y - q2.y * q1.x; Q.w = q2.w * q1.w - q2.x * q1.x - q2.y * q1.y - q2.z * q1.z; return Q; */ /* // Nick Bobick 编写,变成了 Q2*Q1 double A, B, C, D, E, F, G, H; A = (q1.w + q1.x) * (q2.w + q2.x); B = (q1.z - q1.y) * (q2.y - q2.z); C = (q1.x - q1.w) * (q2.y - q2.z); D = (q1.y + q1.z) * (q2.x - q2.w); E = (q1.x + q1.z) * (q2.x + q2.y); F = (q1.x - q1.z) * (q2.x - q2.y); G = (q1.w + q1.y) * (q2.w - q2.z); H = (q1.w - q1.y) * (q2.w + q2.z); QUATERNION Q; Q.w = B + (-E - F + G + H)/2.0f; Q.x = A - ( E + F + G + H)/2.0f; Q.y = -C + ( E - F + G - H)/2.0f; Q.z = -D + ( E - F - G + H)/2.0f; return Q; */ } // Nick Bobick 编写 // Purpose: Spherical Linear Interpolation Between two Quaternions // Arguments: Two Quaternions, blend factor QUATERNION QuaternionSlerp(const QUATERNION from, const QUATERNION to, double t) { double to1[4]; double omega, cosom, sinom, scale0, scale1; // calc cosine cosom = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w; // adjust signs (if necessary) if ( cosom <0.0 ){ cosom = -cosom; to1[0] = - to.x; to1[1] = - to.y; to1[2] = - to.z; to1[3] = - to.w; } else { to1[0] = to.x; to1[1] = to.y; to1[2] = to.z; to1[3] = to.w; } // calculate coefficients if ( (1.0 - cosom) > DELTA_ROT ) { // standard case (slerp) omega = double(acos(cosom)); sinom = double(sin(omega)); scale0 = double(sin((1.0 - t) * omega) / sinom); scale1 = double(sin(t * omega) / sinom); } else { // "from" and "to" quaternions are very close // ... so we can do a linear interpolation scale0 = 1.0f - t; scale1 = t; } // calculate final values QUATERNION res; res.x = scale0 * from.x + scale1 * to1[0]; res.y = scale0 * from.y + scale1 * to1[1]; res.z = scale0 * from.z + scale1 * to1[2]; res.w = scale0 * from.w + scale1 * to1[3]; return res; } /*_____________________________________________________ | | 为提高计算性能,以下变换函数均假定 | | 输入参数 R Q V 已经进行了 Normalize 处理 |_____________________________________________________*/ /*-----------------------------------------------*/ /*----------- QUATERNION — ROTATION ----------*/ // 将 ROTATION 结构表示成 QUATERNION // 假定 ROTATION 参数已经进行了归一化处理 QUATERNION RotationToQuaternion(const ROTATION R) { QUATERNION Q; double cosValue, sinValue, theta; theta = R.angle/180.0f*3.14159f; cosValue = double(cos(theta/2.0f)); sinValue = double(sin(theta/2.0f)); Q.x = sinValue*R.axis[0]; Q.y = sinValue*R.axis[1]; Q.z = sinValue*R.axis[2]; Q.w = cosValue; return Q; } // 将 QUATERNION 结构表示成 ROTATION // 假定 QUATERNION 参数已经进行了归一化处理 ROTATION QuaternionToRotation(const QUATERNION Q) { ROTATION R; if( ((Q.w>1-DELTA_ROT)&&(Q.w<1+DELTA_ROT)) || ((Q.w>-1-DELTA_ROT)&&(Q.w<-1+DELTA_ROT)) ) { R.angle=0.0f; R.axis[0]=0.0f; R.axis[1]=0.0f; R.axis[2]=1.0f; return R; } double sinValue, halfTheta; halfTheta= double(acos(Q.w)); sinValue = double(sin(halfTheta)); // assert(sinValue >= DELTA_ROT); if(sinValue <= DELTA_ROT) { R.angle=0.0f; R.axis[0]=0.0f; R.axis[1]=0.0f; R.axis[2]=1.0f; return R; } R.angle = halfTheta * 2.0f * 180.0f /3.14159f; R.axis[0] = Q.x/sinValue; R.axis[1] = Q.y/sinValue; R.axis[2] = Q.z/sinValue; // VectorNormalize(R.axis); // R.axis 必是单位矢量 return R; } /*-------------------------------------------------------------*/ /*------------------- QUATERNION — Matrix ------------------*/ // Nick Bobick 编写 // 将 Matrix 结构表示成 QUATERNION // 要求 Matrix 是一种旋转矩阵,否则不能得到正确结果 void MatrixToQuaternion(QUATERNION *quat, const double M[16]) { double tr, s, q[4]; int i, j, k; int nxt[3] = {1, 2, 0}; double m[4][4]; for(i=0; i<4; i++) for(j=0; j<4; j++) m[i][j]=M[i*4+j]; tr = m[0][0] + m[1][1] + m[2][2]; // check the diagonal if (tr > 0.0) { s = double(sqrt (tr + 1.0)); // s 为什么 != -sqrt (tr + 1.0) quat->w = s / 2.0f; s = 0.5f / s; quat->x = (m[1][2] - m[2][1]) * s; quat->y = (m[2][0] - m[0][2]) * s; quat->z = (m[0][1] - m[1][0]) * s; } else { // diagonal is negative i = 0; if (m[1][1] > m[0][0]) i = 1; if (m[2][2] > m[i][i]) i = 2; j = nxt[i]; k = nxt[j]; s = double(sqrt ((m[i][i] - (m[j][j] + m[k][k])) + 1.0f)); q[i] = s * 0.5f; if (s != 0.0f) s = 0.5f / s; q[3] = (m[j][k] - m[k][j]) * s; q[j] = (m[i][j] + m[j][i]) * s; q[k] = (m[i][k] + m[k][i]) * s; quat->x = q[0]; quat->y = q[1]; quat->z = q[2]; quat->w = q[3]; } } void MatrixToQuaternion2(QUATERNION& quat, const double R[3][3]) { double trace = 1 + R[0][0] + R[1][1] + R[2][2]; double s; if(trace > 1.0e-8) { s = sqrt(trace)*2.0; quat.x = ( R[2][1] - R[1][2] ) / s; quat.y = ( R[0][2] - R[2][0] ) / s; quat.z = ( R[1][0] - R[0][1] ) / s; quat.w = 0.25 * s; } else { if ( R[0][0] > R[1][1] && R[0][0] > R[2][2] ) { // Column 0: s = sqrt( 1.0 + R[0][0] - R[1][1] - R[2][2] ) * 2; quat.x = 0.25 * s; quat.y = (R[1][0] + R[0][1] ) / s; quat.z = (R[0][2] + R[2][0] ) / s; quat.w = (R[2][1] - R[1][2] ) / s; } else if ( R[1][1] > R[2][2] ) { // Column 1: s = sqrt( 1.0 + R[1][1] - R[0][0] - R[2][2] ) * 2; quat.x = (R[1][0] + R[0][1] ) / s; quat.y = 0.25 * s; quat.z = (R[2][1] + R[1][2] ) / s; quat.w = (R[0][2] - R[2][0] ) / s; } else { // Column 2: s = sqrt( 1.0 + R[2][2] - R[0][0] - R[1][1] ) * 2; quat.x = (R[0][2] + R[2][0] ) / s; quat.y = (R[2][1] + R[1][2] ) / s; quat.z = 0.25 * s; quat.w = (R[1][0] - R[0][1] ) / s; } } // if(trace > 1.0e-8) // { // s = sqrt(trace)*2.0; // quat.x = ( R[1][2] - R[2][1] ) / s; // quat.y = ( R[2][0] - R[0][2] ) / s; // quat.z = ( R[0][1] - R[1][0] ) / s; // quat.w = 0.25 * s; // } // else // { // if ( R[0][0] > R[1][1] && R[0][0] > R[2][2] ) { // Column 0: // s = sqrt( 1.0 + R[0][0] - R[1][1] - R[2][2] ) * 2; // quat.x = 0.25 * s; // quat.y = (R[0][1] + R[1][0] ) / s; // quat.z = (R[2][0] + R[0][2] ) / s; // quat.w = (R[1][2] - R[2][1] ) / s; // } else if ( R[1][1] > R[2][2] ) { // Column 1: // s = sqrt( 1.0 + R[1][1] - R[0][0] - R[2][2] ) * 2; // quat.x = (R[0][1] + R[1][0] ) / s; // quat.y = 0.25 * s; // quat.z = (R[1][2] + R[2][1] ) / s; // quat.w = (R[2][0] - R[0][2] ) / s; // } else { // Column 2: // s = sqrt( 1.0 + R[2][2] - R[0][0] - R[1][1] ) * 2; // quat.x = (R[2][0] + R[0][2] ) / s; // quat.y = (R[1][2] + R[2][1] ) / s; // quat.z = 0.25 * s; // quat.w = (R[0][1] - R[1][0] ) / s; // } // } } void MatrixToQuaternion(QUATERNION *quat, const double R[3][3]) { double M[16]; int i,j; for(i = 0; i < 3; i ++) for(j = 0; j < 3; j ++) M[i*4+j] = R[i][j]; M[3] = M[1*4+3] = M[2*4+3] = M[3*4+0] = M[3*4+1] = M[3*4+2] = 0.0; M[3*4+3] = 1.0; MatrixToQuaternion(quat,M); } // 将 QUATERNION 结构表示成 Matrix void QuaternionToMatrix(double M[16], const QUATERNION quat) { double m[4][4]; double wx, wy, wz, xx, yy, yz, xy, xz, zz, x2, y2, z2; // calculate coefficients x2 = quat.x * 2.0f; y2 = quat.y * 2.0f; z2 = quat.z * 2.0f; xx = quat.x * x2; xy = quat.x * y2; xz = quat.x * z2; yy = quat.y * y2; yz = quat.y * z2; zz = quat.z * z2; wx = quat.w * x2; wy = quat.w * y2; wz = quat.w * z2; m[0][0] = 1.0f - (yy + zz); m[0][1] = xy + wz; m[0][2] = xz - wy; m[0][3] = 0.0f; m[1][0] = xy - wz; m[1][1] = 1.0f - (xx + zz); m[1][2] = yz + wx; m[1][3] = 0.0f; m[2][0] = xz + wy; m[2][1] = yz - wx; m[2][2] = 1.0f - (xx + yy); m[2][3] = 0.0f; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; for(int i=0; i<4; i++) for(int j=0; j<4; j++) M[i*4+j]=m[i][j]; } void QuaternionToMatrix(double R[3][3], const QUATERNION quat) { double wx, wy, wz, xx, yy, yz, xy, xz, zz, x2, y2, z2; // calculate coefficients x2 = quat.x * 2.0f; y2 = quat.y * 2.0f; z2 = quat.z * 2.0f; xx = quat.x * x2; xy = quat.x * y2; xz = quat.x * z2; yy = quat.y * y2; yz = quat.y * z2; zz = quat.z * z2; wx = quat.w * x2; wy = quat.w * y2; wz = quat.w * z2; // Transpose // R[0][0] = 1.0f - (yy + zz); // R[1][0] = xy - wz; // R[2][0] = xz + wy; // // R[0][1] = xy + wz; // R[1][1] = 1.0f - (xx + zz); // R[2][1] = yz - wx; // // R[0][2] = xz - wy; // R[1][2] = yz + wx; // R[2][2] = 1.0f - (xx + yy); R[0][0] = 1.0f - (yy + zz); R[0][1] = xy - wz; R[0][2] = xz + wy; R[1][0] = xy + wz; R[1][1] = 1.0f - (xx + zz); R[1][2] = yz - wx; R[2][0] = xz - wy; R[2][1] = yz + wx; R[2][2] = 1.0f - (xx + yy); } // 将 QUATERNION 结构表示成 Matrix // The matrix is represented in a column major format (OpenGL format) void QuaternionToMatrix_OpenGL(double M[16], const QUATERNION quat) { double m[4][4]; //column major format (OpenGL format) double wx, wy, wz, xx, yy, yz, xy, xz, zz, x2, y2, z2; // calculate coefficients x2 = quat.x * 2.0f; y2 = quat.y * 2.0f; z2 = quat.z * 2.0f; xx = quat.x * x2; xy = quat.x * y2; xz = quat.x * z2; yy = quat.y * y2; yz = quat.y * z2; zz = quat.z * z2; wx = quat.w * x2; wy = quat.w * y2; wz = quat.w * z2; m[0][0] = 1.0f - (yy + zz); m[0][1] = xy - wz; m[0][2] = xz + wy; m[0][3] = 0.0f; m[1][0] = xy + wz; m[1][1] = 1.0f - (xx + zz); m[1][2] = yz - wx; m[1][3] = 0.0f; m[2][0] = xz - wy; m[2][1] = yz + wx; m[2][2] = 1.0f - (xx + yy); m[2][3] = 0.0f; m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; for(int i=0; i<4; i++) for(int j=0; j<4; j++) M[i*4+j]=m[i][j]; //column major format (OpenGL format) } /*-----------------------------------------------*/ /*----------- QUATERNION — Coord ------------*/ // 将矢量(或三维空间的一点)表示成四元组 QUATERNION VectorToQuaternion(const Coord V) { QUATERNION Q; Q.x = V[0]; Q.y = V[1]; Q.z = V[2]; Q.w = 0.0f; return Q; } // 将四元组的虚部用矢量表示 Coord QuaternionToVector(const QUATERNION Q) { Coord V; V[0] = Q.x; V[1] = Q.y; V[2] = Q.z; return V; } // V 经过 Q 变换后为 V', 函数返回 V' Coord VectorTransform(const Coord V, const QUATERNION Q) { if( ((Q.w>1-DELTA_ROT)&&(Q.w<1+DELTA_ROT)) || ((Q.w>-1-DELTA_ROT)&&(Q.w<-1+DELTA_ROT)) ) return V; QUATERNION A, B, C; A=VectorToQuaternion(V); B=Q; QuaternionInverse(&B); C=Q*A*B; return QuaternionToVector(C); }
[ [ [ 1, 728 ] ] ]
1b4567f02d44aaef46e934d1b89d7ce05466fd49
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/rawhid/pjrc_rawhid_unix.cpp
fc2437679d10afc8dba71f436a7f28f50a9a4315
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,809
cpp
/* @file pjrc_rawhid_unix.cpp * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup RawHIDPlugin Raw HID Plugin * @{ * @brief Impliments a HID USB connection to the flight hardware as a QIODevice *****************************************************************************/ /* Simple Raw HID functions for Linux - for use with Teensy RawHID example * http://www.pjrc.com/teensy/rawhid.html * Copyright (c) 2009 PJRC.COM, LLC * * rawhid_open - open 1 or more devices * rawhid_recv - receive a packet * rawhid_send - send a packet * rawhid_close - close a device * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above description, website URL and copyright notice and this permission * notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Version 1.0: Initial Release */ #include "pjrc_rawhid.h" #include <usb.h> #include <QDebug> #include <QString> typedef struct hid_struct hid_t; static hid_t *first_hid; static hid_t *last_hid; struct hid_struct { usb_dev_handle *usb; int open; int iface; int ep_in; int ep_out; struct hid_struct *prev; struct hid_struct *next; }; static void add_hid(hid_t *h); static hid_t * get_hid(int num); static void free_all_hid(void); static void hid_close(hid_t *hid); static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end); #define printf qDebug pjrc_rawhid::pjrc_rawhid() { first_hid = NULL; last_hid = NULL; } // open - open 1 or more devices // // Inputs: // max = maximum number of devices to open // vid = Vendor ID, or -1 if any // pid = Product ID, or -1 if any // usage_page = top level usage page, or -1 if any // usage = top level usage number, or -1 if any // Output: // actual number of devices opened // int pjrc_rawhid::open(int max, int vid, int pid, int usage_page, int usage) { struct usb_bus *bus; struct usb_device *dev; struct usb_interface *iface; struct usb_interface_descriptor *desc; struct usb_endpoint_descriptor *ep; usb_dev_handle *u; uint8_t buf[1024], *p; int i, n, len, tag, ep_in, ep_out, count=0, claimed; uint32_t val=0, parsed_usage, parsed_usage_page; hid_t *hid; if (first_hid) free_all_hid(); //printf("pjrc_rawhid_open, max=%d\n", max); if (max < 1) return 0; usb_init(); usb_find_busses(); usb_find_devices(); for (bus = usb_get_busses(); bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->next) { if (vid > 0 && dev->descriptor.idVendor != vid) continue; if (pid > 0 && dev->descriptor.idProduct != pid) continue; if (!dev->config) continue; if (dev->config->bNumInterfaces < 1) continue; printf("device: vid=%04X, pic=%04X, with %d iface\n", dev->descriptor.idVendor, dev->descriptor.idProduct, dev->config->bNumInterfaces); iface = dev->config->interface; u = NULL; claimed = 0; for (i=0; i<dev->config->bNumInterfaces && iface; i++, iface++) { desc = iface->altsetting; if (!desc) continue; printf(" type %d, %d, %d\n", desc->bInterfaceClass, desc->bInterfaceSubClass, desc->bInterfaceProtocol); if (desc->bInterfaceClass != 3) continue; if (desc->bInterfaceSubClass != 0) continue; if (desc->bInterfaceProtocol != 0) continue; ep = desc->endpoint; ep_in = ep_out = 0; for (n = 0; n < desc->bNumEndpoints; n++, ep++) { if (ep->bEndpointAddress & 0x80) { if (!ep_in) ep_in = ep->bEndpointAddress & 0x7F; printf(" IN endpoint %d\n", ep_in); } else { if (!ep_out) ep_out = ep->bEndpointAddress; printf(" OUT endpoint %d\n", ep_out); } } if (!ep_in) continue; if (!u) { u = usb_open(dev); if (!u) { printf(" unable to open device\n"); break; } } printf(" hid interface (generic)\n"); if (usb_get_driver_np(u, i, (char *)buf, sizeof(buf)) >= 0) { printf(" in use by driver \"%s\"\n", buf); if (usb_detach_kernel_driver_np(u, i) < 0) { printf(" unable to detach from kernel\n"); continue; } } if (usb_claim_interface(u, i) < 0) { printf(" unable claim interface %d\n", i); continue; } len = usb_control_msg(u, 0x81, 6, 0x2200, i, (char *)buf, sizeof(buf), 250); printf(" descriptor, len=%d\n", len); if (len < 2) { usb_release_interface(u, i); continue; } p = buf; parsed_usage_page = parsed_usage = 0; while ((tag = hid_parse_item(&val, &p, buf + len)) >= 0) { printf(" tag: %X, val %X\n", tag, val); if (tag == 4) parsed_usage_page = val; if (tag == 8) parsed_usage = val; if (parsed_usage_page && parsed_usage) break; } if ((!parsed_usage_page) || (!parsed_usage) || (usage_page > 0 && parsed_usage_page != (uint32_t)usage_page) || (usage > 0 && parsed_usage != (uint32_t)usage)) { usb_release_interface(u, i); continue; } hid = (struct hid_struct *)malloc(sizeof(struct hid_struct)); if (!hid) { usb_release_interface(u, i); continue; } hid->usb = u; hid->iface = i; hid->ep_in = ep_in; hid->ep_out = ep_out; hid->open = 1; add_hid(hid); claimed++; count++; if (count >= max) return count; } if (u && !claimed) usb_close(u); } } return count; } // recveive - receive a packet // Inputs: // num = device to receive from (zero based) // buf = buffer to receive packet // len = buffer's size // timeout = time to wait, in milliseconds // Output: // number of bytes received, or -1 on error // int pjrc_rawhid::receive(int num, void *buf, int len, int timeout) { hid_t *hid; int r; hid = get_hid(num); if (!hid || !hid->open) return -1; r = usb_interrupt_read(hid->usb, hid->ep_in, (char *)buf, len, timeout); if (r >= 0) return r; if (r == -110) return 0; // timeout return -1; } // send - send a packet // Inputs: // num = device to transmit to (zero based) // buf = buffer containing packet to send // len = number of bytes to transmit // timeout = time to wait, in milliseconds // Output: // number of bytes sent, or -1 on error // int pjrc_rawhid::send(int num, void *buf, int len, int timeout) { hid_t *hid; hid = get_hid(num); if (!hid || !hid->open) return -1; if (hid->ep_out) { return usb_interrupt_write(hid->usb, hid->ep_out, (char *)buf, len, timeout); } else { return usb_control_msg(hid->usb, 0x21, 9, 0, hid->iface, (char *)buf, len, timeout); } } // getserial - get the serialnumber of the device // // Inputs: // num = device to close (zero based) // buf = buffer to read the serialnumber into // Output // number of bytes in found, or -1 on error // QString pjrc_rawhid::getserial(int num) { hid_t *hid; char buf[128]; hid = get_hid(num); if (!hid || !hid->open) return QString(""); int retlen = usb_get_string_simple(hid->usb, 3, buf, 128); return QString().fromAscii(buf,-1); } // close - close a device // // Inputs: // num = device to close (zero based) // Output // (nothing) // void pjrc_rawhid::close(int num) { hid_t *hid; hid = get_hid(num); if (!hid || !hid->open) return; hid_close(hid); } // // // Private Functions // // // Chuck Robey wrote a real HID report parser // ([email protected]) [email protected] // http://people.freebsd.org/~chuckr/code/python/uhidParser-0.2.tbz // this tiny thing only needs to extract the top-level usage page // and usage, and even then is may not be truly correct, but it does // work with the Teensy Raw HID example. static int hid_parse_item(uint32_t *val, uint8_t **data, const uint8_t *end) { const uint8_t *p = *data; uint8_t tag; int table[4] = {0, 1, 2, 4}; int len; if (p >= end) return -1; if (p[0] == 0xFE) { // long item, HID 1.11, 6.2.2.3, page 27 if (p + 5 >= end || p + p[1] >= end) return -1; tag = p[2]; *val = 0; len = p[1] + 5; } else { // short item, HID 1.11, 6.2.2.2, page 26 tag = p[0] & 0xFC; len = table[p[0] & 0x03]; if (p + len + 1 >= end) return -1; switch (p[0] & 0x03) { case 3: *val = p[1] | (p[2] << 8) | (p[3] << 16) | (p[4] << 24); break; case 2: *val = p[1] | (p[2] << 8); break; case 1: *val = p[1]; break; case 0: *val = 0; break; } } *data += len + 1; return tag; } static void add_hid(hid_t *h) { if (!first_hid || !last_hid) { first_hid = last_hid = h; h->next = h->prev = NULL; return; } last_hid->next = h; h->prev = last_hid; h->next = NULL; last_hid = h; } static hid_t * get_hid(int num) { hid_t *p; for (p = first_hid; p && num > 0; p = p->next, num--) ; return p; } static void free_all_hid(void) { hid_t *p, *q; for (p = first_hid; p; p = p->next) { hid_close(p); } p = first_hid; while (p) { q = p; p = p->next; free(q); } first_hid = last_hid = NULL; } static void hid_close(hid_t *hid) { hid_t *p; int others=0; usb_release_interface(hid->usb, hid->iface); for (p = first_hid; p; p = p->next) { if (p->open && p->usb == hid->usb) others++; } if (!others) usb_close(hid->usb); hid->usb = NULL; }
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 365 ] ] ]
55d81664f7eaaed6721999b048bca4f3c63a3135
89147ec4f5c9a5cf4ad59c83517da2179a2f040e
/christmas lights/clights.cpp
1ffb48f32572e09eac61e2c6081199304b128034
[]
no_license
swarnaprakash/my-acm-problemset
3f977867a6637a28b486021634e30efabe30ef52
e07654590c2691839b01291e5237082971b8cc85
refs/heads/master
2016-09-05T10:39:59.726651
2011-09-04T15:01:01
2011-09-04T15:01:01
2,323,366
0
0
null
null
null
null
UTF-8
C++
false
false
478
cpp
#include<iostream> #include<map> using namespace std; main() { int l,r,ns,nq,i,q; while(1) { cin>>ns>>nq; if(ns==0 & nq==0) break; map<int,int> p; map<int,int>::iterator it; for(i=0;i<ns;++i) { cin>>l>>r; p[l]++; p[r+1]--; } for(i=0;i<nq;++i) { cin>>q; int s=0; for(it=p.begin();it!=p.end() && it->first<=q;++it) s+=it->second; if(s%2==0) cout<<"NO"<<endl; else cout<<"YES"<<endl; } cout<<endl; } return 0; }
[ [ [ 1, 44 ] ] ]
2481a1bf39e53dbb39c069d7ce9a15470ccad24f
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/Common/Scd/XYLib/2D_POLY.H
58691ffb240df9672a0e8155d747776dfb9446f9
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,693
h
//================== SysCAD - Copyright Kenwalt (Pty) Ltd =================== // $Nokeywords: $ //=========================================================================== // SysCAD Copyright Kenwalt (Pty) Ltd 1992 #ifndef __2D_POLY_H #define __2D_POLY_H #ifdef __2D_POLY_CPP #define DllImportExport DllExport #elif !defined(XYLIB) #define DllImportExport DllImport #else #define DllImportExport #endif //============================================================================ const long C2DPolyMaxOrder = 9; //============================================================================ DEFINE_TAGOBJ(C2DPoly); class DllImportExport C2DPoly : public C2DModel { public: static pchar ParmDescs[C2DPolyMaxOrder+1]; long Order; //n'th order of polynomial public: C2DPoly(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach); virtual ~C2DPoly(); virtual void CopyModel(pC2DPoly pMd); virtual void Clear(); virtual void BuildDataDefn(DataDefnBlk & DDB); virtual flag DataXchg(DataChangeBlk &DCB); virtual flag InitParms(flag DoIt); virtual double Yx(double Xi); virtual flag ReFit(); virtual pchar GetParmDesc(long i) { return ParmDescs[i]; }; // FxdEdtBookRef Overrides virtual void Build(flag bShowEqn); virtual void Load(FxdEdtInfo &EI, Strng & Str); virtual long Parse(FxdEdtInfo &EI, Strng & Str); virtual long ButtonPushed(FxdEdtInfo &EI, Strng & Str); void SetOrder(long nOrder); }; // =========================================================================== #undef DllImportExport #endif
[ [ [ 1, 54 ] ] ]
52e6532b648203a88ee5a0d73e6c546aa0985078
6712f8313dd77ae820aaf400a5836a36af003075
/readEntries.cpp
05c5bb41310f4d7803a3784a2816e00acb76ae07
[]
no_license
AdamTT1/bdScript
d83c7c63c2c992e516dca118cfeb34af65955c14
5483f239935ec02ad082666021077cbc74d1790c
refs/heads/master
2021-12-02T22:57:35.846198
2010-08-08T22:32:02
2010-08-08T22:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include <time.h> #include <stdio.h> #include "entryFlash.h" int main( int argc, char const * const argv[] ){ if( 2 <= argc ){ char const * const mtdName = argv[1]; struct tagAndCount_t tc = {0}; mtdCircular_t mtdDev(mtdName,&tc,validate_flash_entry_line); if( mtdDev.isOpen() ){ struct tm tm ; localtime_r(&tc.when_, &tm); char time_buf[80]; strftime(time_buf,sizeof(time_buf),"%Y-%m-%d %H:%M:%S", &tm); printf( "%s: %s, count %u\n", time_buf, tc.tag_, tc.numEntries_ ); } else perror(mtdName); } else fprintf( stderr, "Usage: %s /dev/mtdx\n", argv[0]); return 0 ; }
[ "ericn@ericsony.(none)" ]
[ [ [ 1, 22 ] ] ]
570b37400a2f6f09ed197979e79f6c93a3eae52c
a7ead79a090d7d83eabc22d7ec633368de06b989
/client/CliUser.cpp
cec39e1aa6cee94e07f08f192d0cdeeff5f9af33
[]
no_license
rjp/qUAck
0fd7a189c41cb30363bea5947816c9c234f40169
78216295097806938c792466eab509460f9cf33a
refs/heads/master
2020-06-06T14:34:41.579463
2010-08-25T11:01:29
2010-08-25T11:01:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,982
cpp
/* ** UNaXcess Conferencing System ** (c) 1998 Michael Wood ([email protected]) ** ** Concepts based on Bradford UNaXcess (c) 1984-87 Brandon S Allbery ** Extensions (c) 1989, 1990 Andrew G Minter ** Manchester UNaXcess extensions by Rob Partington, Gryn Davies, ** Michael Wood, Andrew Armitage, Francis Cook, Brian Widdas ** ** The look and feel was reproduced. No code taken from the original ** UA was someone else's inspiration. Copyright and 'nuff respect due ** ** CliUser.cpp: Implementation of common user functions */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <time.h> #include "EDF/EDF.h" #include "ua.h" #include "CliUser.h" // UserGet: Find a given user // iUserID - ID of the user to search for // iSearchType - Flag for which search (0 = use szUserName, 1 = use iUserID) // bReset - Flag for temporary position setting bool UserGet(EDF *pData, int *iUserID, char **szUserName, int iSearchType, bool bReset, long lDate) { STACKTRACE int iUserEDF = -1; long lDateEDF = 0; char *szUserEDF = NULL; bool bLoop = true, bFound = false, bGetCopy = false; if((iSearchType == 0 && (szUserName == NULL || *szUserName == NULL)) || (iSearchType == 1 && (iUserID == NULL || *iUserID <= 0))) { return false; } bGetCopy = pData->GetCopy(false); if(bReset == true) { // Mark position for reset pData->TempMark(); } /* if(lDate != -1) { debug("UserGet userid %d (date %ld)\n", *iUserID, lDate); } */ // Move to first user pData->Root(); pData->Child("users"); bLoop = pData->Child("user"); while(bFound == false && bLoop == true) { if(lDate != -1 || pData->GetChildBool("deleted") == false) { if(iSearchType == 0) { // Search by name pData->GetChild("name", &szUserEDF); if(stricmp(*szUserName, szUserEDF) == 0) { // Set user ID return pData->Get(NULL, iUserID); strcpy(*szUserName, szUserEDF); bFound = true; } } else { // Search by ID pData->Get(NULL, &iUserEDF); if(*iUserID == iUserEDF) { if(szUserName != NULL) { // Set user name return /* if(lDate != -1) { EDFPrint("UserGet historical pre check", pData, false); } */ pData->Child("name", EDFElement::LAST); pData->Get(NULL, &szUserEDF); if(lDate != -1) { // Check historical names // printf("UserGet current name %s\n", szUserEDF); bLoop = pData->Prev("name"); while(bLoop == true) { lDateEDF = time(NULL); pData->GetChild("date", &lDateEDF); printf("UserGet historical check %ld", lDateEDF); if(lDateEDF >= lDate) { pData->Get(NULL, &szUserEDF); printf(". match %s", szUserEDF); bLoop = pData->Prev("name"); } else { bLoop = false; } printf("\n"); } // printf("UserGet historical name %s\n", szUserEDF); // EDFPrint("UserGet historial name post check", pData, false); } pData->Parent(); /* if(lDate != -1) { EDFPrint("UserGet historial name post check", pData, false); } */ *szUserName = strmk(szUserEDF); } bFound = true; } } } if(bFound == false) { // Move to next child bLoop = pData->Next("user"); } } if(bReset == true) { // Reset to marked position pData->TempUnmark(); } pData->GetCopy(bGetCopy); return bFound; } // UserGet: Get user from name (convinence function) int UserGet(EDF *pData, char *&szUserName, bool bReset) { STACKTRACE int iUserID = -1; UserGet(pData, &iUserID, &szUserName, 0, bReset, -1); return iUserID; } // UserGet: Get user from ID (convinence function) bool UserGet(EDF *pData, int iUserID, char **szUserName, bool bReset, long lDate) { STACKTRACE bool bReturn = false; bReturn = UserGet(pData, &iUserID, szUserName, 1, bReset, lDate); return bReturn; }
[ [ [ 1, 172 ] ] ]
ced8bb2b60fd6b3e9f8cbb9e525cb71a95cb7adc
54cacc105d6bacdcfc37b10d57016bdd67067383
/trunk/source/level/objects/commands/CmdBipedSetLook.cpp
c4964c19a34bfe50aabed232c3049f74917ea4db
[]
no_license
galek/hesperus
4eb10e05945c6134901cc677c991b74ce6c8ac1e
dabe7ce1bb65ac5aaad144933d0b395556c1adc4
refs/heads/master
2020-12-31T05:40:04.121180
2009-12-06T17:38:49
2009-12-06T17:38:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
867
cpp
/*** * hesperus: CmdBipedSetLook.cpp * Copyright Stuart Golodetz, 2009. All rights reserved. ***/ #include "CmdBipedSetLook.h" #include <source/axes/NUVAxes.h> #include <source/level/objects/components/ICmpOrientation.h> namespace hesp { //#################### CONSTRUCTORS #################### CmdBipedSetLook::CmdBipedSetLook(const ObjectID& objectID, const Vector3d& look) : m_objectID(objectID), m_look(look) {} //#################### PUBLIC METHODS #################### void CmdBipedSetLook::execute(const ObjectManager_Ptr& objectManager, const std::vector<CollisionPolygon_Ptr>& polygons, const OnionTree_CPtr& tree, const NavManager_CPtr& navManager, int milliseconds) { ICmpOrientation_Ptr cmpOrientation = objectManager->get_component(m_objectID, cmpOrientation); cmpOrientation->nuv_axes()->set_n(m_look); } }
[ [ [ 1, 26 ] ] ]
5d5591b94fa93fce897cd22919e9063916a1823e
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/MobiHealth/moc_PatientSearchResultsForm.cpp
5475576b315c9b4b782530d620d97fbd2263b9f6
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,332
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'PatientSearchResultsForm.h' ** ** Created: Sun Mar 14 10:40:24 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "PatientSearchResultsForm.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'PatientSearchResultsForm.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_PatientSearchResultsForm[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_PatientSearchResultsForm[] = { "PatientSearchResultsForm\0" }; const QMetaObject PatientSearchResultsForm::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_PatientSearchResultsForm, qt_meta_data_PatientSearchResultsForm, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &PatientSearchResultsForm::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *PatientSearchResultsForm::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *PatientSearchResultsForm::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_PatientSearchResultsForm)) return static_cast<void*>(const_cast< PatientSearchResultsForm*>(this)); return QWidget::qt_metacast(_clname); } int PatientSearchResultsForm::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ [ [ 1, 69 ] ] ]
a53a9d0f2808f57c23194c7dc279b0afc601f46a
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/example/cla/validation/access_unknown.cpp
2eb7362ad476566465ffebf2a8551947726a8d9d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
// (C) Copyright Gennadiy Rozental 2001-2006. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // Boost.Runtime.Param #include <boost/test/utils/runtime/cla/named_parameter.hpp> #include <boost/test/utils/runtime/cla/parser.hpp> namespace rt = boost::runtime; namespace cla = boost::runtime::cla; // STL #include <iostream> int main() { char* argv[] = { "basic", "-abcd", "25" }; int argc = sizeof(argv)/sizeof(char*); try { cla::parser P; P << cla::named_parameter<int>( "abcd" ); P.parse( argc, argv ); P["ab"]; } catch( rt::logic_error const& ex ) { std::cout << "Logic error: " << ex.msg() << std::endl; return -1; } return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 37 ] ] ]
6a528ddf2133e5433aa2a02ed018d5543c8b7b9a
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/GuiControls/IAlphaDrawer.h
adc54b3752a8da767a96e2c0d8deac3ff3d29595
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
1,396
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * 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, 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 GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #pragma once class IAlphaDrawer { public: enum DrawOptions { DO_DrawNotAlphaPerigram = 1 }; IAlphaDrawer(void) {} virtual ~IAlphaDrawer(void) {} virtual void SetColor(COLORREF col) = 0; virtual void Draw(CDC& dc, CRect& rc, BYTE Alpha) = 0; //Advanced Functions virtual CDC* GetInternalDC() = 0; virtual CRect* GetInternalRect() = 0; virtual void SetDrawOptions(UINT drawOptions) = 0; };
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 45 ] ] ]
2076ef2a53a2778c3afa3d5bfc5436f1533ae73f
6581dacb25182f7f5d7afb39975dc622914defc7
/ZCode/Utility.cpp
b6d383b8ae20af1ee4df5c57805b28ff7191024c
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,159
cpp
// Utility.cpp : Implementation of CUtility #include "stdafx.h" #include "ZCode.h" #include "Utility.h" #include "CyoEncode.h" #include "CyoDecode.h" #include "zlib.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <vector> #include <fstream> #include <map> #define TEST_BASExx(base,str,expected) \ printf( "TEST_BASE%s('%s')='%s'", #base, str, expected ); \ required = cyoBase##base##EncodeGetLength( strlen( str )); \ encoded = malloc( required ); \ if (encoded == NULL) { \ printf( "\n*** ERROR: Unable to allocate buffer for encoding ***\n" ); \ goto exit; \ } \ cyoBase##base##Encode( encoded, str, strlen( str )); \ if (strcmp( encoded, expected ) != 0) { \ printf( "\n*** ERROR: Encoding failure ***\n" ); \ goto exit; \ } \ valid = cyoBase##base##Validate( encoded, strlen( encoded )); \ if (valid < 0) \ { \ printf( "\n*** ERROR: Unable to validate encoding (error %d) ***\n", valid ); \ goto exit; \ } \ printf( " [passed]\n" ); \ free( encoded ); encoded = NULL; #define TEST_BASE64(str,expected) TEST_BASExx(64,str,expected) #define TEST_BASE32(str,expected) TEST_BASExx(32,str,expected) #define TEST_BASE16(str,expected) TEST_BASExx(16,str,expected) #define CHECK_INVALID_BASExx(base,str,res) \ printf( "CHECK_INVALID_BASE%s('%s')=%d", #base, str, res ); \ valid = cyoBase##base##Validate( str, strlen( str )); \ if (valid == 0) \ { \ printf( "\n*** ERROR: This is a valid encoding! ***\n" ); \ goto exit; \ } \ if (valid != res) \ { \ printf( "\n*** ERROR: Expected a different return code! (%d) ***\n", valid ); \ goto exit; \ } \ printf( " [passed]\n", #base, str ); \ #define CHECK_INVALID_BASE16(enc,res) CHECK_INVALID_BASExx(16,enc,res) #define CHECK_INVALID_BASE32(enc,res) CHECK_INVALID_BASExx(32,enc,res) #define CHECK_INVALID_BASE64(enc,res) CHECK_INVALID_BASExx(64,enc,res) using namespace std; ///////////////////////////////////////////////////////////////////////////// // CUtility struct Destroyer { Destroyer(char * p) : _p(p) {} ~Destroyer() { if (_p) delete[] _p; } void DestroyNow() { delete[] _p; _p = 0; } char * _p; }; STDMETHODIMP CUtility::InterfaceSupportsErrorInfo(REFIID riid) { static const IID* arr[] = { &IID_IUtility }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } STDMETHODIMP CUtility::get_Base16Table(BSTR *pVal) { // TODO: Add your implementation code here static const char* const BASE16_TABLE = "0123456789ABCDEF"; CComBSTR(BASE16_TABLE).CopyTo(pVal); return S_OK; } STDMETHODIMP CUtility::get_Base32Table(BSTR *pVal) { // TODO: Add your implementation code here static const char* const BASE32_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="; CComBSTR(BASE32_TABLE).CopyTo(pVal); return S_OK; } STDMETHODIMP CUtility::get_Base64Table(BSTR *pVal) { // TODO: Add your implementation code here static const char* const BASE64_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; CComBSTR(BASE64_TABLE).CopyTo(pVal); return S_OK; } HRESULT CUtility::reportError(HRESULT hr, const wchar_t * fmt, ...) { va_list args; va_start(args, fmt); wchar_t temp[300]; memset(temp, 0, sizeof(temp)); _vsnwprintf(temp, sizeof(temp)/sizeof(wchar_t)-1, fmt, args); if (hr == E_OUTOFMEMORY) { MEMORYSTATUS stat; GlobalMemoryStatus (&stat); wchar_t buf[100]; swprintf(buf, L"[vm: %d/%d]", stat.dwAvailVirtual, stat.dwTotalVirtual); wcscat(temp, buf); } AtlReportError(GetObjectCLSID(), temp, GUID_NULL, hr); va_end(args); return hr; } STDMETHODIMP CUtility::CompressWithBase16(BSTR Source, BSTR *pVal) { unsigned long nSrc = ::SysStringByteLen(Source); char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase16() - pSrc - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = compressBound(nSrc); char * pDest = new char[nDest]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase16() - pDest - new %d bytes failed", nDest); Destroyer ddest(pDest); int ret = compress((Bytef*)pDest, &nDest, (Bytef*)pSrc, nSrc); if (ret != Z_OK) { return reportError(E_FAIL, L"ZCode::CompressWithBase16() - compress() Error: %d", ret); } /*Encode With Base16*/ size_t required = cyoBase16EncodeGetLength( strlen( pDest )); char* pEncoded = new char[required]; if (pEncoded == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase16() - pEncoded - new %d bytes failed", required); } Destroyer dencoded(pEncoded); cyoBase16Encode( pEncoded, pDest, strlen( pDest )); /* Validate encoding */ int valid = cyoBase16Validate( pEncoded, strlen( pEncoded )); if (valid < 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase16() *** ERROR: Encoding failure (error %d) ***\n", valid ); CComBSTR(pEncoded).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"TZip::cmpr() - A2WBSTR() returns 0 for %d bytes string", required); return S_OK; } STDMETHODIMP CUtility::CompressWithBase32(BSTR Source, BSTR *pVal) { // TODO: Add your implementation code here unsigned long nSrc = ::SysStringByteLen(Source); char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase32() - pSrc - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = compressBound(nSrc); char * pDest = new char[nDest]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase32() - pDest - new %d bytes failed", nDest); Destroyer ddest(pDest); int ret = compress((Bytef*)pDest, &nDest, (Bytef*)pSrc, nSrc); if (ret != Z_OK) { return reportError(E_FAIL, L"ZCode::CompressWithBase32() - compress() Error: %d", ret); } /*Encode With Base32*/ size_t required = cyoBase32EncodeGetLength( strlen( pDest )); char* pEncoded = new char[required]; if (pEncoded == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase32() - pEncoded - new %d bytes failed", required); } Destroyer dencoded(pEncoded); cyoBase32Encode( pEncoded, pDest, strlen( pDest )); /* Validate encoding */ int valid = cyoBase32Validate( pEncoded, strlen( pEncoded )); if (valid < 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase32() *** ERROR: Encoding failure (error %d) ***\n", valid ); CComBSTR(pEncoded).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"TZip::cmpr() - A2WBSTR() returns 0 for %d bytes string", required); return S_OK; } STDMETHODIMP CUtility::CompressWithBase64(BSTR Source, BSTR *pVal) { unsigned long nSrc = ::SysStringByteLen(Source); char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase64() - pSrc - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = compressBound(nSrc); char * pDest = new char[nDest]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase64() - pDest - new %d bytes failed", nDest); Destroyer ddest(pDest); int ret = compress((Bytef*)pDest, &nDest, (Bytef*)pSrc, nSrc); if (ret != Z_OK) { return reportError(E_FAIL, L"ZCode::CompressWithBase64() - compress() Error: %d", ret); } /*Encode With Base64*/ size_t required = cyoBase64EncodeGetLength( strlen( pDest )); char* pEncoded = new char[required]; if (pEncoded == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase64() - pEncoded - new %d bytes failed", required); } Destroyer dencoded(pEncoded); cyoBase64Encode( pEncoded, pDest, strlen( pDest )); /* Validate encoding */ int valid = cyoBase64Validate( pEncoded, strlen( pEncoded )); if (valid < 0) return reportError(E_OUTOFMEMORY, L"ZCode::CompressWithBase64() *** ERROR: Encoding failure (error %d) ***\n", valid ); CComBSTR(pEncoded).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"TZip::cmpr() - A2WBSTR() returns 0 for %d bytes string", required); return S_OK; } STDMETHODIMP CUtility::DecompressWithBase16(BSTR Source, BSTR *pVal) { unsigned long nSrc = ::SysStringLen(Source); if (nSrc <= 8) return S_OK; char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase16() - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = cyoBase16DecodeGetLength( strlen( pSrc )); char * pRealSrc = new char[nDest]; if (pRealSrc == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase16() *** ERROR: Unable to allocate buffer %d for decoding ***",nDest); } cyoBase16Decode( pRealSrc, pSrc, strlen( pSrc )); Destroyer drsrc(pRealSrc); char * pDest = new char[nDest+1]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase16() - new %d bytes failed", nDest+1); Destroyer ddest(pDest); int ret = uncompress((Bytef*)pDest, &nDest, (Bytef*)pRealSrc, nSrc); if (ret == Z_OK) { pDest[nDest] = '\0'; CComBSTR(pDest).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase16() - A2WBSTR() returns 0 for %d bytes string", nDest); } else return reportError(E_FAIL, L"ZCode::DecompressWithBase16() - uncompress() Error: %d", ret); return S_OK; } STDMETHODIMP CUtility::DecompressWithBase32(BSTR Source, BSTR *pVal) { unsigned long nSrc = ::SysStringLen(Source); if (nSrc <= 8) return S_OK; char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase32() - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = cyoBase32DecodeGetLength( strlen( pSrc )); char * pRealSrc = new char[nDest]; if (pRealSrc == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase32() *** ERROR: Unable to allocate buffer %d for decoding ***",nDest); } cyoBase32Decode( pRealSrc, pSrc, strlen( pSrc )); Destroyer drsrc(pRealSrc); char * pDest = new char[nDest+1]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase32() - new %d bytes failed", nDest+1); Destroyer ddest(pDest); int ret = uncompress((Bytef*)pDest, &nDest, (Bytef*)pRealSrc, nSrc); if (ret == Z_OK) { pDest[nDest] = '\0'; CComBSTR(pDest).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase32() - A2WBSTR() returns 0 for %d bytes string", nDest); } else return reportError(E_FAIL, L"ZCode::DecompressWithBase32() - uncompress() Error: %d", ret); return S_OK; } STDMETHODIMP CUtility::DecompressWithBase64(BSTR Source, BSTR *pVal) { unsigned long nSrc = ::SysStringLen(Source); if (nSrc <= 8) return S_OK; char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase64() - new %d bytes failed", nSrc+1); Destroyer dsrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, Source, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; unsigned long nDest = cyoBase64DecodeGetLength( strlen( pSrc )); char * pRealSrc = new char[nDest]; if (pRealSrc == NULL) { return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase64() *** ERROR: Unable to allocate buffer %d for decoding ***",nDest); } cyoBase64Decode( pRealSrc, pSrc, strlen( pSrc )); Destroyer drsrc(pRealSrc); char * pDest = new char[nDest+1]; if (pDest == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase64() - new %d bytes failed", nDest+1); Destroyer ddest(pDest); int ret = uncompress((Bytef*)pDest, &nDest, (Bytef*)pRealSrc, nSrc); if (ret == Z_OK) { pDest[nDest] = '\0'; CComBSTR(pDest).CopyTo(pVal); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"ZCode::DecompressWithBase64() - A2WBSTR() returns 0 for %d bytes string", nDest); } else return reportError(E_FAIL, L"ZCode::DecompressWithBase64() - uncompress() Error: %d", ret); return S_OK; } STDMETHODIMP CUtility::CodeReplace(BSTR inTable, BSTR toTable, BSTR src, BSTR *pVal) { // TODO: Add your implementation code here unsigned long nInTable = ::SysStringLen(inTable); if (nInTable <= 8) return S_OK; char * pInTable = new char[nInTable+1]; if (pInTable == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CodeReplace() - inTable - new %d bytes failed", nInTable+1); Destroyer dInTable(pInTable); ::ZeroMemory(pInTable, sizeof(pInTable)); nInTable = ::WideCharToMultiByte(CP_ACP, 0, inTable, -1, pInTable, nInTable+1, 0, 0); if (nInTable > 0) nInTable--; unsigned long nToTable = ::SysStringLen(toTable); if (nToTable <= 8) return S_OK; char * pToTable = new char[nToTable+1]; if (pToTable == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CodeReplace() - ToTable - new %d bytes failed", nToTable+1); Destroyer dToTable(pToTable); ::ZeroMemory(pToTable, sizeof(pToTable)); nToTable = ::WideCharToMultiByte(CP_ACP, 0, toTable, -1, pToTable, nToTable+1, 0, 0); if (nToTable > 0) nToTable--; unsigned long nSrc = ::SysStringLen(src); if (nSrc <= 8) return S_OK; char * pSrc = new char[nSrc+1]; if (pSrc == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CodeReplace() - Src - new %d bytes failed", nSrc+1); Destroyer dSrc(pSrc); ::ZeroMemory(pSrc, sizeof(pSrc)); nSrc = ::WideCharToMultiByte(CP_ACP, 0, src, -1, pSrc, nSrc+1, 0, 0); if (nSrc > 0) nSrc--; std::map<char,char> replacer; for(long index=0; index <nToTable && index< nInTable; index++) replacer[*(pInTable+index)]=*(pToTable+index); std::map<char,char>::iterator iter; for(long i=0; i<nSrc; i++) { iter=replacer.find(*(pSrc+i)); if(iter!=replacer.end()) *(pSrc+i)=iter->second; } *pVal=CComBSTR(pSrc).Detach(); if (*pVal == 0) return reportError(E_OUTOFMEMORY, L"ZCode::CodeReplace() - A2WBSTR() returns 0 for %d bytes string", nSrc); return S_OK; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 485 ] ] ]
620900c09e478d8609ab2fcc6025ac7bcb63c8cf
f96efcf47a7b6a617b5b08f83924c7384dcf98eb
/trunk/rvp/RVPImpl.h
d7732d00ed52870dabebdec828adfe0c5d0fd6dc
[]
no_license
BackupTheBerlios/mtlen-svn
0b4e7c53842914416ed3f6b1fa02c3f1623cac44
f0ea6f0cec85e9ed537b89f7d28f75b1dc108554
refs/heads/master
2020-12-03T19:37:37.828462
2011-12-07T20:02:16
2011-12-07T20:02:16
40,800,938
0
0
null
null
null
null
UTF-8
C++
false
false
2,856
h
/* RVP Protocol Plugin for Miranda IM Copyright (C) 2005 Piotr Piastucki 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. */ class RVPImpl; class RVPImplAsyncData; #ifndef RVPIMPL_INCLUDED #define RVPIMPL_INCLUDED #include "rvp.h" #include "RVPClient.h" #include "ThreadManager.h" #include "List.h" class RVPImplAsyncData { private: char *message; wchar_t *messageW; public: RVPImplAsyncData(RVPImpl *); ~RVPImplAsyncData(); void setMessage(const char *); void setMessage(const wchar_t *); const char *getMessage(); const wchar_t *getMessageW(); int id; RVPImpl *impl; RVPSubscription *subscription; RVPFile *file; HANDLE hContact; int status; int oldStatus; }; class RVPImpl:public ThreadManager, public RVPClientListener { private: RVPClient* client; int oldStatus; int msgCounter; int typingCoutner; int renewCounter; int searchCounter; List *typingNotifications; public: enum THREADGROUPS { TGROUP_SIGNIN = 1, TGROUP_NORMAL = 2, TGROUP_SHUTDOWN = 4, TGROUP_SIGNOUT = 8, }; RVPImpl(); RVPClient *getClient(); void setCredentials(HTTPCredentials *c); int signIn(const char *signInName, const char *manualServer, int initialStatus); int signOut(); int signOutThreadCall(); int subscribe(HANDLE hContact); int unsubscribe(HANDLE hContact); int subscribeAll(); int unsubscribeAll(); int setStatus(int status); int sendStatus(); int sendMessage(HANDLE hContact, CCSDATA *ccs); int sendTyping(HANDLE hContact, bool on); int sendFileAccept(RVPFile *file, const char *path); int sendFileReject(RVPFile *file); int cancelFile(RVPFile *file); RVPFile *sendFileInvite(HANDLE hContact, const char * filename); int searchContact(const char *login); bool isTyping(HANDLE hContact); RVPSubscription* getProperty(const char *node, const char *property); /* RVPClientListener */ void onTyping(const char *login); void onMessage(const char *login, const char *nick, const wchar_t *message); void onStatus(const char *login, int status); void onFileInvite(const char *login, const char *nick, RVPFile *file); void onFileProgress(RVPFile *file, int type, int progress); }; #endif
[ "the_leech@3f195757-89ef-0310-a553-cc0e5972f89c" ]
[ [ [ 1, 97 ] ] ]
b18678f317c3d73adb7c8e8ccee3df673ab77f77
d64ed1f7018aac768ddbd04c5b465c860a6e75fa
/drawing_element/dle_donut.cpp
024612bc5fd2817b2b821e0800ec171be7788833
[]
no_license
roc2/archive-freepcb-codeproject
68aac46d19ac27f9b726ea7246cfc3a4190a0136
cbd96cd2dc81a86e1df57b86ce540cf7c120c282
refs/heads/master
2020-03-25T00:04:22.712387
2009-06-13T04:36:32
2009-06-13T04:36:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,143
cpp
#include "stdafx.h" #include "dle_donut.h" // annulus void CDLE_DONUT::_Draw(CDrawInfo const &di) const { if( onScreen() ) { int thick = (w - holew)/2; int ww = w - thick; int _holew = holew; int size_of_2_pixels = dlist->m_scale; if( thick < size_of_2_pixels ) { _holew = w - 2*size_of_2_pixels; if( _holew < 0 ) _holew = 0; thick = (w - _holew)/2; ww = w - thick; } if( w-_holew > 0 ) { CPen pen( PS_SOLID, thick, di.layer_color[1] ); di.DC->SelectObject( &pen ); di.DC->SelectObject( di.erase_brush ); di.DC->Ellipse( i.x - ww/2, i.y - ww/2, i.x + ww/2, i.y + ww/2 ); di.DC->SelectObject( di.line_pen ); di.DC->SelectObject( di.fill_brush ); } else { CPen backgnd_pen( PS_SOLID, 1, di.layer_color[0] ); di.DC->SelectObject( di.erase_pen ); di.DC->SelectObject( di.erase_brush ); di.DC->Ellipse( i.x - _holew/2, i.y - _holew/2, i.x + _holew/2, i.y + _holew/2 ); di.DC->SelectObject( di.line_pen ); di.DC->SelectObject( di.fill_brush ); } } } void CDLE_DONUT::_DrawClearance(CDrawInfo const &di) const { }
[ "jamesdily@9bfb2a70-7351-0410-8a08-c5b0c01ed314" ]
[ [ [ 1, 48 ] ] ]
904bcfe77932ec2cf161460da5b0aab9dbd5dd74
5e6ff9e6e8427078135a7b4d3b194bcbf631e9cd
/EngineSource/dpslim/dpslim/Database/Source/DBSegChars.cpp
394836d6a939d1930ecb590fc51f266e35ad3c49
[]
no_license
karakots/dpresurrection
1a6f3fca00edd24455f1c8ae50764142bb4106e7
46725077006571cec1511f31d314ccd7f5a5eeef
refs/heads/master
2016-09-05T09:26:26.091623
2010-02-01T11:24:41
2010-02-01T11:24:41
32,189,181
0
0
null
null
null
null
UTF-8
C++
false
false
1,103
cpp
// ---------------------- // // Created 11/20/200 // Vicki de Mey, DecisionPower, Inc. // #include <afxdb.h> // MFC ODBC database classes ///////////////////////////////////////////////////////////////////////////// // Product recordset class ProductRecordset : public CRecordset { public: ProductRecordset(CDatabase* pDatabase = NULL); DECLARE_DYNAMIC(ProductRecordset) // Field/Param Data //{{AFX_FIELD(ProductRecordset, CRecordset) long m_ProductID; CString m_ProductName; //}}AFX_FIELD // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(ProductRecordset) public: virtual CString GetDefaultConnect(); // Default connection string virtual CString GetDefaultSQL(); // Default SQL for Recordset virtual void DoFieldExchange(CFieldExchange* pFX); // RFX support virtual int Open(unsigned int nOpenType = snapshot, LPCTSTR lpszSql = NULL, DWORD dwOptions = none); //}}AFX_VIRTUAL // Implementation #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif };
[ "Isaac.Noble@fd82578e-0ebe-11df-96d9-85c6b80b8d9c" ]
[ [ [ 1, 41 ] ] ]
9c56a02c9eee615438c87180f1b673137409ab19
f78d9c67f1785c436050d3c1ca40bf4253501717
/Sky.cpp
0bbc3b9c4f705a731725f3b0b5f817e75c5ff645
[]
no_license
elcerdo/pixelcity
0cdafbd013994475cd1db5919807f4e537d58b4c
aafecd6bd344ec79298d8aaf0c08426934fc2049
refs/heads/master
2021-01-10T22:06:18.964202
2009-05-13T19:15:40
2009-05-13T19:15:40
194,478
3
1
null
null
null
null
UTF-8
C++
false
false
3,667
cpp
/*----------------------------------------------------------------------------- Sky.cpp 2009 Shamus Young ------------------------------------------------------------------------------- Did this need to be written as a class? It did not. There will never be more than one sky in play, so the whole class structure here is superflous, but harmless. -----------------------------------------------------------------------------*/ #define SKYPOINTS 24 #include <cmath> #include <GL/gl.h> #include "Camera.h" #include "Macro.h" #include "Math.h" #include "Random.h" #include "Render.h" #include "Sky.h" #include "Texture.h" #include "World.h" #include "glTypes.h" static CSky* sky; /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void SkyRender () { if (sky && !RenderFlat ()) sky->Render (); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void SkyClear () { if(sky) delete sky; sky = NULL; } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CSky::Render () { GLvector angle, position; if (!RenderFog ()) return; glDepthMask (false); glPushAttrib (GL_POLYGON_BIT | GL_FOG_BIT); glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); glDisable (GL_FOG); glDisable (GL_CULL_FACE); glPushMatrix (); glLoadIdentity(); angle = CameraAngle (); position = CameraPosition (); glRotatef (angle.x, 1.0f, 0.0f, 0.0f); glRotatef (angle.y, 0.0f, 1.0f, 0.0f); glRotatef (angle.z, 0.0f, 0.0f, 1.0f); glTranslatef (0.0f, -position.y / 100.0f, 0.0f); glEnable (GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, TextureId (TEXTURE_SKY)); glCallList (m_list); glEnable (GL_BLEND); glBindTexture(GL_TEXTURE_2D, TextureId (TEXTURE_CLOUDS)); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glCallList (m_list); glPopMatrix (); glPopAttrib (); glDepthMask (true); glEnable (GL_COLOR_MATERIAL); } /*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CSky::CSky () { GLvertex circle[SKYPOINTS]; GLvector pos; float angle; int i; float size; float rad; float lum; size = 10.0f; for (i = 0; i < SKYPOINTS; i++) { angle = (float)i / (float)(SKYPOINTS - 1); angle *= 360; angle *= DEGREES_TO_RADIANS; circle[i].position.x = sinf (angle) * size; circle[i].position.y = 0.1f; circle[i].position.z = cosf (angle) * size; circle[i].uv.x = ((float)i / (float)(SKYPOINTS - 1)) * 5.0f; circle[i].uv.y = 0.5f; rad = ((float)i / (SKYPOINTS - 1)) * 180.0f * DEGREES_TO_RADIANS; lum = sinf (rad); lum = (float)pow (lum, 5); circle[i].color = glRgba (lum); } m_list = glGenLists(1); glNewList (m_list, GL_COMPILE); glColor3f (1, 1, 1); glBegin (GL_QUAD_STRIP); for (i = 0; i < SKYPOINTS; i++) { glTexCoord2f (circle[i].uv.x, 0.0f); glVertex3fv (&circle[i].position.x); pos = circle[i].position; pos.y = size / 3.5f; glTexCoord2f (circle[i].uv.x, 1.0f); glVertex3fv (&pos.x); } glEnd (); glEndList(); glEndList(); sky = this; }
[ "youngshamus@c6164f88-37c5-11de-9d05-31133e6853b1", "[email protected]" ]
[ [ [ 1, 16 ], [ 28, 144 ] ], [ [ 17, 27 ], [ 145, 145 ] ] ]
aaef2abe6b5ec238c75ed9e796516eedcae77d84
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/MainMenuListView.cpp
d2a8f710d8f639cc4f9b31de77f1e0d74a90d165
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,781
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <aknviewappui.h> #include <arch.h> #include <stringloader.h> #include "MainMenuListView.h" #include "WayFinderSettings.h" #include "WayFinderConstants.h" #include "RsgInclude.h" #include "wficons.mbg" #include "wayfinder.hrh" #include "WayFinderAppUi.h" #include "PathFinder.h" #include "WFLayoutUtils.h" #include "MainMenuListContainer.h" const TInt MbmImageIds [] = { EMbmWficonsSearch, EMbmWficonsFavorites, EMbmWficonsMap }; const TInt MbmMaskIds [] = { EMbmWficonsSearch_mask, EMbmWficonsFavorites_mask, EMbmWficonsMap_mask }; //This int array has to end with -1 so the container knows how //many items we should have in the grid. const TInt MainMenuCommandIds [] = { EWayFinderCmdCSMainView, EWayFinderCmdMyDest, EWayFinderCmdMap, -1 }; const TInt MainMenuFirstLabelIds [] = { R_MM_SEARCH, R_MM_FAVORITES, R_MM_MAP }; const TInt MainMenuSecondLabelIds [] = { R_MM_SEARCH_SUBTITLE, R_MM_FAVORITES_SUBTITLE, R_MM_MAP_SUBTITLE }; CMainMenuListView* CMainMenuListView::NewL(CWayFinderAppUi* aWayFinderAppUi) { CMainMenuListView* self = CMainMenuListView::NewLC(aWayFinderAppUi); CleanupStack::Pop(self); return self; } CMainMenuListView* CMainMenuListView::NewLC(CWayFinderAppUi* aWayFinderAppUi) { CMainMenuListView* self = new (ELeave) CMainMenuListView(aWayFinderAppUi); CleanupStack::PushL(self); self->ConstructL(); return self; } CMainMenuListView::CMainMenuListView(CWayFinderAppUi* aWayFinderAppUi) : CViewBase(aWayFinderAppUi), iSelectedItem(0) { } void CMainMenuListView::ConstructL() { BaseConstructL(R_WAYFINDER_MAIN_MENU_LIST_VIEW); } CMainMenuListView::~CMainMenuListView() { if (iContainer) { AppUi()->RemoveFromViewStack(*this, iContainer); } delete iContainer; } TPtrC CMainMenuListView::GetMbmName() { return iWayfinderAppUi->iPathManager->GetMbmName(); } void CMainMenuListView::SetNaviPaneLabelL(TInt aLabelId) { iWayfinderAppUi->SetMainMenuNaviPaneLabelL(MainMenuFirstLabelIds[aLabelId]); } void CMainMenuListView::ResetNaviPaneLabelL() { SetNaviPaneLabelL(iSelectedItem); } // void CMainMenuListView::HandleCommandL(const class CWAXParameterContainer& aCont) // { // iWayfinderAppUi->ClearBrowserCache(); // iWayfinderAppUi->GotoStartViewL(); // } TUid CMainMenuListView::Id() const { return KMainMenuViewId; } void CMainMenuListView::HandleCommandL( TInt aCommand ) { switch (aCommand) { case EWayFinderCmdStartPageOpen: { iContainer->ActivateSelection(); break; } case EWayFinderPublishMyPosition: { iWayfinderAppUi->SendTrackingLevel(isab::GuiProtEnums::tracking_level_live); break; } case EWayFinderStopPublishMyPosition: { iWayfinderAppUi->SendTrackingLevel(0); break; } default: { iSelectedItem = iContainer->GetActiveSelection(); AppUi()->HandleCommandL(aCommand); break; } } } void CMainMenuListView::HandleClientRectChange() { if (iContainer) { iContainer->SetRect(ClientRect()); } } void CMainMenuListView::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane) { AppUi()->DynInitMenuPaneL(aResourceId, aMenuPane); } void CMainMenuListView::DoActivateL(const TVwsViewId& aPrevViewId, TUid aCustomMessageId, const TDesC8& aCustomMessage) { CViewBase::DoActivateL(aPrevViewId, aCustomMessageId, aCustomMessage); iWayfinderAppUi->ActivateMainMenuNaviPaneLabelL(); HBufC* titleText = StringLoader::LoadLC(R_TITLEPANE_NAVIGATION_TEXT); iWayfinderAppUi->setTitleText(titleText->Des()); CleanupStack::PopAndDestroy(titleText); if(!iContainer) { iContainer = CMainMenuListContainer::NewL(ClientRect(), this, MbmImageIds, MbmMaskIds, MainMenuCommandIds, MainMenuFirstLabelIds, MainMenuSecondLabelIds); AppUi()->AddToStackL(*this, iContainer); } iContainer->SetActiveSelection(iSelectedItem); SetNaviPaneLabelL(iContainer->GetActiveSelection()); // check for new versions of software iWayfinderAppUi->GenerateEvent(CWayFinderAppUi::EWayfinderEventCheckAndShowUpgradeDialog); } void CMainMenuListView::DoDeactivate() { iWayfinderAppUi->DeactivateMainMenuNaviPaneLabelL(); if (iContainer) { AppUi()->RemoveFromViewStack(*this, iContainer); } delete iContainer; iContainer = NULL; } void CMainMenuListView::UpdateActiveSelection() { //iSelectedItem = aSelectedItem; if(iContainer) { iContainer->SetActiveSelection(iSelectedItem); SetNaviPaneLabelL(iSelectedItem); } } void CMainMenuListView::UpdateSelectedIndex(TInt aIndex) { iSelectedItem = aIndex; } TInt CMainMenuListView::GetSelectedIndex() { return iSelectedItem; }
[ [ [ 1, 215 ] ] ]
3744efee698e8422012b36235ae1006fd3ce8f47
b822313f0e48cf146b4ebc6e4548b9ad9da9a78e
/KylinSdk/Engine/Source/Debug.h
5b3855787f8314e33853b1709839683a6c1aff45
[]
no_license
dzw/kylin001v
5cca7318301931bbb9ede9a06a24a6adfe5a8d48
6cec2ed2e44cea42957301ec5013d264be03ea3e
refs/heads/master
2021-01-10T12:27:26.074650
2011-05-30T07:11:36
2011-05-30T07:11:36
46,501,473
0
0
null
null
null
null
UTF-8
C++
false
false
486
h
#pragma once namespace Kylin { class DebugLine { public: DebugLine(); virtual ~DebugLine(); // KBOOL GetVisible(); // KVOID SetVisible(KBOOL bFlag); // // KBOOL GetCloseFlag(); // KVOID SetCloseFlag(KBOOL bFlag); // // KVOID SetLineColor(KColor kColor); // KColor GetLineColor(); // // KVOID AddPoint(KPoint3 kPos); // // KVOID Clear(); // // public: // virtual KVOID Draw(KFLOAT fElapsed); protected: }; }
[ [ [ 1, 33 ] ] ]
fe0505c1a7cdaeec418c0070d18d9f5dec9616ca
90e001b00ae30ef22a3b07f6c9c374b0f2a1ee65
/Computer Code/main.cpp
39bf0fdf4abb39f5b02eefb50162806fbf022572
[]
no_license
yazaddaruvala/2010W_UBC_EECE_375_450_Team6
6ca20eacef048a770e4422b45b49cedac8d6efe9
e87918415ac41c7953f67247d6b9d3ce12f6e95a
refs/heads/master
2016-09-11T04:20:55.171140
2011-05-29T08:32:43
2011-05-29T08:32:43
1,816,632
2
0
null
null
null
null
UTF-8
C++
false
false
1,084
cpp
/* * Written by Yazad Daruvala */ #include <cv.h> #include <highgui.h> using namespace cv; #include <boost/thread.hpp> #include "FrameCapturer.h" #include "RobotMover.h" #include "ProjectGUI.h" #include "ImageProcessor.h" #include "PathFinder.h" #define SERIAL_PORT "COM5" #define BALL_LOWER_BOUND cvScalar(24, 126, 91) //Ball Hopefully #define BALL_UPPER_BOUND cvScalar(77, 157, 150) //Ball Hopefully int main(){ FrameCapturer * capture = new FrameCapturer( "http://137.82.120.10:8008.mjpeg" ); RobotMover * robo = new RobotMover( SERIAL_PORT ); ProjectGUI * guiGUI = new ProjectGUI( capture ); guiGUI->start(); ImageProcessor * processor = new ImageProcessor( capture ); PathFinder * pather = new PathFinder( robo ); char key = '\0'; cvWaitKey(0); while ((key = cvWaitKey(1000/1000)) != 27){ processor->process(); guiGUI->updateOverlay( processor ); pather->updateData( processor ); switch(key) { case 'c': //configure processor->configure(); break; default: break; } } return 0; }
[ [ [ 1, 49 ] ] ]
9dca2d87c1a43c4de1164e1a38c19f777487dcaa
ab41c2c63e554350ca5b93e41d7321ca127d8d3a
/glm/setup.hpp
cad92b65026654f33f7643993162043711604f8d
[]
no_license
burner/e3rt
2dc3bac2b7face3b1606ee1430e7ecfd4523bf2e
775470cc9b912a8c1199dd1069d7e7d4fc997a52
refs/heads/master
2021-01-11T08:08:00.665300
2010-04-26T11:42:42
2010-04-26T11:42:42
337,021
3
0
null
null
null
null
UTF-8
C++
false
false
12,232
hpp
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2008 G-Truc Creation (www.g-truc.net) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2006-11-13 // Updated : 2009-08-24 // Licence : This source is under MIT License // File : glm/setup.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_setup #define glm_setup /////////////////////////////////////////////////////////////////////////////////////////////////// // Version #define GLM_VERSION 84 #define GLM_REVISION 724 /////////////////////////////////////////////////////////////////////////////////////////////////// // Common values #define GLM_DISABLE 0x00000000 #define GLM_ENABLE 0x00000001 /////////////////////////////////////////////////////////////////////////////////////////////////// // Message #define GLM_MESSAGE_QUIET 0x00000000 #define GLM_MESSAGE_WARNING 0x00000001 #define GLM_MESSAGE_NOTIFICATION 0x00000002 #define GLM_MESSAGE_CORE 0x00000004 #define GLM_MESSAGE_EXTS 0x00000008 #define GLM_MESSAGE_SETUP 0x0000000F #define GLM_MESSAGE_ALL GLM_MESSAGE_WARNING | GLM_MESSAGE_NOTIFICATION | GLM_MESSAGE_CORE | GLM_MESSAGE_EXTS | GLM_MESSAGE_SETUP //! By default: // #define GLM_MESSAGE GLM_MESSAGE_QUIET /////////////////////////////////////////////////////////////////////////////////////////////////// // Precision #define GLM_PRECISION_NONE 0x00000000 #define GLM_PRECISION_LOWP_FLOAT 0x00000011 #define GLM_PRECISION_MEDIUMP_FLOAT 0x00000012 #define GLM_PRECISION_HIGHP_FLOAT 0x00000013 #define GLM_PRECISION_LOWP_INT 0x00001100 #define GLM_PRECISION_MEDIUMP_INT 0x00001200 #define GLM_PRECISION_HIGHP_INT 0x00001300 #define GLM_PRECISION_LOWP_UINT 0x00110000 #define GLM_PRECISION_MEDIUMP_UINT 0x00120000 #define GLM_PRECISION_HIGHP_UINT 0x00130000 /////////////////////////////////////////////////////////////////////////////////////////////////// // Use options // To disable multiple vector component names access. // GLM_USE_ONLY_XYZW // To use anonymous union to provide multiple component names access for class valType. Visual C++ only. // GLM_USE_ANONYMOUS_UNION /////////////////////////////////////////////////////////////////////////////////////////////////// // Compiler #define GLM_COMPILER_NONE 0x00000000 // Visual C++ defines #define GLM_COMPILER_VC 0x01000000 #define GLM_COMPILER_VC60 0x01000040 // unsupported #define GLM_COMPILER_VC70 0x01000080 // unsupported #define GLM_COMPILER_VC71 0x010000F0 // unsupported #define GLM_COMPILER_VC80 0x01000100 #define GLM_COMPILER_VC90 0x01000200 #define GLM_COMPILER_VC2010 0x01000400 // GCC defines #define GLM_COMPILER_GCC 0x02000000 #define GLM_COMPILER_GCC28 0x02000020 // unsupported #define GLM_COMPILER_GCC29 0x02000040 // unsupported #define GLM_COMPILER_GCC30 0x02000080 // unsupported #define GLM_COMPILER_GCC31 0x020000F0 // unsupported #define GLM_COMPILER_GCC32 0x02000100 #define GLM_COMPILER_GCC33 0x02000200 #define GLM_COMPILER_GCC34 0x02000400 #define GLM_COMPILER_GCC35 0x02000800 #define GLM_COMPILER_GCC40 0x02000F00 #define GLM_COMPILER_GCC41 0x02001000 #define GLM_COMPILER_GCC42 0x02002000 #define GLM_COMPILER_GCC43 0x02004000 #define GLM_COMPILER_GCC44 0x02008000 #define GLM_COMPILER_GCC45 0x02010000 #define GLM_COMPILER_GCC46 0x02020000 #define GLM_COMPILER_GCC50 0x02040000 #define GLM_MODEL_32 0x00000010 #define GLM_MODEL_64 0x00000020 #ifndef GLM_COMPILER ///////////////// // Visual C++ // #ifdef _MSC_VER #if defined(_WIN64) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif// #if _MSC_VER == 1200 #define GLM_COMPILER GLM_COMPILER_VC60 #endif #if _MSC_VER == 1300 #define GLM_COMPILER GLM_COMPILER_VC70 #endif #if _MSC_VER == 1310 #define GLM_COMPILER GLM_COMPILER_VC71 #endif #if _MSC_VER == 1400 #define GLM_COMPILER GLM_COMPILER_VC80 #endif #if _MSC_VER == 1500 #define GLM_COMPILER GLM_COMPILER_VC90 #endif #if _MSC_VER == 1600 #define GLM_COMPILER GLM_COMPILER_VC2010 #endif #endif//_MSC_VER ////////////////// // GCC defines // #ifdef __GNUC__ #if(defined(__WORDSIZE) && (__WORDSIZE == 64)) || defined(__arch64__) #define GLM_MODEL GLM_MODEL_64 #else #define GLM_MODEL GLM_MODEL_32 #endif// #if (__GNUC__ == 2) && (__GNUC_MINOR__ == 8) #error "GCC 2.8x isn't supported" #define GLM_COMPILER GLM_COMPILER_GCC28 #endif #if (__GNUC__ == 2) && (__GNUC_MINOR__ == 9) #error "GCC 2.9x isn't supported" #define GLM_COMPILER GLM_COMPILER_GCC29 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 0) #error "GCC 3.0 isn't supported" #define GLM_COMPILER GLM_COMPILER_GCC30 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 1) #error "GCC 3.1 isn't supported" #define GLM_COMPILER GLM_COMPILER_GCC31 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC32 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC33 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC34 #endif #if (__GNUC__ == 3) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC35 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC40 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 1) #define GLM_COMPILER GLM_COMPILER_GCC41 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) #define GLM_COMPILER GLM_COMPILER_GCC42 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) #define GLM_COMPILER GLM_COMPILER_GCC43 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 4) #define GLM_COMPILER GLM_COMPILER_GCC44 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 5) #define GLM_COMPILER GLM_COMPILER_GCC45 #endif #if (__GNUC__ == 4) && (__GNUC_MINOR__ == 6) #define GLM_COMPILER GLM_COMPILER_GCC46 #endif #if (__GNUC__ == 5) && (__GNUC_MINOR__ == 0) #define GLM_COMPILER GLM_COMPILER_GCC50 #endif #endif//__GNUC__ #endif//GLM_COMPILER #ifndef GLM_COMPILER #error "GLM_COMPILER undefined, your compiler may not be supported by GLM. Add #define GLM_COMPILER 0 to ignore this message." #endif//GLM_COMPILER #if(!defined(GLM_MODEL) && GLM_COMPILER != 0) #error "GLM_MODEL undefined, your compiler may not be supported by GLM. Add #define GLM_MODEL 0 to ignore this message." #endif//GLM_MODEL #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_VC) # pragma message("GLM message: Compiled with Visual C++") # elif(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_GCC) # pragma message("GLM message: Compiled with GCC") # else # pragma message("GLM warning: Compiler not detected") # endif #endif//GLM_MESSAGE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(GLM_MODEL == GLM_MODEL_64) # pragma message("GLM message: 64 bits model") # elif(GLM_MODEL == GLM_MODEL_32) # pragma message("GLM message: 32 bits model") # endif//GLM_MODEL #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Compatibility #define GLM_COMPATIBILITY_DEFAULT 0 #define GLM_COMPATIBILITY_STRICT 1 //! By default: //#define GLM_COMPATIBILITY GLM_COMPATIBILITY_DEFAULT #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(!defined(GLM_COMPATIBILITY) || (defined(GLM_COMPATIBILITY) && (GLM_COMPATIBILITY == GLM_COMPATIBILITY_STRICT))) # # elif(defined(GLM_COMPATIBILITY) && (GLM_COMPATIBILITY == GLM_COMPATIBILITY_STRICT)) # pragma message("GLM message: compatibility strict") # endif//GLM_AUTO_CAST #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // External dependencies #define GLM_DEPENDENCE_NONE 0x00000000 #define GLM_DEPENDENCE_GLEW 0x00000001 #define GLM_DEPENDENCE_GLEE 0x00000002 #define GLM_DEPENDENCE_GL 0x00000004 #define GLM_DEPENDENCE_GL3 0x00000008 #define GLM_DEPENDENCE_BOOST 0x0000000F #define GLM_DEPENDENCE_STL 0x00000010 #define GLM_DEPENDENCE_TR1 0x00000020 #define GLM_DEPENDENCE_TR2 0x00000040 //! By default: // #define GLM_DEPENDENCE GLM_DEPENDENCE_NONE #if(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_GLEW)) #include <GL/glew.hpp> #elif(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_GLEE)) #include <GL/GLee.hpp> #elif(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_GL)) #include <GL/gl.h> #elif(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_GL3)) #include <GL3/gl3.h> #endif//GLM_DEPENDENCE #if(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_BOOST)) #include <boost/static_assert.hpp> #endif//GLM_DEPENDENCE #if(defined(GLM_DEPENDENCE) && (GLM_DEPENDENCE & GLM_DEPENDENCE_BOOST)) || defined(BOOST_STATIC_ASSERT) #define GLM_STATIC_ASSERT(x) BOOST_STATIC_ASSERT(x) #else #define GLM_STATIC_ASSERT(x) typedef char __CASSERT__##__LINE__[(x) ? 1 : -1] #endif//GLM_DEPENDENCE /////////////////////////////////////////////////////////////////////////////////////////////////// // Cast #define GLM_CAST_NONE 0x00000000 #define GLM_CAST_DIRECTX_9 0x00000001 #define GLM_CAST_DIRECTX_10 0x00000002 #define GLM_CAST_NVSG 0x00000004 #define GLM_CAST_WILD_MAGIC_3 0x00000008 #define GLM_CAST_WILD_MAGIC_4 0x00000010 #define GLM_CAST_PHYSX 0x00000020 #define GLM_CAST_ODE 0x00000040 //! By default: // #define GLM_CAST GLM_CAST_NONE // #define GLM_CAST_EXT GLM_CAST_NONE /////////////////////////////////////////////////////////////////////////////////////////////////// // Automatic cast // glColor4fv(glm::vec4(1.0)) //! By default: // #define GLM_AUTO_CAST GLM_ENABLE // GLM_AUTO_CAST isn't defined by defaut but also enable by default with GLM 0.7.x // Disable GLM_AUTO_CAST by default on Visual C++ 7.1 #if(defined(GLM_COMPILER) && GLM_COMPILER & GLM_COMPILER_VC && GLM_COMPILER <= GLM_COMPILER_VC71) # if(defined(GLM_AUTO_CAST) || (GLM_AUTO_CAST == GLM_ENABLE)) # error "GLM_AUTO_CAST isn't supported by Visual C++ 7.1 and below" # else # define GLM_AUTO_CAST GLM_DISABLE # endif//GLM_AUTO_CAST #endif//GLM_COMPILER #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if(!defined(GLM_AUTO_CAST) || (defined(GLM_AUTO_CAST) && (GLM_AUTO_CAST == GLM_ENABLE))) # pragma message("GLM message: Auto cast enabled") # else # pragma message("GLM message: Auto cast disabled") # endif//GLM_AUTO_CAST #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// // Swizzle operators #define GLM_SWIZZLE_NONE 0x00000000 #define GLM_SWIZZLE_XYZW 0x00000002 #define GLM_SWIZZLE_RGBA 0x00000004 #define GLM_SWIZZLE_STQP 0x00000008 #define GLM_SWIZZLE_FULL (GLM_SWIZZLE_XYZW | GLM_SWIZZLE_RGBA | GLM_SWIZZLE_STQP) //! By default: // #define GLM_SWIZZLE GLM_SWIZZLE_NONE #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_SETUP | GLM_MESSAGE_NOTIFICATION))) # if !defined(GLM_SWIZZLE)|| (defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_NONE) # pragma message("GLM message: No swizzling operator used") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE == GLM_SWIZZLE_FULL) # pragma message("GLM message: Full swizzling operator support enabled") # elif(defined(GLM_SWIZZLE) && GLM_SWIZZLE & GLM_SWIZZLE_FULL) # pragma message("GLM message: Partial swizzling operator support enabled") # endif//GLM_SWIZZLE #endif//GLM_MESSAGE /////////////////////////////////////////////////////////////////////////////////////////////////// #endif//glm_setup
[ [ [ 1, 369 ] ] ]
f67057fefeb195cf5de6820f05c2430bc10571ba
6686575384667a600902a254703c2923e7ae74d1
/Hasami Shogi/Source/Node.cpp
9f46f03f4ad6d7f5be257cd213c846e9c38a224d
[]
no_license
tiagobabo/laigproject3
d0006b32602a3da05a8a1dce50ff196e4077dcc2
789baabd7846371deb9fc690d5ddc471b70c9204
refs/heads/master
2020-04-30T00:29:15.507686
2010-12-19T20:24:56
2010-12-19T20:24:56
32,797,165
0
0
null
null
null
null
ISO-8859-1
C++
false
false
12,797
cpp
#include "SceneLoader.h" RGBpixmap pixmap; vector<Texture*> textures; int exists(Texture* text) { for(int i = 0; i < textures.size(); i++) { if(textures.at(i)->file == text->file) return i+1; } char *FileExt = const_cast<char*> ( text->file.c_str()); pixmap.readBMPFile(FileExt); textures.push_back(text); pixmap.setTexture(textures.size()); return textures.size(); } void ReduceToUnit(float vector[3]) // Reduces A Normal Vector (3 Coordinates) { // To A Unit Normal Vector With A Length Of One. float length; // Holds Unit Length // Calculates The Length Of The Vector length = (float)sqrt((vector[0]*vector[0]) + (vector[1]*vector[1]) + (vector[2]*vector[2])); if(length == 0.0f) // Prevents Divide By 0 Error By Providing length = 1.0f; // An Acceptable Value For Vectors To Close To 0. vector[0] /= length; // Dividing Each Element By vector[1] /= length; // The Length Results In A vector[2] /= length; // Unit Normal Vector. } void calcNormal(float v[3][3], float out[3]) // Calculates Normal For A Quad Using 3 Points { float v1[3],v2[3]; // Vector 1 (x,y,z) & Vector 2 (x,y,z) static const int x = 0; // Define X Coord static const int y = 1; // Define Y Coord static const int z = 2; // Define Z Coord // Finds The Vector Between 2 Points By Subtracting // The x,y,z Coordinates From One Point To Another. // Calculate The Vector From Point 1 To Point 0 v1[x] = v[0][x] - v[1][x]; // Vector 1.x=Vertex[0].x-Vertex[1].x v1[y] = v[0][y] - v[1][y]; // Vector 1.y=Vertex[0].y-Vertex[1].y v1[z] = v[0][z] - v[1][z]; // Vector 1.z=Vertex[0].y-Vertex[1].z // Calculate The Vector From Point 2 To Point 1 v2[x] = v[1][x] - v[2][x]; // Vector 2.x=Vertex[0].x-Vertex[1].x v2[y] = v[1][y] - v[2][y]; // Vector 2.y=Vertex[0].y-Vertex[1].y v2[z] = v[1][z] - v[2][z]; // Vector 2.z=Vertex[0].z-Vertex[1].z // Compute The Cross Product To Give Us A Surface Normal out[x] = v1[y]*v2[z] - v1[z]*v2[y]; // Cross Product For Y - Z out[y] = v1[z]*v2[x] - v1[x]*v2[z]; // Cross Product For X - Z out[z] = v1[x]*v2[y] - v1[y]*v2[x]; // Cross Product For X - Y ReduceToUnit(out); // Normalize The Vectors } void loadMaterial(Material* m) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMaterialfv(GL_FRONT, GL_SHININESS, &m->shininess); glMaterialfv(GL_FRONT, GL_SPECULAR, m->specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, m->diffuse); glMaterialfv(GL_FRONT, GL_AMBIENT, m->ambient); glMaterialfv(GL_FRONT, GL_EMISSION, m->emission); } //constructores das classes Node::Node(string id, string type) { this->id = id; this->type = type; this->texture = NULL; this->material = NULL; this->visi=-1; this->visi_enable=1; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glGetFloatv(GL_MODELVIEW_MATRIX, &transformations[0][0]); } Object::Object(string id, string type):Node(id,type) {} CompoundObject::CompoundObject(string id, string type):Node(id,type) {} Box::Box(string id, string type, float dx, float dy, float dz) :Object(id,type) { this->dx=dx; this->dy=dy; this->dz=dz; } Triangle::Triangle(string id, string type, float x1, float x2, float x3, float y1, float y2, float y3, float z1, float z2, float z3) :Object(id, type) { this->x1= x1; this->x2= x2; this->x3= x3; this->y1= y1; this->y2= y2; this->y3= y3; this->z1= z1; this->z2= z2; this->z3= z3; } Rectangle::Rectangle(string id, string type, float x1, float y1, float x2, float y2) :Object(id, type) { this->x1=x1; this->y1=y1; this->x2=x2; this->y2=y2; } Cylinder::Cylinder(string id, string type, float base, float top, float height, float slices, float stacks) :Object(id,type) { this->base = base; this->top = top; this-> height = height; this->slices = slices; this->stacks = stacks; } Disk::Disk(string id, string type, float inner, float outer, float slices, float loops) :Object(id, type) { this->inner = inner; this->outer = outer; this->slices = slices; this->loops = loops; } Sphere::Sphere(string id, string type, float radius, float slices, float stacks) :Object(id, type) { this->radius = radius; this->slices = slices; this->stacks = stacks; } //Fim da construção das classes //Funções partilhadas da classe Node void Node::setTexture(string t) { this->textureid = t; } void Node::setMaterial(string m) { this->materialid = m; } void Node::setVisi(int v) { this->visi=v; } string Node::getTextureId() { return this->textureid; } string Node::getMaterialId() { return this->materialid; } void Node::setId(string id) { this->id = id; } void CompoundObject::addNode(Node* node) { this->nodes.push_back(node); } void CompoundObject::addId(string node) { this->ids.push_back(node); } void CompoundObject::draw() { vector<Node*>::iterator it; glPushMatrix(); glMatrixMode(GL_MODELVIEW); glMultMatrixf(&this->transformations[0][0]); for(it=nodes.begin() ; it < nodes.end(); it++) { glMatrixMode(GL_MODELVIEW); if((*it)->visi_enable==1){ if((*it)->visi==1) (*it)->draw(); } else (*it)->draw(); } glPopMatrix(); } void Box::draw() { float s=1; float t=1; if(this->texture != NULL&& this->texture->id != "clear"){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); // estao a faltar 4 faces... //direita glBegin(GL_POLYGON); glNormal3d(1.0,0.0,0.0); glTexCoord2f((this->dz)/s,0.0); glVertex3d(this->dx/2,-this->dy/2,-this->dz/2); glTexCoord2f((this->dz)/s,(this->dy)/t); glVertex3d(this->dx/2,this->dy/2,-this->dz/2); glTexCoord2f(0.0,(this->dy)/t); glVertex3d(this->dx/2,this->dy/2,this->dz/2); glTexCoord2f(0.0,0.0); glVertex3d(this->dx/2,-this->dy/2,this->dz/2); glEnd(); //esquerda glBegin(GL_POLYGON); glNormal3d(-1.0,0.0,0.0); glTexCoord2f(0.0,0.0); glVertex3d(-this->dx/2,-this->dy/2,-this->dz/2); glTexCoord2f((this->dz)/s,0.0); glVertex3d(-this->dx/2,-this->dy/2,this->dz/2); glTexCoord2f((this->dz)/s,(this->dy)/t); glVertex3d(-this->dx/2,this->dy/2,this->dz/2); glTexCoord2f(0.0,(this->dy)/t); glVertex3d(-this->dx/2,this->dy/2,-this->dz/2); glEnd(); //frente glBegin(GL_POLYGON); glNormal3d(0.0,0.0,1.0); glTexCoord2f((this->dx)/s,0.0); glVertex3d(this->dx/2,-this->dy/2,this->dz/2); glTexCoord2f((this->dx)/s,(this->dy)/t); glVertex3d(this->dx/2,this->dy/2,this->dz/2); glTexCoord2f(0.0,(this->dy)/t); glVertex3d(-this->dx/2,this->dy/2,this->dz/2); glTexCoord2f(0.0,0.0); glVertex3d(-this->dx/2,-this->dy/2,this->dz/2); glEnd(); //tras glBegin(GL_POLYGON); glNormal3d(0.0,0.0,-1.0); glTexCoord2f(0.0,0.0); glVertex3d(this->dx/2,-this->dy/2,-this->dz/2); glTexCoord2f((this->dx)/s,0.0); glVertex3d(-this->dx/2,-this->dy/2,-this->dz/2); glTexCoord2f((this->dx)/s,(this->dy)/t); glVertex3d(-this->dx/2,this->dy/2,-this->dz/2); glTexCoord2f(0.0,(this->dy)/t); glVertex3d(this->dx/2,this->dy/2,-this->dz/2); glEnd(); //cima glBegin(GL_POLYGON); glNormal3d(0.0,1.0,0.0); glTexCoord2f((this->dx)/s,0.0); glVertex3d(this->dx/2,this->dy/2,this->dz/2); glTexCoord2f((this->dx)/s,(this->dz)/t); glVertex3d(this->dx/2,this->dy/2,-this->dz/2); glTexCoord2f(0.0,(this->dz)/t); glVertex3d(-this->dx/2,this->dy/2,-this->dz/2); glTexCoord2f(0.0,0.0); glVertex3d(-this->dx/2,this->dy/2,this->dz/2); glEnd(); //baixo glBegin(GL_POLYGON); glNormal3d(0.0,-1.0,0.0); glTexCoord2f(0.0,0.0); glVertex3d(this->dx/2,-this->dy/2,this->dz/2); glTexCoord2f((this->dx)/s,0.0); glVertex3d(-this->dx/2,-this->dy/2,this->dz/2); glTexCoord2f((this->dx)/s,(this->dz)/t); glVertex3d(-this->dx/2,-this->dy/2,-this->dz/2); glTexCoord2f(0.0,(this->dz)/t); glVertex3d(this->dx/2,-this->dy/2,-this->dz/2); glEnd(); glEnd(); glPopMatrix(); glDisable(GL_TEXTURE_2D); } void Triangle::draw() { float s=1; float t=1; if(this->texture != NULL&& this->texture->id != "clear"){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); float pontos[3][3] = {{this->x1,this->y1,this->z1},{this->x2,this->y2,this->z2},{this->x3,this->y3,this->z3}}; float normal[3]; calcNormal(pontos, normal); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); glBegin(GL_TRIANGLES); glNormal3d(normal[0],normal[1],normal[2]); glTexCoord2f(0.0,0.0); glVertex3d(this->x1, this->y1, this->z1); glTexCoord2f(abs((this->x2-this->x1)/s*normal[2]+(this->x2-this->x1)/s*normal[1]+(this->z2-this->z1)/s*normal[0]),0.0); glVertex3d(this->x2, this->y2, this->z2); glTexCoord2f(abs((this->x3-this->x1)/s*normal[2]+(this->x3-this->x1)/s*normal[1]+(this->z3-this->z1)/s*normal[0]),abs((this->y3-this->y1)/t*normal[2]+(this->x3-this->x1)/t*normal[1]+(this->y3-this->y1)/t*normal[0])); glVertex3d(this->x3, this->y3, this->z3); glEnd(); glPopMatrix(); glDisable(GL_TEXTURE_2D); } void Rectangle::draw() { float s=1; float t=1; if(this->texture != NULL && this->texture->id != "clear"){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); glBegin(GL_POLYGON); if( (this->y2 < this->y1) && (this->x2 < this->x1)){ glNormal3d(0.0,0.0,-1.0); glTexCoord2f(0.0,0.0); glVertex3d(this->x2, this->y2, 0.0); glTexCoord2f((this->x1-this->x2)/s,0.0); glVertex3d(this->x1, this->y2, 0.0); glTexCoord2f((this->x2-this->x1)/s,(this->y2-this->y1)/t); glVertex3d(this->x1, this->y1, 0.0); glTexCoord2f(0.0,(this->y2-this->y1)/t); glVertex3d(this->x2, this->y1, 0.0); } else{ glNormal3d(0.0,0.0,1.0); glTexCoord2f(0.0,0.0); glVertex3d(this->x1, this->y1, 0.0); glTexCoord2f((this->x2-this->x1)/s,0.0); glVertex3d(this->x2, this->y1, 0.0); glTexCoord2f((this->x2-this->x1)/s,(this->y2-this->y1)/t); glVertex3d(this->x2, this->y2, 0.0); glTexCoord2f(0.0,(this->y2-this->y1)/t); glVertex3d(this->x1, this->y2, 0.0); } glEnd(); glPopMatrix(); glDisable(GL_TEXTURE_2D); } void Cylinder::draw() { float s=1; float t=1; GLUquadric* glQ2; glQ2 = gluNewQuadric(); if(this->texture != NULL&& this->texture->id != "clear"){ glEnable(GL_TEXTURE_2D); gluQuadricTexture(glQ2, GL_TRUE); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); gluCylinder(glQ2, this->base, this->top, this->height, this->slices, this->stacks); glPopMatrix(); glDisable(GL_TEXTURE_2D); gluQuadricTexture(glQ2, GL_FALSE); } void Disk::draw() { float s=1; float t=1; GLUquadric* glQ2; glQ2 = gluNewQuadric(); if(this->texture != NULL && this->texture->id != "clear"){ gluQuadricTexture(glQ2, GL_TRUE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); gluDisk(glQ2, this->inner, this->outer, this->slices, this->loops); glPopMatrix(); glDisable(GL_TEXTURE_2D); gluQuadricTexture(glQ2, GL_FALSE); } void Sphere::draw() { float s=1; float t=1; GLUquadric* glQ2; glQ2 = gluNewQuadric(); if(this->texture != NULL&& this->texture->id != "clear"){ gluQuadricTexture(glQ2, GL_TRUE); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, exists(this->texture)); s=this->texture->length_s; t=this->texture->length_t; } if(this->material != NULL) loadMaterial(this->material); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(&this->transformations[0][0]); gluSphere(glQ2, this->radius, this->slices, this->stacks); glPopMatrix(); glDisable(GL_TEXTURE_2D); gluQuadricTexture(glQ2, GL_FALSE); }
[ "inpanzinator@b1645c4f-d7ca-25ad-7c18-ae5f0ac7c14a" ]
[ [ [ 1, 421 ] ] ]
846ff04143e60d7902fda666c52f535aa61f2635
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKitTools/DumpRenderTree/qt/GCControllerQt.h
c6a8a8ce1cf6f396741bd31a6675136e20ce69c6
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,064
h
/* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/ * * 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GCControllerQt_h #define GCControllerQt_h #include <QObject> class QWebPage; class DumpRenderTreeSupportQt; class GCController : public QObject { Q_OBJECT public: GCController(QWebPage* parent); public slots: void collect() const; void collectOnAlternateThread(bool waitUntilDone) const; size_t getJSObjectCount() const; }; #endif
[ [ [ 1, 50 ] ] ]
915bba688ddc6e953195d22d50adef4fbb16d163
ad33a51b7d45d8bf1aa900022564495bc08e0096
/DES/DES_GOBSTG/Header/Scripter.h
eb45ef3a63981b184bf5208c311b8222537cd5f3
[]
no_license
CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4
31aff43df2571d334672929c88dfd41315a4098a
f33d52bbb59dfb758b24c0651449322ecd1b56b7
refs/heads/master
2016-09-11T02:42:42.116248
2011-09-26T04:30:32
2011-09-26T04:30:32
32,192,691
0
0
null
null
null
null
UTF-8
C++
false
false
5,305
h
#ifndef _SCRIPTER_H #define _SCRIPTER_H #include "MainDependency.h" #include "Const.h" #include "keytable.h" #ifndef __NOTUSELUA #include "Export_Lua.h" #endif #define SCRIPT_DATAMAX 0x400000 #define SCR_MAXDESC 0x100 #ifdef __DEBUG #define __COUNT_SCRIPTSIZE #endif #define SCRIPT_GETTINGTEXT 0x10 #define SCRIPT_GETTINGBIN 0x20 #define SCRIPT_CON_INIT 0x0000 #define SCRIPT_CON_QUIT 0xffff #define SCRIPT_CON_POST 0x0000 #define SCR_VARBEGIN 0x30 #define SCR_FREEBEGIN 0x70 #define SCR_RESERVEBEGIN 0x90 #define SCR_VARDESCNUM (SCR_FREEBEGIN - SCR_VARBEGIN) #define CAST(p) (((p).bfloat) ? (CFLOAT((p).value)) : (CINT((p).value))) #define UCAST(p) (*(DWORD *)(p).value) #define SCRVECALL_FILE_SMALL 0x20 #define SCRVECALL_FILE_NORMAL 0x100 #define SCRVECALL_FILE_LARGE 0x400 #define SCRVECALL_BLOCK 0x60 enum{ SCR_TOKEN_VALUE = 0x0001, SCR_TOKEN_HANDLE = 0x0002, SCR_TOKEN_COMMAND = 0x0004, SCR_TOKEN_TYPE = 0x0008, SCR_TOKEN_VARIABLE = 0x0010, SCR_TOKEN_FLOAT = 0x0100, SCR_TOKEN_OPERATOR = 0x0200, SCR_TOKEN_KEYWORD = 0x0400, SCR_TOKEN_EOF = 0x0800, SCR_TOKEN_NULL = 0x1000, SCR_TOKEN_ERROR = 0x8000, }; enum{ SCR_FORCE_INT = 0x01, SCR_FORCE_FLOAT = 0x02, }; enum{ SCR_ERROR_INVALIDSTRING, SCR_ERROR_STRINGTOOLONG, SCR_ERROR_STRINGTOOMUCH, SCR_ERROR_VAROVER, SCR_ERROR_FREEVAROVER, SCR_ERROR_RESERVEVAROVER, }; typedef struct tagToken { DWORD value; DWORD type; }Token; typedef Token Script; typedef struct tagBlock //time, depth { vector<Script> block; DWORD con; //condition int varcount; #ifdef __COUNT_SCRIPTSIZE DWORD _size; #endif }Block; typedef struct tagFile //each file { vector<Block> file; DWORD name; #ifdef __COUNT_SCRIPTSIZE DWORD _size; #endif }File; typedef struct tagTData { void * value; bool bfloat; }TData; class Scripter { public: Scripter(); ~Scripter(); Token GetToken(); void FillCustomConstDesc(); bool LoadAll(); bool LoadScript(const char * filename); bool Resize(); bool SetValue(int index, void * value, bool bfloat); void * GetValue(int index); bool SetIntValue(int index, int ival) { return SetValue(index, &ival, false); } int GetIntValue(int index) { return CINT(GetValue(index)); } bool SetDWORDValue(int index, DWORD uval) { return SetValue(index, &uval, false); } DWORD GetDWORDValue(int index) { return CUINT(GetValue(index)); } bool SetFloatValue(int index, float fval) { return SetValue(index, &fval, true); } int GetFloatValue(int index) { return CFLOAT(GetValue(index)); } bool SetString(int index, char * str); char * GetString(int index); char * GetStringSp(int descindex); void LogOut(); private: bool Execute(vector<File> * ptype, DWORD name, DWORD con); public: bool Execute(DWORD typeflag, DWORD name, DWORD con) { #ifndef __NOTUSELUA return Execute_Lua(typeflag, name, con); #endif switch(typeflag) { case SCR_CONTROL: return Execute(&control, name, con); case SCR_STAGE: return Execute(&stage, name, con); case SCR_EDEF: return Execute(&edef, name, con); case SCR_SCENE: return Execute(&scene, name, con); case SCR_FUNCTION: return Execute(&function, name, con); case SCR_EVENT: return Execute(&event, name, con); } return false; } private: bool controlExecute(DWORD name, DWORD con) { return Execute(&control, name, con); }; bool stageExecute(DWORD name, DWORD con) { return Execute(&stage, name, con); }; bool edefExecute(DWORD name, DWORD con) { return Execute(&edef, name, con); }; bool sceneExecute(DWORD name, DWORD con) { return Execute(&scene, name, con); }; bool functionExecute(DWORD name, DWORD con) { return Execute(&function, name, con); }; bool eventExecute(DWORD name, DWORD con) { return Execute(&event, name, con); } public: bool Parse(int varcount); /* bool Copy(vector<Script>::iterator * p, BYTE num, BYTE dstart = 0);*/ void * Value(vector<Script>::iterator * p, int i, BYTE force); void * ValueI(vector<Script>::iterator * p, int i){return Value(p, i, SCR_FORCE_INT);}; void * ValueF(vector<Script>::iterator * p, int i){return Value(p, i, SCR_FORCE_FLOAT);}; void ReleaseVarName(); public: // char varName[SCR_FREEBEGIN-SCR_VARBEGIN][M_STRMAX]; char ** varName; TData d[SCR_MAXDESC]; union { int idesc[SCR_MAXDESC]; float fdesc[SCR_MAXDESC]; }; vector<File> control; vector<File> stage; vector<File> edef; vector<File> scene; vector<File> function; vector<File> event; FILE * file; #ifdef __COUNT_SCRIPTSIZE DWORD _controlsize; DWORD _stagesize; DWORD _edefsize; DWORD _scenesize; DWORD _functionsize; DWORD _eventsize; #endif DWORD binsize; DWORD binoffset; bool binmode; BYTE * bincontent; vector<Script> * pnow; DWORD nowName; DWORD nowCon; int tdi; DWORD tdu; float tdf; int varIndex; DWORD strdescIndex; static char strdesc[STRINGDESCMAX][M_STRMAX*2]; static Scripter scr; #ifndef __NOTUSELUA public: bool LoadAll_Lua(); bool Execute_Lua(DWORD typeflag, DWORD name, DWORD con); #endif }; #endif
[ "CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa" ]
[ [ [ 1, 268 ] ] ]
dc9df612595b482ee3618761f147df5a89c39071
c175910763a4ed175cdbfc58f539aece471f5256
/truck/3d-cg/3DCG/object-rotation/stdafx.cpp
7faaca57a269a70b2be5298cd3af9be73739b9c5
[]
no_license
KiraiChang/3d-cg
357c8315a349653a6cbe7a339cefa04078db4b3d
dbbd66c4331f117857dbfa660991c2ded01d3738
refs/heads/master
2021-01-22T09:32:10.976546
2010-04-27T06:59:57
2010-04-27T06:59:57
32,336,993
1
0
null
null
null
null
BIG5
C++
false
false
296
cpp
// stdafx.cpp : 僅包含標準 Include 檔的原始程式檔 // object-rotation.pch 會成為先行編譯標頭檔 // stdafx.obj 會包含先行編譯型別資訊 #include "stdafx.h" // TODO: 在 STDAFX.H 中參考您需要的任何其他標頭, // 而不要在這個檔案中參考
[ "[email protected]@d0fecb8e-c161-339a-4e07-94e11f48a80e" ]
[ [ [ 1, 8 ] ] ]
b47be06692a83f50b296b4c760e891ae536d7dcb
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkmetaio/metaCommand.h
72b533114469f9819dc9a1f4a306cdc98a103112
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,932
h
/*========================================================================= Program: MetaIO Module: $RCSfile: metaCommand.h,v $ Language: C++ Date: $Date: 2008-04-09 01:42:28 $ Version: $Revision: 1.10 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "metaTypes.h" #ifndef ITKMetaIO_METACOMMAND_H #define ITKMetaIO_METACOMMAND_H #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #pragma warning ( disable : 4251 ) #endif #include <stdlib.h> #include <string> #include <vector> #include <list> #include <map> #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif class METAIO_EXPORT MetaCommand { public: typedef enum {DATA_NONE,DATA_IN,DATA_OUT} DataEnumType; typedef enum {INT,FLOAT,CHAR,STRING,LIST,FLAG,BOOL,IMAGE,FILE} TypeEnumType; struct Field{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::string value; TypeEnumType type; DataEnumType externaldata; METAIO_STL::string rangeMin; METAIO_STL::string rangeMax; bool required; bool userDefined; }; struct Option{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::string tag; METAIO_STL::string longtag; METAIO_STL::string label; METAIO_STL::vector<Field> fields; bool required; bool userDefined; bool complete; }; struct ParameterGroup{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::vector<METAIO_STL::string> options; }; typedef METAIO_STL::vector<Option> OptionVector; typedef METAIO_STL::vector<ParameterGroup> ParameterGroupVector; MetaCommand(); ~MetaCommand() {} bool SetOption(Option option); bool SetOption(METAIO_STL::string name, METAIO_STL::string tag, bool required, METAIO_STL::string description, METAIO_STL::vector<Field> fields); bool SetOption(METAIO_STL::string name, METAIO_STL::string tag, bool required, METAIO_STL::string description, TypeEnumType type = FLAG, METAIO_STL::string defVal = "", DataEnumType externalData = DATA_NONE); /** Fields are added in order */ bool AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, DataEnumType externalData = DATA_NONE, METAIO_STL::string rangeMin = "", METAIO_STL::string rangeMax = "" ); /** For backward compatibility */ bool AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, bool externalData ); /** Add a field to an option */ bool AddOptionField(METAIO_STL::string optionName, METAIO_STL::string name, TypeEnumType type, bool required=true, METAIO_STL::string defVal = "", METAIO_STL::string description = "", DataEnumType externalData = DATA_NONE); /** Set the range of value as an option */ bool SetOptionRange(METAIO_STL::string optionName, METAIO_STL::string name, METAIO_STL::string rangeMin, METAIO_STL::string rangeMax); /** Set the long tag for the option */ bool SetOptionLongTag(METAIO_STL::string optionName, METAIO_STL::string longTag); /** Set the label for the option */ bool SetOptionLabel(METAIO_STL::string optionName, METAIO_STL::string label); /** Set the group for a field or an option * If the group doesn't exist it is automatically created. */ bool SetParameterGroup(METAIO_STL::string optionName, METAIO_STL::string groupName, METAIO_STL::string groupDescription=""); /** Collect all the information until the next tag * \warning this function works only if the field is of type String */ void SetOptionComplete(METAIO_STL::string optionName, bool complete); /** Get the values given the option name */ bool GetValueAsBool(METAIO_STL::string optionName, METAIO_STL::string fieldName=""); bool GetValueAsBool(Option option, METAIO_STL::string fieldName=""); float GetValueAsFloat(METAIO_STL::string optionName, METAIO_STL::string fieldName=""); float GetValueAsFloat(Option option, METAIO_STL::string fieldName=""); int GetValueAsInt(METAIO_STL::string optionName, METAIO_STL::string fieldName=""); int GetValueAsInt(Option option, METAIO_STL::string fieldName=""); METAIO_STL::string GetValueAsString(METAIO_STL::string optionName, METAIO_STL::string fieldName=""); METAIO_STL::string GetValueAsString(Option option, METAIO_STL::string fieldName=""); METAIO_STL::list< METAIO_STL::string > GetValueAsList( METAIO_STL::string optionName); METAIO_STL::list< METAIO_STL::string > GetValueAsList(Option option); bool GetOptionWasSet(METAIO_STL::string optionName); bool GetOptionWasSet(Option option); /** List the options */ void ListOptions(); void ListOptionsXML(); void ListOptionsSlicerXML(); void ListOptionsSimplified(bool extended=true); Option * GetOptionByMinusTag(METAIO_STL::string minusTag); Option * GetOptionByTag(METAIO_STL::string minusTag); bool OptionExistsByMinusTag(METAIO_STL::string minusTag); bool Parse(int argc, char* argv[]); /** Given an XML buffer fill in the command line arguments */ bool ParseXML(const char* buffer); /** Export the current command line arguments to a Grid Application * Description file */ bool ExportGAD(bool dynamic=false); /** Extract the date from cvs date */ METAIO_STL::string ExtractDateFromCVS(METAIO_STL::string date); void SetDateFromCVS(METAIO_STL::string date); /** Extract the version from cvs date */ METAIO_STL::string ExtractVersionFromCVS(METAIO_STL::string version); void SetVersionFromCVS(METAIO_STL::string version); /** Set the version of the app */ METAIO_STL::string GetVersion() { return m_Version; } void SetVersion(const char* version) { m_Version=version; } /** Get the name of the application */ METAIO_STL::string GetApplicationName() { return m_ExecutableName; } /** Set the date of the app */ METAIO_STL::string GetDate() { return m_Date; } void SetDate(const char* date) { m_Date=date; } void SetName(const char* name) { m_Name=name; } /** Set the description */ void SetDescription(const char* description) { m_Description=description; } METAIO_STL::string GetDescription() const {return m_Description;} /** Set the author */ void SetAuthor(const char* author) { m_Author=author; } METAIO_STL::string GetAuthor() const {return m_Author;} /** Set the acknowledgments */ void SetAcknowledgments(const char* acknowledgments) { m_Acknowledgments=acknowledgments; } METAIO_STL::string GetAcknowledgments() const {return m_Acknowledgments;} /** Set the category */ void SetCategory(const char* category) { m_Category=category; } METAIO_STL::string GetCategory() const {return m_Category;} long GetOptionId(Option* option); /** Return the list of options */ const OptionVector & GetOptions() { return m_OptionVector; } /** Return the list of parse options */ const OptionVector & GetParsedOptions() { return m_ParsedOptionVector; } void SetHelpCallBack(void (* newHelpCallBack)(void)) { m_HelpCallBack = newHelpCallBack; } METAIO_STL::string TypeToString(TypeEnumType type); TypeEnumType StringToType(const char* type); void SetVerbose(bool verbose) {m_Verbose = verbose;} void SetParseFailureOnUnrecognizedOption(bool fail) { m_FailOnUnrecognizedOption = fail; } /** Return true if we got the --xml */ bool GotXMLFlag() { return m_GotXMLFlag; } /** Disable the deprecated warnings */ void DisableDeprecatedWarnings(); /** Load arguments from XML file. * The second argument when set to true allows * external classes to use this function to parse XML * arguments. */ bool LoadArgumentsFromXML(const char* filename, bool createMissingArguments=false); protected: /** Small XML helper */ METAIO_STL::string GetXML(const char* buffer, const char* desc, unsigned long pos); METAIO_STL::string m_Version; METAIO_STL::string m_Date; METAIO_STL::string m_Name; METAIO_STL::string m_Description; METAIO_STL::string m_Author; METAIO_STL::string m_ExecutableName; METAIO_STL::string m_Acknowledgments; METAIO_STL::string m_Category; ParameterGroupVector m_ParameterGroup; private: void (* m_HelpCallBack)(void); /** Set the value of an option or a field * This is used when importing command line arguments * from XML */ bool SetOptionValue(const char* optionName, const char* name, const char* value, bool createMissingArgument=false); OptionVector m_OptionVector; OptionVector m_ParsedOptionVector; // We store the parsed option in // case we have multiple options bool m_Verbose; bool m_FailOnUnrecognizedOption; bool m_GotXMLFlag; bool m_DisableDeprecatedWarnings; // Use when write --xml void WriteXMLOptionToCout(METAIO_STL::string optionName,unsigned int& index); }; // end of class #if (METAIO_USE_NAMESPACE) }; #endif #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 330 ] ] ]
6cc85bf47112538d17dc6f901005c239aff480f6
a36d7a42310a8351aa0d427fe38b4c6eece305ea
/core_billiard/CameraCommonImp.h
1aa9c4fba9ffcb070c51266d9d4c8e52062b2f22
[]
no_license
newpolaris/mybilliard01
ca92888373c97606033c16c84a423de54146386a
dc3b21c63b5bfc762d6b1741b550021b347432e8
refs/heads/master
2020-04-21T06:08:04.412207
2009-09-21T15:18:27
2009-09-21T15:18:27
39,947,400
0
0
null
null
null
null
UTF-8
C++
false
false
498
h
#pragma once namespace my_render_imp { class CameraCommonImp : IMPLEMENTS_INTERFACE( CameraCommon ) { public: virtual float getZNear() OVERRIDE; virtual float getZFar() OVERRIDE; virtual float getAspect() OVERRIDE; virtual void setZNear(float nearf) OVERRIDE; virtual void setZFar(float farf) OVERRIDE; virtual void setAspect(float aspect) OVERRIDE; public: CameraCommonImp(); private: float aspect_; float zNear_; float zFar_; }; }
[ "wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635" ]
[ [ [ 1, 25 ] ] ]
7186ddb65ba0984c78cdc97a69665b17da765da2
b83c990328347a0a2130716fd99788c49c29621e
/include/boost/asio/detail/reactive_socket_service.hpp
7d07bbfa4f9d6a739bbd7c07187c94a408cb5b1b
[]
no_license
SpliFF/mingwlibs
c6249fbb13abd74ee9c16e0a049c88b27bd357cf
12d1369c9c1c2cc342f66c51d045b95c811ff90c
refs/heads/master
2021-01-18T03:51:51.198506
2010-06-13T15:13:20
2010-06-13T15:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
56,442
hpp
// // reactive_socket_service.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP #define BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/push_options.hpp> #include <boost/asio/detail/push_options.hpp> #include <boost/shared_ptr.hpp> #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/error.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/socket_base.hpp> #include <boost/asio/detail/bind_handler.hpp> #include <boost/asio/detail/handler_base_from_member.hpp> #include <boost/asio/detail/noncopyable.hpp> #include <boost/asio/detail/service_base.hpp> #include <boost/asio/detail/socket_holder.hpp> #include <boost/asio/detail/socket_ops.hpp> #include <boost/asio/detail/socket_types.hpp> namespace boost { namespace asio { namespace detail { template <typename Protocol, typename Reactor> class reactive_socket_service : public boost::asio::detail::service_base< reactive_socket_service<Protocol, Reactor> > { public: // The protocol type. typedef Protocol protocol_type; // The endpoint type. typedef typename Protocol::endpoint endpoint_type; // The native type of a socket. typedef socket_type native_type; // The implementation type of the socket. class implementation_type : private boost::asio::detail::noncopyable { public: // Default constructor. implementation_type() : socket_(invalid_socket), flags_(0), protocol_(endpoint_type().protocol()) { } private: // Only this service will have access to the internal values. friend class reactive_socket_service<Protocol, Reactor>; // The native socket representation. socket_type socket_; enum { // The user wants a non-blocking socket. user_set_non_blocking = 1, // The implementation wants a non-blocking socket (in order to be able to // perform asynchronous read and write operations). internal_non_blocking = 2, // Helper "flag" used to determine whether the socket is non-blocking. non_blocking = user_set_non_blocking | internal_non_blocking, // User wants connection_aborted errors, which are disabled by default. enable_connection_aborted = 4, // The user set the linger option. Needs to be checked when closing. user_set_linger = 8 }; // Flags indicating the current state of the socket. unsigned char flags_; // The protocol associated with the socket. protocol_type protocol_; // Per-descriptor data used by the reactor. typename Reactor::per_descriptor_data reactor_data_; }; // The maximum number of buffers to support in a single operation. enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; // Constructor. reactive_socket_service(boost::asio::io_service& io_service) : boost::asio::detail::service_base< reactive_socket_service<Protocol, Reactor> >(io_service), reactor_(boost::asio::use_service<Reactor>(io_service)) { reactor_.init_task(); } // Destroy all user-defined handler objects owned by the service. void shutdown_service() { } // Construct a new socket implementation. void construct(implementation_type& impl) { impl.socket_ = invalid_socket; impl.flags_ = 0; } // Destroy a socket implementation. void destroy(implementation_type& impl) { if (impl.socket_ != invalid_socket) { reactor_.close_descriptor(impl.socket_, impl.reactor_data_); if (impl.flags_ & implementation_type::non_blocking) { ioctl_arg_type non_blocking = 0; boost::system::error_code ignored_ec; socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ignored_ec); impl.flags_ &= ~implementation_type::non_blocking; } if (impl.flags_ & implementation_type::user_set_linger) { ::linger opt; opt.l_onoff = 0; opt.l_linger = 0; boost::system::error_code ignored_ec; socket_ops::setsockopt(impl.socket_, SOL_SOCKET, SO_LINGER, &opt, sizeof(opt), ignored_ec); } boost::system::error_code ignored_ec; socket_ops::close(impl.socket_, ignored_ec); impl.socket_ = invalid_socket; } } // Open a new socket implementation. boost::system::error_code open(implementation_type& impl, const protocol_type& protocol, boost::system::error_code& ec) { if (is_open(impl)) { ec = boost::asio::error::already_open; return ec; } socket_holder sock(socket_ops::socket(protocol.family(), protocol.type(), protocol.protocol(), ec)); if (sock.get() == invalid_socket) return ec; if (int err = reactor_.register_descriptor(sock.get(), impl.reactor_data_)) { ec = boost::system::error_code(err, boost::asio::error::get_system_category()); return ec; } impl.socket_ = sock.release(); impl.flags_ = 0; impl.protocol_ = protocol; ec = boost::system::error_code(); return ec; } // Assign a native socket to a socket implementation. boost::system::error_code assign(implementation_type& impl, const protocol_type& protocol, const native_type& native_socket, boost::system::error_code& ec) { if (is_open(impl)) { ec = boost::asio::error::already_open; return ec; } if (int err = reactor_.register_descriptor( native_socket, impl.reactor_data_)) { ec = boost::system::error_code(err, boost::asio::error::get_system_category()); return ec; } impl.socket_ = native_socket; impl.flags_ = 0; impl.protocol_ = protocol; ec = boost::system::error_code(); return ec; } // Determine whether the socket is open. bool is_open(const implementation_type& impl) const { return impl.socket_ != invalid_socket; } // Destroy a socket implementation. boost::system::error_code close(implementation_type& impl, boost::system::error_code& ec) { if (is_open(impl)) { reactor_.close_descriptor(impl.socket_, impl.reactor_data_); if (impl.flags_ & implementation_type::non_blocking) { ioctl_arg_type non_blocking = 0; boost::system::error_code ignored_ec; socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ignored_ec); impl.flags_ &= ~implementation_type::non_blocking; } if (socket_ops::close(impl.socket_, ec) == socket_error_retval) return ec; impl.socket_ = invalid_socket; } ec = boost::system::error_code(); return ec; } // Get the native socket representation. native_type native(implementation_type& impl) { return impl.socket_; } // Cancel all operations associated with the socket. boost::system::error_code cancel(implementation_type& impl, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } reactor_.cancel_ops(impl.socket_, impl.reactor_data_); ec = boost::system::error_code(); return ec; } // Determine whether the socket is at the out-of-band data mark. bool at_mark(const implementation_type& impl, boost::system::error_code& ec) const { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return false; } boost::asio::detail::ioctl_arg_type value = 0; socket_ops::ioctl(impl.socket_, SIOCATMARK, &value, ec); #if defined(ENOTTY) if (ec.value() == ENOTTY) ec = boost::asio::error::not_socket; #endif // defined(ENOTTY) return ec ? false : value != 0; } // Determine the number of bytes available for reading. std::size_t available(const implementation_type& impl, boost::system::error_code& ec) const { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } boost::asio::detail::ioctl_arg_type value = 0; socket_ops::ioctl(impl.socket_, FIONREAD, &value, ec); #if defined(ENOTTY) if (ec.value() == ENOTTY) ec = boost::asio::error::not_socket; #endif // defined(ENOTTY) return ec ? static_cast<std::size_t>(0) : static_cast<std::size_t>(value); } // Bind the socket to the specified local endpoint. boost::system::error_code bind(implementation_type& impl, const endpoint_type& endpoint, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec); return ec; } // Place the socket into the state where it will listen for new connections. boost::system::error_code listen(implementation_type& impl, int backlog, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } socket_ops::listen(impl.socket_, backlog, ec); return ec; } // Set a socket option. template <typename Option> boost::system::error_code set_option(implementation_type& impl, const Option& option, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } if (option.level(impl.protocol_) == custom_socket_option_level && option.name(impl.protocol_) == enable_connection_aborted_option) { if (option.size(impl.protocol_) != sizeof(int)) { ec = boost::asio::error::invalid_argument; } else { if (*reinterpret_cast<const int*>(option.data(impl.protocol_))) impl.flags_ |= implementation_type::enable_connection_aborted; else impl.flags_ &= ~implementation_type::enable_connection_aborted; ec = boost::system::error_code(); } return ec; } else { if (option.level(impl.protocol_) == SOL_SOCKET && option.name(impl.protocol_) == SO_LINGER) { impl.flags_ |= implementation_type::user_set_linger; } socket_ops::setsockopt(impl.socket_, option.level(impl.protocol_), option.name(impl.protocol_), option.data(impl.protocol_), option.size(impl.protocol_), ec); #if defined(__MACH__) && defined(__APPLE__) \ || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) // To implement portable behaviour for SO_REUSEADDR with UDP sockets we // need to also set SO_REUSEPORT on BSD-based platforms. if (!ec && impl.protocol_.type() == SOCK_DGRAM && option.level(impl.protocol_) == SOL_SOCKET && option.name(impl.protocol_) == SO_REUSEADDR) { boost::system::error_code ignored_ec; socket_ops::setsockopt(impl.socket_, SOL_SOCKET, SO_REUSEPORT, option.data(impl.protocol_), option.size(impl.protocol_), ignored_ec); } #endif return ec; } } // Set a socket option. template <typename Option> boost::system::error_code get_option(const implementation_type& impl, Option& option, boost::system::error_code& ec) const { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } if (option.level(impl.protocol_) == custom_socket_option_level && option.name(impl.protocol_) == enable_connection_aborted_option) { if (option.size(impl.protocol_) != sizeof(int)) { ec = boost::asio::error::invalid_argument; } else { int* target = reinterpret_cast<int*>(option.data(impl.protocol_)); if (impl.flags_ & implementation_type::enable_connection_aborted) *target = 1; else *target = 0; option.resize(impl.protocol_, sizeof(int)); ec = boost::system::error_code(); } return ec; } else { size_t size = option.size(impl.protocol_); socket_ops::getsockopt(impl.socket_, option.level(impl.protocol_), option.name(impl.protocol_), option.data(impl.protocol_), &size, ec); if (!ec) option.resize(impl.protocol_, size); return ec; } } // Perform an IO control command on the socket. template <typename IO_Control_Command> boost::system::error_code io_control(implementation_type& impl, IO_Control_Command& command, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } if (command.name() == static_cast<int>(FIONBIO)) { // Flags are manipulated in a temporary variable so that the socket // implementation is not updated unless the ioctl operation succeeds. unsigned char new_flags = impl.flags_; if (*static_cast<ioctl_arg_type*>(command.data())) new_flags |= implementation_type::user_set_non_blocking; else new_flags &= ~implementation_type::user_set_non_blocking; // Perform ioctl on socket if the non-blocking state has changed. if (!(impl.flags_ & implementation_type::non_blocking) && (new_flags & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec); } else if ((impl.flags_ & implementation_type::non_blocking) && !(new_flags & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 0; socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec); } else { ec = boost::system::error_code(); } // Update socket implementation's flags only if successful. if (!ec) impl.flags_ = new_flags; } else { socket_ops::ioctl(impl.socket_, command.name(), static_cast<ioctl_arg_type*>(command.data()), ec); } return ec; } // Get the local endpoint. endpoint_type local_endpoint(const implementation_type& impl, boost::system::error_code& ec) const { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return endpoint_type(); } endpoint_type endpoint; std::size_t addr_len = endpoint.capacity(); if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec)) return endpoint_type(); endpoint.resize(addr_len); return endpoint; } // Get the remote endpoint. endpoint_type remote_endpoint(const implementation_type& impl, boost::system::error_code& ec) const { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return endpoint_type(); } endpoint_type endpoint; std::size_t addr_len = endpoint.capacity(); if (socket_ops::getpeername(impl.socket_, endpoint.data(), &addr_len, ec)) return endpoint_type(); endpoint.resize(addr_len); return endpoint; } /// Disable sends or receives on the socket. boost::system::error_code shutdown(implementation_type& impl, socket_base::shutdown_type what, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } socket_ops::shutdown(impl.socket_, what, ec); return ec; } // Send the given data to the peer. template <typename ConstBufferSequence> size_t send(implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers.begin(); typename ConstBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to receive 0 bytes on a stream socket is a no-op. if (impl.protocol_.type() == SOCK_STREAM && total_buffer_size == 0) { ec = boost::system::error_code(); return 0; } // Send the data. for (;;) { // Try to complete the operation without blocking. int bytes_sent = socket_ops::send(impl.socket_, bufs, i, flags, ec); // Check if operation succeeded. if (bytes_sent >= 0) return bytes_sent; // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for socket to become ready. if (socket_ops::poll_write(impl.socket_, ec) < 0) return 0; } } // Wait until data can be sent without blocking. size_t send(implementation_type& impl, const null_buffers&, socket_base::message_flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for socket to become ready. socket_ops::poll_write(impl.socket_, ec); return 0; } template <typename ConstBufferSequence, typename Handler> class send_operation : public handler_base_from_member<Handler> { public: send_operation(socket_type socket, boost::asio::io_service& io_service, const ConstBufferSequence& buffers, socket_base::message_flags flags, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), io_service_(io_service), work_(io_service), buffers_(buffers), flags_(flags) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers_.begin(); typename ConstBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); } // Send the data. int bytes = socket_ops::send(socket_, bufs, i, flags_, ec); // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: socket_type socket_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; ConstBufferSequence buffers_; socket_base::message_flags flags_; }; // Start an asynchronous send. The data being sent must be valid for the // lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename Handler> void async_send(implementation_type& impl, const ConstBufferSequence& buffers, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { if (impl.protocol_.type() == SOCK_STREAM) { // Determine total size of buffers. typename ConstBufferSequence::const_iterator iter = buffers.begin(); typename ConstBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to receive 0 bytes on a stream socket is a no-op. if (total_buffer_size == 0) { this->get_io_service().post(bind_handler(handler, boost::system::error_code(), 0)); return; } } // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_write_op(impl.socket_, impl.reactor_data_, send_operation<ConstBufferSequence, Handler>( impl.socket_, this->get_io_service(), buffers, flags, handler)); } } template <typename Handler> class null_buffers_operation : public handler_base_from_member<Handler> { public: null_buffers_operation(boost::asio::io_service& io_service, Handler handler) : handler_base_from_member<Handler>(handler), work_(io_service) { } bool perform(boost::system::error_code&, std::size_t& bytes_transferred) { bytes_transferred = 0; return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { work_.get_io_service().post(bind_handler( this->handler_, ec, bytes_transferred)); } private: boost::asio::io_service::work work_; }; // Start an asynchronous wait until data can be sent without blocking. template <typename Handler> void async_send(implementation_type& impl, const null_buffers&, socket_base::message_flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { reactor_.start_write_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } // Send a datagram to the specified endpoint. Returns the number of bytes // sent. template <typename ConstBufferSequence> size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers.begin(); typename ConstBufferSequence::const_iterator end = buffers.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); } // Send the data. for (;;) { // Try to complete the operation without blocking. int bytes_sent = socket_ops::sendto(impl.socket_, bufs, i, flags, destination.data(), destination.size(), ec); // Check if operation succeeded. if (bytes_sent >= 0) return bytes_sent; // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for socket to become ready. if (socket_ops::poll_write(impl.socket_, ec) < 0) return 0; } } // Wait until data can be sent without blocking. size_t send_to(implementation_type& impl, const null_buffers&, socket_base::message_flags, const endpoint_type&, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for socket to become ready. socket_ops::poll_write(impl.socket_, ec); return 0; } template <typename ConstBufferSequence, typename Handler> class send_to_operation : public handler_base_from_member<Handler> { public: send_to_operation(socket_type socket, boost::asio::io_service& io_service, const ConstBufferSequence& buffers, const endpoint_type& endpoint, socket_base::message_flags flags, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), io_service_(io_service), work_(io_service), buffers_(buffers), destination_(endpoint), flags_(flags) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename ConstBufferSequence::const_iterator iter = buffers_.begin(); typename ConstBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::const_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<const void*>(buffer), boost::asio::buffer_size(buffer)); } // Send the data. int bytes = socket_ops::sendto(socket_, bufs, i, flags_, destination_.data(), destination_.size(), ec); // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: socket_type socket_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; ConstBufferSequence buffers_; endpoint_type destination_; socket_base::message_flags flags_; }; // Start an asynchronous send. The data being sent must be valid for the // lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename Handler> void async_send_to(implementation_type& impl, const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_write_op(impl.socket_, impl.reactor_data_, send_to_operation<ConstBufferSequence, Handler>( impl.socket_, this->get_io_service(), buffers, destination, flags, handler)); } } // Start an asynchronous wait until data can be sent without blocking. template <typename Handler> void async_send_to(implementation_type& impl, const null_buffers&, socket_base::message_flags, const endpoint_type&, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { reactor_.start_write_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } // Receive some data from the peer. Returns the number of bytes received. template <typename MutableBufferSequence> size_t receive(implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers.begin(); typename MutableBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to receive 0 bytes on a stream socket is a no-op. if (impl.protocol_.type() == SOCK_STREAM && total_buffer_size == 0) { ec = boost::system::error_code(); return 0; } // Receive some data. for (;;) { // Try to complete the operation without blocking. int bytes_recvd = socket_ops::recv(impl.socket_, bufs, i, flags, ec); // Check if operation succeeded. if (bytes_recvd > 0) return bytes_recvd; // Check for EOF. if (bytes_recvd == 0 && impl.protocol_.type() == SOCK_STREAM) { ec = boost::asio::error::eof; return 0; } // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for socket to become ready. if (socket_ops::poll_read(impl.socket_, ec) < 0) return 0; } } // Wait until data can be received without blocking. size_t receive(implementation_type& impl, const null_buffers&, socket_base::message_flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for socket to become ready. socket_ops::poll_read(impl.socket_, ec); return 0; } template <typename MutableBufferSequence, typename Handler> class receive_operation : public handler_base_from_member<Handler> { public: receive_operation(socket_type socket, int protocol_type, boost::asio::io_service& io_service, const MutableBufferSequence& buffers, socket_base::message_flags flags, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), protocol_type_(protocol_type), io_service_(io_service), work_(io_service), buffers_(buffers), flags_(flags) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers_.begin(); typename MutableBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); } // Receive some data. int bytes = socket_ops::recv(socket_, bufs, i, flags_, ec); if (bytes == 0 && protocol_type_ == SOCK_STREAM) ec = boost::asio::error::eof; // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: socket_type socket_; int protocol_type_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; MutableBufferSequence buffers_; socket_base::message_flags flags_; }; // Start an asynchronous receive. The buffer for the data being received // must be valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename Handler> void async_receive(implementation_type& impl, const MutableBufferSequence& buffers, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { if (impl.protocol_.type() == SOCK_STREAM) { // Determine total size of buffers. typename MutableBufferSequence::const_iterator iter = buffers.begin(); typename MutableBufferSequence::const_iterator end = buffers.end(); size_t i = 0; size_t total_buffer_size = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); total_buffer_size += boost::asio::buffer_size(buffer); } // A request to receive 0 bytes on a stream socket is a no-op. if (total_buffer_size == 0) { this->get_io_service().post(bind_handler(handler, boost::system::error_code(), 0)); return; } } // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } if (flags & socket_base::message_out_of_band) { reactor_.start_except_op(impl.socket_, impl.reactor_data_, receive_operation<MutableBufferSequence, Handler>( impl.socket_, impl.protocol_.type(), this->get_io_service(), buffers, flags, handler)); } else { reactor_.start_read_op(impl.socket_, impl.reactor_data_, receive_operation<MutableBufferSequence, Handler>( impl.socket_, impl.protocol_.type(), this->get_io_service(), buffers, flags, handler)); } } } // Wait until data can be received without blocking. template <typename Handler> void async_receive(implementation_type& impl, const null_buffers&, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else if (flags & socket_base::message_out_of_band) { reactor_.start_except_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler)); } else { reactor_.start_read_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } // Receive a datagram with the endpoint of the sender. Returns the number of // bytes received. template <typename MutableBufferSequence> size_t receive_from(implementation_type& impl, const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers.begin(); typename MutableBufferSequence::const_iterator end = buffers.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); } // Receive some data. for (;;) { // Try to complete the operation without blocking. std::size_t addr_len = sender_endpoint.capacity(); int bytes_recvd = socket_ops::recvfrom(impl.socket_, bufs, i, flags, sender_endpoint.data(), &addr_len, ec); // Check if operation succeeded. if (bytes_recvd > 0) { sender_endpoint.resize(addr_len); return bytes_recvd; } // Check for EOF. if (bytes_recvd == 0 && impl.protocol_.type() == SOCK_STREAM) { ec = boost::asio::error::eof; return 0; } // Operation failed. if ((impl.flags_ & implementation_type::user_set_non_blocking) || (ec != boost::asio::error::would_block && ec != boost::asio::error::try_again)) return 0; // Wait for socket to become ready. if (socket_ops::poll_read(impl.socket_, ec) < 0) return 0; } } // Wait until data can be received without blocking. size_t receive_from(implementation_type& impl, const null_buffers&, endpoint_type& sender_endpoint, socket_base::message_flags, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return 0; } // Wait for socket to become ready. socket_ops::poll_read(impl.socket_, ec); // Reset endpoint since it can be given no sensible value at this time. sender_endpoint = endpoint_type(); return 0; } template <typename MutableBufferSequence, typename Handler> class receive_from_operation : public handler_base_from_member<Handler> { public: receive_from_operation(socket_type socket, int protocol_type, boost::asio::io_service& io_service, const MutableBufferSequence& buffers, endpoint_type& endpoint, socket_base::message_flags flags, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), protocol_type_(protocol_type), io_service_(io_service), work_(io_service), buffers_(buffers), sender_endpoint_(endpoint), flags_(flags) { } bool perform(boost::system::error_code& ec, std::size_t& bytes_transferred) { // Check whether the operation was successful. if (ec) { bytes_transferred = 0; return true; } // Copy buffers into array. socket_ops::buf bufs[max_buffers]; typename MutableBufferSequence::const_iterator iter = buffers_.begin(); typename MutableBufferSequence::const_iterator end = buffers_.end(); size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) { boost::asio::mutable_buffer buffer(*iter); socket_ops::init_buf(bufs[i], boost::asio::buffer_cast<void*>(buffer), boost::asio::buffer_size(buffer)); } // Receive some data. std::size_t addr_len = sender_endpoint_.capacity(); int bytes = socket_ops::recvfrom(socket_, bufs, i, flags_, sender_endpoint_.data(), &addr_len, ec); if (bytes == 0 && protocol_type_ == SOCK_STREAM) ec = boost::asio::error::eof; // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; sender_endpoint_.resize(addr_len); bytes_transferred = (bytes < 0 ? 0 : bytes); return true; } void complete(const boost::system::error_code& ec, std::size_t bytes_transferred) { io_service_.post(bind_handler(this->handler_, ec, bytes_transferred)); } private: socket_type socket_; int protocol_type_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; MutableBufferSequence buffers_; endpoint_type& sender_endpoint_; socket_base::message_flags flags_; }; // Start an asynchronous receive. The buffer for the data being received and // the sender_endpoint object must both be valid for the lifetime of the // asynchronous operation. template <typename MutableBufferSequence, typename Handler> void async_receive_from(implementation_type& impl, const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec, 0)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_read_op(impl.socket_, impl.reactor_data_, receive_from_operation<MutableBufferSequence, Handler>( impl.socket_, impl.protocol_.type(), this->get_io_service(), buffers, sender_endpoint, flags, handler)); } } // Wait until data can be received without blocking. template <typename Handler> void async_receive_from(implementation_type& impl, const null_buffers&, endpoint_type& sender_endpoint, socket_base::message_flags flags, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor, 0)); } else { // Reset endpoint since it can be given no sensible value at this time. sender_endpoint = endpoint_type(); if (flags & socket_base::message_out_of_band) { reactor_.start_except_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler)); } else { reactor_.start_read_op(impl.socket_, impl.reactor_data_, null_buffers_operation<Handler>(this->get_io_service(), handler), false); } } } // Accept a new connection. template <typename Socket> boost::system::error_code accept(implementation_type& impl, Socket& peer, endpoint_type* peer_endpoint, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } // We cannot accept a socket that is already open. if (peer.is_open()) { ec = boost::asio::error::already_open; return ec; } // Accept a socket. for (;;) { // Try to complete the operation without blocking. boost::system::error_code ec; socket_holder new_socket; std::size_t addr_len = 0; if (peer_endpoint) { addr_len = peer_endpoint->capacity(); new_socket.reset(socket_ops::accept(impl.socket_, peer_endpoint->data(), &addr_len, ec)); } else { new_socket.reset(socket_ops::accept(impl.socket_, 0, 0, ec)); } // Check if operation succeeded. if (new_socket.get() >= 0) { if (peer_endpoint) peer_endpoint->resize(addr_len); peer.assign(impl.protocol_, new_socket.get(), ec); if (!ec) new_socket.release(); return ec; } // Operation failed. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) { if (impl.flags_ & implementation_type::user_set_non_blocking) return ec; // Fall through to retry operation. } else if (ec == boost::asio::error::connection_aborted) { if (impl.flags_ & implementation_type::enable_connection_aborted) return ec; // Fall through to retry operation. } #if defined(EPROTO) else if (ec.value() == EPROTO) { if (impl.flags_ & implementation_type::enable_connection_aborted) return ec; // Fall through to retry operation. } #endif // defined(EPROTO) else return ec; // Wait for socket to become ready. if (socket_ops::poll_read(impl.socket_, ec) < 0) return ec; } } template <typename Socket, typename Handler> class accept_operation : public handler_base_from_member<Handler> { public: accept_operation(socket_type socket, boost::asio::io_service& io_service, Socket& peer, const protocol_type& protocol, endpoint_type* peer_endpoint, bool enable_connection_aborted, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), io_service_(io_service), work_(io_service), peer_(peer), protocol_(protocol), peer_endpoint_(peer_endpoint), enable_connection_aborted_(enable_connection_aborted) { } bool perform(boost::system::error_code& ec, std::size_t&) { // Check whether the operation was successful. if (ec) return true; // Accept the waiting connection. socket_holder new_socket; std::size_t addr_len = 0; if (peer_endpoint_) { addr_len = peer_endpoint_->capacity(); new_socket.reset(socket_ops::accept(socket_, peer_endpoint_->data(), &addr_len, ec)); } else { new_socket.reset(socket_ops::accept(socket_, 0, 0, ec)); } // Check if we need to run the operation again. if (ec == boost::asio::error::would_block || ec == boost::asio::error::try_again) return false; if (ec == boost::asio::error::connection_aborted && !enable_connection_aborted_) return false; #if defined(EPROTO) if (ec.value() == EPROTO && !enable_connection_aborted_) return false; #endif // defined(EPROTO) // Transfer ownership of the new socket to the peer object. if (!ec) { if (peer_endpoint_) peer_endpoint_->resize(addr_len); peer_.assign(protocol_, new_socket.get(), ec); if (!ec) new_socket.release(); } return true; } void complete(const boost::system::error_code& ec, std::size_t) { io_service_.post(bind_handler(this->handler_, ec)); } private: socket_type socket_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; Socket& peer_; protocol_type protocol_; endpoint_type* peer_endpoint_; bool enable_connection_aborted_; }; // Start an asynchronous accept. The peer and peer_endpoint objects // must be valid until the accept's handler is invoked. template <typename Socket, typename Handler> void async_accept(implementation_type& impl, Socket& peer, endpoint_type* peer_endpoint, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor)); } else if (peer.is_open()) { this->get_io_service().post(bind_handler(handler, boost::asio::error::already_open)); } else { // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } reactor_.start_read_op(impl.socket_, impl.reactor_data_, accept_operation<Socket, Handler>( impl.socket_, this->get_io_service(), peer, impl.protocol_, peer_endpoint, (impl.flags_ & implementation_type::enable_connection_aborted) != 0, handler)); } } // Connect the socket to the specified endpoint. boost::system::error_code connect(implementation_type& impl, const endpoint_type& peer_endpoint, boost::system::error_code& ec) { if (!is_open(impl)) { ec = boost::asio::error::bad_descriptor; return ec; } // Perform the connect operation. socket_ops::connect(impl.socket_, peer_endpoint.data(), peer_endpoint.size(), ec); if (ec != boost::asio::error::in_progress && ec != boost::asio::error::would_block) { // The connect operation finished immediately. return ec; } // Wait for socket to become ready. if (socket_ops::poll_connect(impl.socket_, ec) < 0) return ec; // Get the error code from the connect operation. int connect_error = 0; size_t connect_error_len = sizeof(connect_error); if (socket_ops::getsockopt(impl.socket_, SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec) == socket_error_retval) return ec; // Return the result of the connect operation. ec = boost::system::error_code(connect_error, boost::asio::error::get_system_category()); return ec; } template <typename Handler> class connect_operation : public handler_base_from_member<Handler> { public: connect_operation(socket_type socket, boost::asio::io_service& io_service, Handler handler) : handler_base_from_member<Handler>(handler), socket_(socket), io_service_(io_service), work_(io_service) { } bool perform(boost::system::error_code& ec, std::size_t&) { // Check whether the operation was successful. if (ec) return true; // Get the error code from the connect operation. int connect_error = 0; size_t connect_error_len = sizeof(connect_error); if (socket_ops::getsockopt(socket_, SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec) == socket_error_retval) return true; // The connection failed so the handler will be posted with an error code. if (connect_error) { ec = boost::system::error_code(connect_error, boost::asio::error::get_system_category()); return true; } return true; } void complete(const boost::system::error_code& ec, std::size_t) { io_service_.post(bind_handler(this->handler_, ec)); } private: socket_type socket_; boost::asio::io_service& io_service_; boost::asio::io_service::work work_; }; // Start an asynchronous connect. template <typename Handler> void async_connect(implementation_type& impl, const endpoint_type& peer_endpoint, Handler handler) { if (!is_open(impl)) { this->get_io_service().post(bind_handler(handler, boost::asio::error::bad_descriptor)); return; } // Make socket non-blocking. if (!(impl.flags_ & implementation_type::internal_non_blocking)) { if (!(impl.flags_ & implementation_type::non_blocking)) { ioctl_arg_type non_blocking = 1; boost::system::error_code ec; if (socket_ops::ioctl(impl.socket_, FIONBIO, &non_blocking, ec)) { this->get_io_service().post(bind_handler(handler, ec)); return; } } impl.flags_ |= implementation_type::internal_non_blocking; } // Start the connect operation. The socket is already marked as non-blocking // so the connection will take place asynchronously. boost::system::error_code ec; if (socket_ops::connect(impl.socket_, peer_endpoint.data(), peer_endpoint.size(), ec) == 0) { // The connect operation has finished successfully so we need to post the // handler immediately. this->get_io_service().post(bind_handler(handler, boost::system::error_code())); } else if (ec == boost::asio::error::in_progress || ec == boost::asio::error::would_block) { // The connection is happening in the background, and we need to wait // until the socket becomes writeable. reactor_.start_connect_op(impl.socket_, impl.reactor_data_, connect_operation<Handler>(impl.socket_, this->get_io_service(), handler)); } else { // The connect operation has failed, so post the handler immediately. this->get_io_service().post(bind_handler(handler, ec)); } } private: // The selector that performs event demultiplexing for the service. Reactor& reactor_; }; } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP
[ [ [ 1, 1788 ] ] ]
414f37238458b3e4cba93a174dcf0ae85f67ffb3
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizerFPGA/exp_recover.h
9bc1be880c4eaa556473c121c6843d7c789c83ee
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
1,297
h
#ifndef EXP_RECOVER_H_ #define EXP_RECOVER_H_ #include "experiments.h" #include "detection_stats.h" /* Check if ion is bright or dark using Baysian analysis. If the ion is dark, try to recover by cooling & adjusting trap parameters. */ class exp_recover : public experiment { public: exp_recover(list_t* exp_list, const std::string& name = "Recover"); virtual ~exp_recover() { } virtual void updateParams(); virtual void run(const GbE_msg& msg_in, GbE_msg& msg_out); //use maximum likelihood method to determine ion state // -1 -- unknown // 0 -- dark // 1 -- bright int ion_state(double min_odds_ratio_dark, double min_odds_ratio_bright); bool recover_ion(); //! cool for approximately spec'd microseconds void cool(unsigned us); protected: void rampDownVoltages(); void rampUpVoltages(); //probability of state i given n counts double P(unsigned i, unsigned n); virtual void run_exp(int iExp); rp_double dark_mean, bright_mean, confidence_dark, confidence_bright; rp_unsigned max_reps; rp_bool ramp_voltages; dds_params Detect, DopplerCool, PrecoolShort, PrecoolLong; double odds_dark, odds_bright; exp_results pmt; vector<double> P0, P1; }; extern exp_recover* eRecover; #endif //EXP_RECOVER_H_
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 59 ] ] ]
155f61925cd54f295ca804a6aebff61b32d78ecb
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/win95/DEBUGLOG.CPP
d0a78477ac77634ecf697cb8c342134818e5c53a
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
2,111
cpp
#include <string.h> #include <stdlib.h> #include <windows.h> #include "debuglog.hpp" LogFile::LogFile(char const * const _fname) : fname(0) , ever_written(0) { FILE * fp = fopen(_fname,"w"); if (fp) { fclose(fp); fname = new char[strlen(_fname)+1]; strcpy(fname,_fname); return; } char const * path = getenv("TEMP"); if (!path) path = getenv("TMP"); if (!path) return; fname = new char[strlen(path)+1+strlen(_fname)+1]; strcpy(fname,path); strncat(fname,"\\",1); strcat(fname,_fname); fp = fopen(fname,"w"); if (fp) fclose(fp); else { delete[] fname; fname = 0; } } LogFile::~LogFile() { if (unwritten.size()) { FILE * fp = fopen(fname,"a"); for (int attempt=0; !fp && attempt<10; ++attempt) { Sleep(100); fp = fopen(fname,"a"); } if (fp) { FlushOut(fp); fclose(fp); } } if (fname) delete[] fname; } LogFile & LogFile::operator = (LogFile const & l) { if (&l != this) { if (fname) delete[] fname; if (l.fname) { fname = new char[strlen(l.fname)+1]; strcpy(fname,l.fname); } else fname = 0; unwritten = l.unwritten; ever_written = l.ever_written; } return *this; } LogFile::LogFile(LogFile const & l) : unwritten(l.unwritten) , ever_written(l.ever_written) { if (l.fname) { fname = new char[strlen(l.fname)+1]; strcpy(fname,l.fname); } else fname = 0; } void LogFile::FlushOut(FILE * fp) { while (unwritten.size()) { char * str = unwritten.first_entry(); unwritten.delete_first_entry(); fputs(str,fp); delete[] str; } } int vlfprintf(LOGFILE * lfp, char const * format, va_list args ) { return lfp->vlprintf(format,args); } int lfprintf(LOGFILE * lfp, char const * format, ... ) { va_list ap; va_start(ap, format); int rv = lfp->vlprintf(format,ap); va_end(ap); return rv; } int lfputs(LOGFILE * lfp, char const * str) { return lfp->lputs(str); } LOGFILE * lfopen(char const * fname) { return new LogFile(fname); } void lfclose(LOGFILE * lfp) { delete lfp; }
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 122 ] ] ]
5028a941ab86a1442d9b97acf384fc1a847ee0e0
af3b3fd56239cddee37913ee4184e2c62b428659
/src/thread/ThreadPool.cpp
afec2fb62bf6ffc91c0d8ac74d01fbc33fa27de6
[]
no_license
d3v3r4/clearcase-sponge
7c80405b58c2720777a008e67693869ea835b60e
699a1ef4874b9b9da2c84072774172d22c1d7369
refs/heads/master
2021-01-01T05:32:15.402646
2009-06-15T06:39:38
2009-06-15T06:39:38
41,874,171
0
0
null
null
null
null
UTF-8
C++
false
false
3,529
cpp
// ThreadPool.cpp #include "ThreadPool.h" #include <exception/ThreadException.h> #include <util/Locker.h> ThreadPool::ThreadPool(uint32 maxThreads) { init(maxThreads, 0); } ThreadPool::ThreadPool(uint32 maxThreads, uint32 timeoutMillis) { init(maxThreads, timeoutMillis); } ThreadPool::ThreadPool(uint32 maxThreads, uint32 timeoutMillis, uint32 queueMax) : m_pending(queueMax) { init(maxThreads, timeoutMillis); } void ThreadPool::init(uint32 maxThreads, uint32 timeoutMillis) { m_maxThreads = maxThreads; m_timeout = timeoutMillis; m_threadCount = 0; m_waitingThreads = 0; } ThreadPool::~ThreadPool() { shutdown(); } void ThreadPool::execute(Runnable* runnable) { m_condition.lock(); // If the queue is stopped, shutdown was called. Throw an exception. if (m_pending.isStopped()) { m_condition.unlock(); throw ThreadException("Cannot execute runnable in thread pool after " "the pool is shut down"); } // Join any stopped threads joinStopped(); // If we are already at the limit for threads, queue the runnable. // If there is a maximum queue size, we have to go into a wait loop // to wait for either space in the queue or the ability to start // another thread. if (m_threadCount == m_maxThreads) { bool queued = m_pending.tryPut(runnable); while (!queued && m_threadCount == m_maxThreads) { m_condition.wait(); queued = m_pending.tryPut(runnable); } // If we succeeded in queueing it, return if (queued) { m_condition.unlock(); return; } } // Otherwise increment the thread count because we will start a thread. m_threadCount++; m_condition.unlock(); // Start a WorkerThread for the Runnable. WorkerThread* workerThread = new WorkerThread(this, runnable); workerThread->start(); } void ThreadPool::shutdown() { // Stopping the queue causes an effective shutdown m_pending.stop(); Locker locker(m_condition); // wait until there are no running threads while (m_threadCount != 0) { m_condition.wait(); } // Clean up and join the stopped threads joinStopped(); } void ThreadPool::shutdownWhenEmpty() { Locker locker(m_condition); // Wait till there are no remaining Runnables and all remaining threads // are waiting for another Runnable while (m_pending.size() > 0 || m_waitingThreads != m_threadCount) { m_condition.wait(); } m_pending.stop(); // Now wait until there are no running threads while (m_threadCount != 0) { m_condition.wait(); } // Clean up and join the stopped threads joinStopped(); } uint32 ThreadPool::getPendingTaskCount() { return m_pending.size(); } Runnable* ThreadPool::getNextTask(WorkerThread* caller) { Runnable* ret = NULL; bool success; m_condition.lock(); m_waitingThreads++; m_condition.unlock(); // Try to get another Runnable for the given timeout success = m_pending.tryGet(ret, m_timeout); m_condition.lock(); m_waitingThreads--; // Decrement the current thread count if the get failed (because the // thread will stop) and add the thread to the list of stopped threads. if (!success) { m_threadCount--; m_stopped.push_back(caller); } m_condition.signalAll(); m_condition.unlock(); return ret; } void ThreadPool::joinStopped() { for (uint32 i = 0; i < m_stopped.size(); i++) { WorkerThread* stoppedThread = m_stopped.at(i); delete stoppedThread; } m_stopped.clear(); }
[ "scott.conger@2a29f4a4-5970-11de-9a1b-6103e4980ab8" ]
[ [ [ 1, 164 ] ] ]
ab7bb10feff0fa644a32562721b233a12b67c908
6e563096253fe45a51956dde69e96c73c5ed3c18
/os/AX_Logger.cpp
504256e8f574e7c7eba861cb55dd52aae2ae899b
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
GB18030
C++
false
false
9,629
cpp
#include "AX_Logger.h" #include <fcntl.h> #include <time.h> #include <sys/stat.h> #ifdef WIN32 #include <io.h> #include <share.h> #include <direct.h> #include <assert.h> #include <tchar.h> #pragma warning(disable : 4996) #else #include <stdlib.h> #include <unistd.h> #include <stdarg.h> #include <errno.h> #endif #ifndef assert #define assert #endif bool CFileLogHandler::m_forceFlush=false; int CFileLogHandler::_controlcout = 0; //AX_Mutex CFileLogHandler::mutex; CLogRecord::CLogRecord(LEVEL level, const char* loggerName, const char* message, const char* sourceFile, unsigned int sourceLine) : m_loggerName(loggerName), m_message(message), m_sourceFile(sourceFile) { m_level = level; ftime(&m_timeStamp); m_sourceLine = sourceLine; } int CLogRecord::GetFormatedMessage(string& result,bool bformat) { if (bformat) { char tempBuffer[256]; struct tm* tempTm = localtime(&m_timeStamp.time); result += "Logger name: "; result += m_loggerName; result += "\nLevel: "; result += levelNames[m_level]; strftime(tempBuffer, 255, "%d/%m/%Y %H:%M:%S.", tempTm); result += "\nTime: "; result += tempBuffer; sprintf(tempBuffer, "%u", m_timeStamp.millitm); result += tempBuffer; result += "\nSequence: "; sprintf(tempBuffer, "%u", m_sequenceNumber); result += tempBuffer; result += "\nSource file: "; result += m_sourceFile; result += "\nSource line: "; sprintf(tempBuffer, "%u", m_sourceLine); result += tempBuffer; result += "\nMessage: "; result += m_message; result += "\n\n"; } else { result += m_message; result += "\n"; } return 0; } CFileLogHandler::CFileLogHandler(LEVEL level, const char* fileName, unsigned int maxLength, bool console,bool format) : CLogHandler(level,format), m_fileName(fileName) { m_maxLength = maxLength; m_pBuf = NULL; if ( console) { _controlcout++; m_fileHandler = 2; } else { if ( MakeSureDirectoryExist(fileName) ) { OpenLogFile(); } m_pBuf = new char[DEFAULT_LOG_BUF_LEN]; m_bufLen = DEFAULT_LOG_BUF_LEN; m_writePos = 0; } } CFileLogHandler::~CFileLogHandler() { FlushRecords(); //关闭文件 #ifdef WIN32 //mutex.acquire(); //_controlcout --; //mutex.release(); if (_controlcout <=0) { _close(m_fileHandler); } #else if (m_fileHandler != -1) { close(m_fileHandler); m_fileHandler = -1; } #endif if ( NULL != m_pBuf ) { delete []m_pBuf; m_pBuf = NULL; } } void CFileLogHandler::SetBuffer(int bufLen) { if ( m_bufLen != bufLen && bufLen >= MIN_LOG_BUF_LEN ) { if ( NULL != m_pBuf ) { delete []m_pBuf; m_pBuf = NULL; } m_pBuf = new char[bufLen]; m_bufLen = bufLen; } } bool CFileLogHandler::Publish(CLogRecord& record) { if (GetLevel() == LEVEL_OFF) { return true; } if (record.GetLevel() < GetLevel()) { return true; } record.SetSequenceNumber(m_sequenceNumber++); string buffer(""); record.GetFormatedMessage(buffer, m_format); int len = (int)buffer.size(); if ( 2 == m_fileHandler) { //控制台,直接写入 #ifdef WIN32 if (_write(m_fileHandler, buffer.c_str(), len) != len) #else if (write(m_fileHandler, buffer.c_str(), len) != len) #endif { assert(false); return false; } } else if ( m_fileHandler != -1 ) { const char* data = buffer.c_str(); int freeLen = m_bufLen - m_writePos; int writelen = (freeLen > len) ? len : freeLen; memcpy(m_pBuf + m_writePos, data, writelen); m_writePos += writelen; #ifndef WIN32 m_forceFlush = true; #endif //如果缓存已满,就写入到磁盘 if ( m_writePos == m_bufLen || (m_forceFlush && 0<m_writePos)) { m_forceFlush=false; if(FlushRecords() < 0) { return false; } //检查文件大小是否到上限 #ifdef WIN32 struct _stat statistics; if (m_fileHandler != -1 && _fstat(m_fileHandler, &statistics) == 0) //如果磁盘满FlushRecords会将句柄给关掉 #else struct stat statistics; if (m_fileHandler != -1 && fstat(m_fileHandler, &statistics) == 0) #endif { if ((unsigned int)statistics.st_size >= m_maxLength) { #ifdef WIN32 _close(m_fileHandler); #else close(m_fileHandler); #endif m_fileHandler = -1; //打开新的日志文件 OpenLogFile(); } } } //end of if ( m_writePos + len >= m_bufLen ) //剩余数据写入到缓存 int remainLen = len - writelen; if ( remainLen > 0 && m_pBuf != NULL ) { memcpy(m_pBuf + m_writePos, data + writelen, remainLen); m_writePos += remainLen; } } // FlushRecords(); return true; } void CFileLogHandler::ForceFlush() { m_forceFlush=true; } int CFileLogHandler::FlushRecords() { if ( -1 == m_fileHandler || 2 == m_fileHandler ) { return -1; } #ifdef WIN32 int writeLen = _write(m_fileHandler, m_pBuf, m_writePos); #else int writeLen = write(m_fileHandler, m_pBuf, m_writePos); #endif if (writeLen != m_writePos) { //assert(false); if ( writeLen != -1 ) { memmove(m_pBuf, m_pBuf + writeLen, m_writePos - writeLen); m_writePos -= writeLen; } else { //写入失败,就打开新的文件来写入 #ifdef WIN32 _close(m_fileHandler); #else close(m_fileHandler); #endif m_fileHandler = -1; //打开新的日志文件 if (errno != ENOSPC) ///等缓冲区的长度大于磁盘空间的时候,会进入到这里 { OpenLogFile(); return FlushRecords(); } else return -2; } } else { m_writePos = 0; } return 0; } bool CFileLogHandler::MakeSureDirectoryExist(const char* dir) { char temp[256]; int len = (int)strlen(dir); strcpy(temp, dir); for ( int i = 0; i < len; ++i ) { //windows下的分隔符可能是'\\' if ( dir[i] == '\\' || dir[i] == '/' ) { //将该字符设成结束符,temp可以截取前面一段作为字符串访问 temp[i] = '\0'; #ifdef WIN32 if ( _access(temp, 0) == -1 ) { if ( _mkdir(temp) == -1 ) { #else if ( access(temp, 0) == -1 ) { if ( mkdir(temp, 0777) == -1 ) { #endif return false; } } //再将该字符还原,以便访问下个目录 temp[i] = dir[i]; } } return true; } inline bool CFileLogHandler::OpenLogFile() { time_t curtime = time(NULL); struct tm* temp = localtime(&curtime); char filename[256]; sprintf(filename, "%s_%02d_%02d_%02d_%02d_%02d_%02d.log", m_fileName.c_str(), temp->tm_year + 1900, temp->tm_mon + 1, temp->tm_mday, temp->tm_hour, temp->tm_min, temp->tm_sec); #ifdef WIN32 m_fileHandler = _sopen(filename, _O_CREAT | _O_APPEND | _O_BINARY | _O_WRONLY, _SH_DENYNO, _S_IREAD | _S_IWRITE); #else m_fileHandler = open(filename, O_CREAT | O_APPEND | O_WRONLY, S_IREAD | S_IWRITE); #endif if ( -1 == m_fileHandler ) { if (errno != ENOSPC) { assert(false); } //printf("-1 == m_fileHandler errno:%d\n",errno); //DWORD dwError = GetLastError(); return false; } return true; } CLogger::CLogger(const char* loggerName) : m_loggerName(loggerName) { memset(m_logHandlers, 0, sizeof(m_logHandlers)); } bool CLogger::log(LEVEL level, const char* sourceFile, unsigned int sourceLine, const char* message) { CLogRecord record(level, m_loggerName.c_str(), message, sourceFile, sourceLine); m_mutex.acquire(); for (int i = 0; i < MAX_LOG_HANDLERS_NUMBER; i++) { if (m_logHandlers[i] != NULL) { if ( !m_logHandlers[i]->Publish(record) ) { assert(false); } } } m_mutex.release(); return true; } int CLogger::AddHandler(CLogHandler* logHandler) { int i = 0; int freeIndex = -1; m_mutex.acquire(); for (i = 0; i < MAX_LOG_HANDLERS_NUMBER; i++) { if (m_logHandlers[i] == logHandler) { m_mutex.release(); return true; } else if ( NULL == m_logHandlers[i] && -1 == freeIndex ) { freeIndex = i; } } if ( -1 != freeIndex ) { m_logHandlers[freeIndex] = logHandler; m_mutex.release(); return true; } m_mutex.release(); return freeIndex; } CLogHandler* CLogger::GetHandlerAt(int index) { m_mutex.acquire(); CLogHandler *temp = NULL; if (index < MAX_LOG_HANDLERS_NUMBER) { temp = m_logHandlers[index]; } m_mutex.release(); return temp; } CLogHandler* CLogger::RemoveHandlerAt(int index) { m_mutex.acquire(); if (index >= MAX_LOG_HANDLERS_NUMBER) { m_mutex.release(); return NULL; } CLogHandler* result = m_logHandlers[index]; m_logHandlers[index] = NULL; m_mutex.release(); return result; } static char buffer[1024] = {0}; bool CLogger::logf(LEVEL level, const char* sourceFile, unsigned int sourceLine, const char* message,...) { va_list argp; m_mutex.acquire(); va_start(argp, message); #ifdef _WIN32 _vsnprintf ((char*) buffer, sizeof (buffer) / sizeof (char), (const char*)message, argp) ; #else vsnprintf ((char*) buffer, sizeof (buffer) / sizeof (char), (const char*)message, argp) ; #endif va_end(argp); CLogRecord record(level, m_loggerName.c_str(), buffer, sourceFile, sourceLine); for (int i = 0; i < MAX_LOG_HANDLERS_NUMBER; i++) { if (m_logHandlers[i] != NULL) { if ( !m_logHandlers[i]->Publish(record) ) { //assert(false); } } } m_mutex.release(); return true; }
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 479 ] ] ]
6881c70202d3ef5a23834958227066d5ac2f24e1
651639abcfc06818971a0296944703b3dd050e8d
/MoveDownEvent.cpp
edf99cca8d89ad2c4cc8d5e1af0052fac85b0f9a
[]
no_license
reanag/snailfight
5256dc373e3f3f3349f77c7e684cb0a52ccc5175
c4f157226faa31d526684233f3c5cd4572949698
refs/heads/master
2021-01-19T07:34:17.122734
2010-01-20T17:16:36
2010-01-20T17:16:36
34,893,173
0
0
null
null
null
null
UTF-8
C++
false
false
361
cpp
#include "MoveDownEvent.hpp" MoveDownEvent::MoveDownEvent(){ EventName = "5MoveRightEvent"; } MoveDownEvent::MoveDownEvent(string s){ for(int i = 0; i<s.size(); i++){ if(s.at(i)=='!'){ break; } EventName +=s.at(i); } } string MoveDownEvent::EventToString(){ return EventName+"!"; }
[ "[email protected]@96fa20d8-dc45-11de-8f20-5962d2c82ea8" ]
[ [ [ 1, 20 ] ] ]
c2bd89b3ec4b793b56109f4979f4178f47881cee
bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed
/kguitext.cpp
382c4dff468125b9906f6bdab0d454c3d7bda4af
[]
no_license
cnsuhao/kgui-1
d0a7d1e11cc5c15d098114051fabf6218f26fb96
ea304953c7f5579487769258b55f34a1c680e3ed
refs/heads/master
2021-05-28T22:52:18.733717
2011-03-10T03:10:47
2011-03-10T03:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,131
cpp
/*********************************************************************************/ /* kGUI - kguitext.cpp */ /* */ /* Initially Designed and Programmed by Kevin Pickell */ /* */ /* http://code.google.com/p/kgui/ */ /* */ /* kGUI is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU Lesser General Public License as published by*/ /* the Free Software Foundation; version 2. */ /* */ /* kGUI 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. */ /* */ /* http://www.gnu.org/licenses/lgpl.txt */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with kGUI; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* */ /*********************************************************************************/ /*! @file kguitext.cpp @brief This is the static text object, static text can have a single font/color/size or can be 'rich' and each character can have it's own font/color/size There is also a scroll text object kGUIScrollTextObj. a scroll text object is just static text with a left arrow on the left and a right arrow on the right, if either of these arrows are pressed then a callback is triggered allowing the users code to change the text. An example would be for users selecting a "month", the text would default to a particular month, then pressing the left button would have the month decrement down to January and if the right arrow is pressed it would increment up to December. The callback would be the code to change the text itself. */ #include "kgui.h" //this should not have m_ since that is the member prefix! #define m_xoff 3 #define m_yoff 3 void kGUITextObj::Control(unsigned int command,KGCONTROL_DEF *data) { switch(command) { case KGCONTROL_GETSKIPTAB: data->m_bool=true; break; default: kGUIObj::Control(command,data); break; } } void kGUITextObj::Changed() { /* only expand to fit, don't shrink */ SetSize(MAX((int)GetWidth()+(m_xoff<<1),GetZoneW()),MAX((int)GetLineHeight()+(m_yoff<<1),GetZoneH())); Dirty(); } const unsigned int kGUIText::GetWidest(void) { int i; unsigned int maxw=0; kGUIInputLineInfo *lbptr; /* get widest */ if(m_llnum<2) return(GetWidth()); else { for(i=0;i<m_llnum;++i) { lbptr=m_linelist.GetEntry(i); maxw=MAX(lbptr->pixwidth,maxw); } } return(maxw); } /* if the text is too wide, then shrink the font size until it fits */ void kGUITextObj::ShrinktoFit(void) { int fontsize; int w=GetZoneW(); int h=GetZoneH(); fontsize=GetFontSize(); CalcLineList(w); while( ((((int)GetWidest()+m_xoff+m_xoff)>w) || ((int)GetTotalHeight()+m_yoff+m_yoff)>h) && (fontsize>1)) { SetFontSize(--fontsize); SetSize(w,h); CalcLineList(w); } } void kGUITextObj::Draw(void) { kGUICorners c; int w=GetZoneW(); int h=GetZoneH(); kGUI::PushClip(); GetCorners(&c); kGUI::ShrinkClip(&c); /* is there anywhere to draw? */ if(kGUI::ValidClip()) { if(ImCurrent()) SetRevRange(0,GetLen()); else SetRevRange(0,0); if(GetUseBGColor()==true) kGUI::DrawRect(c.lx,c.ty,c.rx,c.by,GetBGColor()); kGUIText::Draw(c.lx+m_xoff,c.ty+m_yoff,w-(m_xoff+m_xoff),h-(m_yoff+m_yoff)); } kGUI::PopClip(); } /* since this is static text there is no real input needed except */ /* that it can be used for clicking to trigger popup menus etc. */ /* so it handles click callbacks */ bool kGUITextObj::UpdateInput(void) { if(kGUI::GetMouseReleaseLeft()==true) CallEvent(EVENT_LEFTCLICK); if(kGUI::GetMouseDoubleClickLeft()==true) CallEvent(EVENT_LEFTDOUBLECLICK); return(true); } /********************************************************************/ kGUIScrollTextObj::kGUIScrollTextObj() { SetHAlign(FT_CENTER); SetVAlign(FT_MIDDLE); } bool kGUIScrollTextObj::UpdateInput(void) { if(kGUI::GetMouseClickLeft()==true) { kGUICorners c; kGUIEvent e; int w=kGUI::GetSkin()->GetScrollHorizButtonWidths(); GetCorners(&c); if(kGUI::GetMouseX()<(c.lx+w)) { e.m_value[0].i=-1; CallEvent(EVENT_PRESSED,&e); /* left arrow button was pressed */ } else if(kGUI::GetMouseX()>(c.rx-w)) { e.m_value[0].i=1; CallEvent(EVENT_PRESSED,&e); /* right arrow button was pressed */ } else { if(kGUI::GetMouseDoubleClickLeft()==true) CallEvent(EVENT_LEFTDOUBLECLICK); else CallEvent(EVENT_LEFTCLICK); } kGUI::CallAAParents(this); } return(true); } void kGUIScrollTextObj::Draw(void) { kGUICorners c; GetCorners(&c); kGUI::GetSkin()->DrawScrollHoriz(&c); SetColor(DrawColor(0,0,0)); //should this be here??? should use the defined color not force black kGUIText::Draw(c.lx,c.ty,c.rx-c.lx,c.by-c.ty); }
[ "[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d" ]
[ [ [ 1, 188 ] ] ]
bb6e2a92ecda9d5955d118d41d5fc83e2bad26f9
73861c79fbe4cb57e6f4a75369519cbe43a0406e
/KTB_Mortgage/ResultNewMortgage.cpp
6dec69940e2440142c84074506cf731fbcab24a7
[]
no_license
hunganhu/dac
5d8cc276601fa8e7e23fa84ae003da51128c48af
a48c7a58578b3503edd564b9ca23eed1926d9642
refs/heads/master
2022-07-28T04:50:00.442444
2007-10-26T02:41:58
2007-10-26T02:41:58
266,997,798
0
0
null
null
null
null
BIG5
C++
false
false
4,817
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "ResultNewMortgage.h" #include "LoanTypeSelection.h" #include "dm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TfrmRegularResult *frmRegularResult; extern AnsiString case_sn; extern AnsiString connection_string_module; //--------------------------------------------------------------------------- __fastcall TfrmRegularResult::TfrmRegularResult(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TfrmRegularResult::btnEndClick(TObject *Sender) { Application->Terminate(); } //--------------------------------------------------------------------------- void __fastcall TfrmRegularResult::btnNextClick(TObject *Sender) { frmSelection->Show(); frmRegularResult->Hide(); } //--------------------------------------------------------------------------- void __fastcall TfrmRegularResult::btnScoreClick(TObject *Sender) { init(case_sn); char c_message[256]; AnsiString message = lblExecution->Caption; int return_code = 0; return_code = FM_New(case_sn.c_str(), connection_string_module.c_str(), c_message); if(return_code != 0){ message += static_cast<AnsiString>(c_message); lblExecution->Caption = message; } else{ message += "評分完成\n"; lblExecution->Caption = message; try{ fill_result(Data->query, case_sn); } catch(Exception &Err){ message += Err.Message; lblExecution->Caption = message; }; }; frmRegularResult->Refresh(); }; void __fastcall TfrmRegularResult::fill_result(TADOQuery *query, const AnsiString &case_sn) { AnsiString sql_stmt; unsigned int amount; double rate1, rate2, rate3; sql_stmt = "SELECT * FROM APP_RESULT AS A INNER JOIN APP_INFO AS B "; sql_stmt += "ON A.CASE_NO = B.CASE_NO WHERE A.CASE_NO = :case_sn"; sql_stmt = sql_stmt.UpperCase(); query->Close(); query->SQL->Clear(); query->SQL->Add(sql_stmt); query->Parameters->ParamValues["case_sn"] = case_sn; query->Open(); if(query->RecordCount == 0) lblExecution->Caption = "程式錯誤,沒有找到評分結果,請聯絡DAC\n"; else{ amount = query->FieldValues["APPROVED_AMOUNT"].IsNull() ? 0 : query->FieldValues["APPROVED_AMOUNT"]; amount /= 10000; if(amount == 0) lblAmount->Caption = ""; else lblAmount->Caption = amount; if(query->FieldValues["MIN_RATE1"].IsNull()) rate1 = 0; else rate1 = query->FieldValues["MIN_RATE1"]; rate1 *= 100; if(query->FieldValues["MIN_RATE1"].IsNull()) lblRate1->Caption = ""; else lblRate1->Caption = rate1; if(query->FieldValues["MIN_RATE2"].IsNull()) rate2 = 0; else rate2 = query->FieldValues["MIN_RATE2"]; rate2 *= 100; if(query->FieldValues["MIN_RATE2"].IsNull()) lblRate2->Caption = ""; else lblRate2->Caption = rate2; if(query->FieldValues["MIN_RATE3"].IsNull()) rate3 = 0; else rate3 = query->FieldValues["MIN_RATE3"]; rate3 *= 100; if(query->FieldValues["MIN_RATE3"].IsNull()) lblRate3->Caption = ""; else lblRate3->Caption = rate3; if(query->FieldValues["SEG1"].IsNull() || rate1 == 0) lblPeriod1->Caption = ""; else lblPeriod1->Caption = query->FieldValues["SEG1"]; if(query->FieldValues["SEG2"].IsNull() || rate2 == 0) lblPeriod2->Caption = ""; else lblPeriod2->Caption = query->FieldValues["SEG2"]; if(query->FieldValues["SEG3"].IsNull() || rate3 == 0) lblPeriod3->Caption = ""; else lblPeriod3->Caption = query->FieldValues["SEG3"]; if(query->FieldValues["SUGG_MSG"].IsNull()) lblSuggestion1->Caption = ""; else lblSuggestion1->Caption = query->FieldValues["SUGG_MSG"]; if(query->FieldValues["REASON_MSG"].IsNull()) lblSuggestion2->Caption = ""; else lblSuggestion2->Caption = query->FieldValues["REASON_MSG"]; }; frmRegularResult->Refresh(); }; void __fastcall TfrmRegularResult::init(const AnsiString &case_sn) { lblSN->Caption = case_sn; lblAmount->Caption = ""; lblPeriod1->Caption = ""; lblPeriod2->Caption = ""; lblPeriod3->Caption = ""; lblRate1->Caption = ""; lblRate2->Caption = ""; lblRate3->Caption = ""; lblSuggestion1->Caption = ""; lblSuggestion2->Caption = ""; lblExecution->Caption = "模組評分中\n"; frmRegularResult->Refresh(); }; //---------------------------------------------------------------------------
[ "oliver" ]
[ [ [ 1, 153 ] ] ]
f09bd3adfbcae99eb0e213cf1a9f43e5e5940018
eb0e2d45369a325639098705eb414cb66d25db7a
/end/base.h
736f808860c99278635fe474eaa2dc346808a9f0
[]
no_license
PoRTiLo/Projekt-IMS
3e8c10a43016ba018b1c8dfff860e95f5a679b9d
287865006e5210a6592053324d1df5940e5d387e
refs/heads/master
2020-12-24T15:57:48.050689
2010-12-19T15:03:16
2010-12-19T15:03:16
978,258
0
0
null
null
null
null
UTF-8
C++
false
false
2,794
h
/*IMS - Modelovani a simulace * * Project: Simulator cernobilych stochastickych Petriho siti * File: base.h * Author: Dusan Kovacic, xkovac21, [email protected] * Jaroslav Sendler, xsendl00, [email protected] * * Encoding: UTF-8 * * Description: */ #pragma once #include <vector> #include "coreFunc.h" #include "directedArc.h" #include "statusList.h" #include "baseData.h" #include "gen.h" #include <cstring> using namespace std; class SCBase { protected: //members string m_name; //name unsigned int m_id; //uniq id int m_status; //status vector<SCDirectedArc*> m_directedArcsFrom; //arcs that direct to this object vector<SCDirectedArc*> m_directedArcsTo; //arcs that direct from this object SSBaseData m_data; //data - depends on virtual method SCDirectedArc *m_lastCommited; //last commited place/transition public: //methods virtual void AddTransToCommit(SCTransition *tr); static int EvaluateErrorCode(int code,SCBase* subject = NULL); //checks the error weight SCDirectedArc* GetLastCommitedArc(); //return last commited place/trans void SetLastCommitedArc(SCDirectedArc *directedArc); //sets last commited place/trans string GetName(); //returns current name void SetName(string name); //sets name unsigned int GetId(); //returns current id virtual double GetExactTime(); //returns exact time,the next event of this type ocures virtual int Run(); //tries to commit transition/place virtual void SetProbabCallback(double probab); //sets probabiliy for transitions with zero if they are in probability group virtual bool IsReadyToRun(); //checks if current place/transition is ready to run virtual SSBaseData* GetData(); //returns data, depends on object type virtual int Action(int code, int param = 1); //removes,add marks to current place- depends on parameter int GetStatus(); //returns status int AddDirectedArcFrom(SCDirectedArc *directedArc); //adds arc to vector of all arcs that directs to this place/transition int AddDirectedArcTo(SCDirectedArc *directedArc); //adds arc to vector of all arcs that from to this place/transition bool IsCycle(vector<SCBase*> *base); //checks if this place/transition is in zero time loop vector<SCDirectedArc*>* GetDirectedArcsFrom(); //returns vector of all arcs that directs to this place/transition vector<SCDirectedArc*>* GetDirectedArcsTo(); //returns vector of all arcs that directs from this place/transition SCBase(); //constructor ~SCBase(); //destructor };
[ [ [ 1, 59 ] ] ]
34a9fe6ce4f0b6ca57512aab45e7c8b4b6a7c93f
e02fa80eef98834bf8a042a09d7cb7fe6bf768ba
/MyGUIEngine/src/MyGUI_FooBar.cpp
7c3658fae6fc4aa0766fb406416f59aa99febb84
[]
no_license
MyGUI/mygui-historical
fcd3edede9f6cb694c544b402149abb68c538673
4886073fd4813de80c22eded0b2033a5ba7f425f
refs/heads/master
2021-01-23T16:40:19.477150
2008-03-06T22:19:12
2008-03-06T22:19:12
22,805,225
2
0
null
null
null
null
UTF-8
C++
false
false
6,607
cpp
/*! @file @author Denis Koronchik @date 3/2008 @module */ #include "MyGUI_FooBar.h" #include "MyGUI_Macros.h" #include "MyGUI_Gui.h" #include "MyGUI_StaticImage.h" #include "MyGUI_InputManager.h" namespace MyGUI { FooBar::FooBar(const IntCoord& _coord, Align _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, const Ogre::String & _name) : Widget(_coord, _align, _info, _parent, _name), mSnapDistance(0), mLayout(FBL_COORDS), mWidth(70), mMouseWidget(-1) { Gui::getInstance().addFrameListener(this); } FooBar::~FooBar() { Gui::getInstance().removeFrameListener(this); _removeAllChildItems(); } void FooBar::setPosition(const IntPoint& _pos) { updatePosition(_pos); } void FooBar::setPosition(const IntCoord& _coord) { //updatePosition(pt); } void FooBar::setSize(const IntSize& _size) { updateSize(_size); } void FooBar::_frameEntered(float _time) { IntPoint pt = InputManager::getInstance().getMousePosition(); if ((mCoord.left > pt.left || (mCoord.left + mCoord.width) < pt.left) || (mCoord.top > pt.top || (mCoord.top + mCoord.height) < pt.top)) { if (mMouseWidget != -1) { mMouseWidget = -1; updateItemsLayout(); } mMouseWidget = -1; return; } int n = (int)mItemsOrder.size(); for (int i = 0; i < n; i++) if (checkPoint(pt.left, pt.top, mItemsOrder[i])) if (mMouseWidget != i) { mMouseWidget = i; updateItemsLayout(); return; } } void FooBar::_onMouseDrag(int _left, int _top) { Widget::_onMouseDrag(_left, _top); } bool FooBar::checkPoint(int left, int top, WidgetPtr widget) { IntPoint pt = widget->getPosition(); IntSize sz = widget->getSize(); IntPoint p = getPosition(); int l, t; l = left - p.left; t = top - p.top; if (l < pt.left || l > (pt.left + sz.width)) return false; if (t < pt.top || t > (pt.top + sz.height)) return false; return true; } void FooBar::setSnapDistance(const Ogre::Real &sd) { mSnapDistance = sd; } const Ogre::Real& FooBar::getSnapDistance() const { return mSnapDistance; } void FooBar::setLayout(FooBar::Layout layout) { if (mLayout != layout) { mLayout = layout; updatePosition(getPosition()); updateSize(IntSize(mCoord.width, mCoord.height)); }else mLayout = layout; } FooBar::Layout FooBar::getLayout() const { return mLayout; } void FooBar::setWidth(int width) { mWidth = width; if (mLayout != FBL_COORDS) updateSize(IntSize(mCoord.width, mCoord.height)); } int FooBar::getWidth() const { return mWidth; } void FooBar::updatePosition(const IntPoint& _pos) { int width = (int)Gui::getInstance().getViewWidth(); int height = (int)Gui::getInstance().getViewHeight(); IntPoint pos = _pos; //if (mSnap) { switch(mLayout) { case FBL_COORDS: if (abs(pos.left) <= mSnapDistance) pos.left = 0; if (abs(pos.top) <= mSnapDistance) pos.top = 0; if ( abs(pos.left + mCoord.width - width) < mSnapDistance) pos.left = width - mCoord.width; if ( abs(pos.top + mCoord.height - height) < mSnapDistance) pos.top = height - mCoord.height; break; case FBL_SNAP_BOTTOM: pos.top = height - mWidth; pos.left = 0; break; case FBL_SNAP_LEFT: pos.top = 0; pos.left = 0; break; case FBL_SNAP_RIGHT: pos.top = 0; pos.left = width - mWidth; break; case FBL_SNAP_TOP: pos.top = 0; pos.left = 0; break; } //} Widget::setPosition(pos); } void FooBar::updateSize(const IntSize& _size) { int width = (int)Gui::getInstance().getViewWidth(); int height = (int)Gui::getInstance().getViewHeight(); IntSize size = _size; switch(mLayout) { case FBL_COORDS: break; case FBL_SNAP_BOTTOM: case FBL_SNAP_TOP: size.height = mWidth; size.width = width; break; case FBL_SNAP_LEFT: case FBL_SNAP_RIGHT: size.height = height; size.width = mWidth; break; } Widget::setSize(size); } void FooBar::updateItemsLayout() { updateItemsSize(); updateItemsPosition(); } void FooBar::updateItemsSize() { int n = (int)mItemsOrder.size(); int sz; for (int i = 0; i < n; i++) { WidgetPtr widget = mItemsOrder[i]; if (mMouseWidget != -1) { if (abs(i - mMouseWidget) < 5) sz = mWidth / (1.0 + 0.12 * abs(i - mMouseWidget)); else sz = mWidth / 1.7; }else sz = mWidth / 1.7; widget->setSize(sz, sz); } } void FooBar::updateItemsPosition() { int w, h; //int wp, hp; switch(mLayout) { case FBL_COORDS: break; case FBL_SNAP_LEFT: case FBL_SNAP_RIGHT: w = 0; h = 1; break; case FBL_SNAP_TOP: case FBL_SNAP_BOTTOM: w = 1; h = 0; break; } int n = (int)mItemsOrder.size(); int dw = 20, dh = 20; for (int i = 0; i < n; i++) { IntSize sz = mItemsOrder[i]->getSize(); IntPoint pt; pt.left = (dw + 5) * w; pt.top = (dh + 5) * h; dw += (sz.width + 5) * w; dh += (sz.height + 5) * h; mItemsOrder[i]->setPosition(pt); } } void FooBar::addItem(const Ogre::String &name, const Ogre::String &material) { StaticImagePtr item = createWidget<StaticImage>("FooBarItem", IntCoord(0, 0, mWidth, mWidth), ALIGN_DEFAULT); item->setImageMaterial(material); _addChildItem(name, item); updateItemsLayout(); } void FooBar::removeItem(const Ogre::String &name) { } void FooBar::_addChildItem(const Ogre::String &name, MyGUI::WidgetPtr widget) { if (_isChildItem(name)) return; mItems[name] = widget; mItemsOrder.push_back(widget); } void FooBar::_removeChildItem(const Ogre::String &name) { WidgetMap::iterator it = mItems.find(name); if (it != mItems.end()) { int n = (int)mItemsOrder.size(); for (int i = 0; i < n; i++) if (mItemsOrder[i] == it->second) { mItemsOrder.erase(mItemsOrder.begin() + i); break; } mItems.erase(it); } } bool FooBar::_isChildItem(const Ogre::String &name) { WidgetMap::iterator it = mItems.find(name); if (it != mItems.end()) return true; return false; } void FooBar::_removeAllChildItems() { while (!mItems.empty()) { _destroyChildWidget(mItems.begin()->second); mItems.erase(mItems.begin()); } mItemsOrder.clear(); } }
[ [ [ 1, 349 ] ] ]
589401850d8f759bd4584075b81513adcfb448f2
3449de09f841146a804930f2a51ccafbc4afa804
/C++/CodeJam/practice/Hyphenated.cpp
2c355b03e57edbea174443d3ecdd4c553e11b7c5
[]
no_license
davies/daviescode
0c244f4aebee1eb909ec3de0e4e77db3a5bbacee
bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd
refs/heads/master
2020-06-04T23:32:27.360979
2007-08-19T06:31:49
2007-08-19T06:31:49
32,641,672
1
1
null
null
null
null
UTF-8
C++
false
false
6,027
cpp
// BEGIN CUT HERE // PROBLEM STATEMENT // We want to be able to judge whether text is suitable for a // particular age // group. We will base our judgment on the average length of // a word in the text, so we // need to define what a "word" is. // // We define a "word" to be a maximal sequence of letters // ('A'-'Z' and/or 'a-z') within a // single line. (Maximal means that if 2 letters are adjacent // within a line, they are in the same // word.) But if a line ends with a sequence of one or more // letters immediately // followed by a hyphen ('-') and the next line starts with a // sequence of one or more letters, // all these letters are considered to be in the same word. // It is even possible that a hyphenated // word could extend across several lines (see Example 2). // // Create a class Hyphenated that contains a method avgLength // that is given a // vector <string> lines containing the lines of text and // that returns the average length // of the words within the text. // // // DEFINITION // Class:Hyphenated // Method:avgLength // Parameters:vector <string> // Returns:double // Method signature:double avgLength(vector <string> lines) // // // NOTES // -A return value with either an absolute or relative error // of less than 1.0E-9 is considered correct. // // // CONSTRAINTS // -lines will contain between 1 and 50 elements inclusive. // -Each element of lines will contain between 1 and 50 // characters inclusive. // -Each character in each element of lines will be a letter // ('A-'Z' or 'a'-'z') or will be one of these: ' ', '-', '.' // -At least one element of lines will contain a letter. // // // EXAMPLES // // 0) // {" now is the ex-", "ample. "} // // Returns: 3.75 // // There are 4 words: now, is, the, example // // // 1) // {" now is the ex-", " ample. "} // // Returns: 3.0 // // // There are 5 words: now, is, the, ex, ample // Note that the leading blank prevents the joining of ex // and ample. Also // note that words only consist of letters, so the hyphen // is never a part of // a word. // // // 2) // {"inter-","national-","ization.."} // // Returns: 20.0 // // // // There is only one word. // // 3) // {"All the time I have well-defined "," trouble."} // // Returns: 4.125 // // Note that well-defined consists of 2 separate words. // // 4) // {"hello-","-","-","-","great"} // // Returns: 5.0 // // END CUT HERE #line 97 "Hyphenated.cpp" #include <string> #include <iostream> #include <sstream> #include <vector> #include <queue> #include <list> #include <set> #include <map> #include <cmath> #include <valarray> #include <numeric> #include <functional> #include <algorithm> using namespace std; typedef long long ll; typedef vector<int> VI; typedef vector< VI > VVI; typedef vector<char> VC; typedef vector<string> VS; typedef stringstream SS; typedef istringstream ISS; typedef ostringstream OSS; #define FOR(i,a,b) for(int i=(a);i<int(b);++i) #define REP(i,n) FOR(i,0,n) template<class U,class T> T cast(U x){T y; OSS a; a<<x; ISS b(a.str());b>>y;return y;} #define ALL(v) (v).begin(),(v).end() #define SZ(v) ((int)(v).size()) #define FOUND(v,p) (find(ALL(v),p)!=v.end()) #define DV(v) REP(i,SZ(v)) cout << v[i] << " "; cout << endl #define SUM(v) accumulate(ALL(v),0) #define SE(i) (i)->second class Hyphenated { public: double avgLength(vector <string> s) { int l=0,sum=0,cnt=0; REP(i,SZ(s)) REP(j,SZ(s[i])) { if( isalpha(s[i][j]) ){ l++; if( j==SZ(s[i])-1 ){ sum+=l; cnt++; l=0; } }else if( !(s[i][j] == '-' && j==SZ(s[i])-1 && j-1>=0 && isalpha(s[i][j-1]) && i+1<SZ(s) && SZ(s[i+1])>=1 && isalpha(s[i+1][0])) ) { if( l > 0){ sum+=l; cnt++; l=0; } } } if( l > 0 ) {sum += l; cnt++;} return (double)sum/cnt; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {" now is the ex-", "ample. "} ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 3.75; verify_case(0, Arg1, avgLength(Arg0)); } void test_case_1() { string Arr0[] = {" now is the ex-", " ample. "}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 3.0; verify_case(1, Arg1, avgLength(Arg0)); } void test_case_2() { string Arr0[] = {"inter-","national-","ization.."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 20.0; verify_case(2, Arg1, avgLength(Arg0)); } void test_case_3() { string Arr0[] = {"All the time I have well-defined "," trouble."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 4.125; verify_case(3, Arg1, avgLength(Arg0)); } void test_case_4() { string Arr0[] = {"hello-","-","-","-","great"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); double Arg1 = 5.0; verify_case(4, Arg1, avgLength(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Hyphenated ___test; ___test.run_test(-1); } // END CUT HERE
[ "davies.liu@32811f3b-991a-0410-9d68-c977761b5317" ]
[ [ [ 1, 181 ] ] ]
7150abb4bc9759ad2c35a3d4a99f1954d84221ae
9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed
/CS_153_Data_Structures/assignment5/exception.h
9a31c17932c455e001203750508a2820599def0a
[]
no_license
Mr-Anderson/james_mst_hw
70dbde80838e299f9fa9c5fcc16f4a41eec8263a
83db5f100c56e5bb72fe34d994c83a669218c962
refs/heads/master
2020-05-04T13:15:25.694979
2011-11-30T20:10:15
2011-11-30T20:10:15
2,639,602
2
0
null
null
null
null
UTF-8
C++
false
false
2,173
h
#ifndef EXCEPTION_H #define EXCEPTION_H ////////////////////////////////////////////////////////////////////// /// @file exception.h /// @author James Anderson Section A /// @brief Heder file for exception class for assignment 6 ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @class exception /// @brief Used to handel exceptions thrown in the code ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Exception::Exception (Error_Type _error_code, string _error_message) /// @brief stores the exception name and an error message /// @pre error code must be previously defined and the message must be a string /// @post will store the parameters given to it /// @param Error_Type _error_code stores the error code /// @param string _error_message holds a string with a message for the user ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Error_Type Exception::error_code () /// @brief gives back the Exception error code /// @pre error code must be previously stored /// @post feeds back error code /// @return returns the Error code it has stored ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// @fn Error_Type Exception::error_message () /// @brief gives back the Exception error message /// @pre error message must be previously stored /// @post feeds back error message /// @return returns the Error message it has stored ////////////////////////////////////////////////////////////////////// #include <string> using std::string; enum Error_Type { CONTAINER_FULL, CONTAINER_EMPTY, OUT_OF_BOUNDS, VALUE_EXISTS }; class Exception { public: Exception (Error_Type, string); Error_Type error_code (); string error_message (); private: Error_Type m_error_code; string m_error_message; }; #endif
[ [ [ 1, 51 ] ] ]
f23e90f066af7df302ba20e6c6375bf98e177684
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/spirit/fusion/test/tie_tests.cpp
f4458acd070c02866ba242eb8ba0b53ea88eae9c
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
ISO-8859-1
C++
false
false
1,986
cpp
/*============================================================================= Copyright (C) 1999-2003 Jaakko Järvi Copyright (c) 2003 Joel de Guzman Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #include <boost/detail/lightweight_test.hpp> #include <boost/spirit/fusion/sequence/tuple.hpp> #include <boost/spirit/fusion/sequence/get.hpp> #include <boost/spirit/fusion/sequence/tie.hpp> #include <boost/spirit/fusion/sequence/make_tuple.hpp> namespace { // something to prevent warnings for unused variables template<class T> void dummy(const T&) {} // no public default constructor class foo { public: explicit foo(int v) : val(v) {} bool operator==(const foo& other) const { return val == other.val; } private: foo() {} int val; }; } int main() { using namespace boost::fusion; int a; char b; foo c(5); tie(a, b, c) = make_tuple(2, 'a', foo(3)); BOOST_TEST(a == 2); BOOST_TEST(b == 'a'); BOOST_TEST(c == foo(3)); tie(a, ignore, c) = make_tuple((short int)5, false, foo(5)); BOOST_TEST(a == 5); BOOST_TEST(b == 'a'); BOOST_TEST(c == foo(5)); // testing assignment from std::pair int i, j; tie (i, j) = std::make_pair(1, 2); BOOST_TEST(i == 1 && j == 2); tuple<int, int, float> ta; #ifdef E11 ta = std::make_pair(1, 2); // should fail, tuple is of length 3, not 2 #endif dummy(ta); // ties cannot be rebound int d = 3; tuple<int&> ti(a); BOOST_TEST(&get<0>(ti) == &a); ti = tuple<int&>(d); BOOST_TEST(&get<0>(ti) == &a); return boost::report_errors(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 79 ] ] ]
11b2705d56c912a63990b5bfe33473861fca4f65
65f587a75567b51375bde5793b4ec44e4b79bc7d
/sklepSeqSkin.h
fc822d4d85402a477bc6692068fa3ea2165c0b88
[]
no_license
discordance/sklepseq
ce4082074afbdb7e4f7185f042ce9e34d42087ef
8d4fa5a2710ba947e51f5572238eececba4fef74
refs/heads/master
2021-01-13T00:15:23.218795
2008-07-20T20:48:44
2008-07-20T20:48:44
49,079,555
0
0
null
null
null
null
UTF-8
C++
false
false
2,796
h
/* ============================================================================== This is an automatically generated file created by the Jucer! Creation date: 26 Jun 2008 7:31:47 pm Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Jucer version: 1.11 ------------------------------------------------------------------------------ The Jucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-6 by Raw Material Software ltd. ============================================================================== */ #ifndef __JUCER_HEADER_SKLEPSEQSKIN_SKLEPSEQSKIN_B664AADE__ #define __JUCER_HEADER_SKLEPSEQSKIN_SKLEPSEQSKIN_B664AADE__ //[Headers] -- You can add your own extra header files here -- #include "juce.h" //[/Headers] //============================================================================== /** //[Comments] An auto-generated component, created by the Jucer. Describe your class and how it works here! //[/Comments] */ class sklepSeqSkin : public LookAndFeel, public Component { public: //============================================================================== sklepSeqSkin (); ~sklepSeqSkin(); //============================================================================== //[UserMethods] -- You can add your own custom methods in this section. void drawDocumentWindowTitleBar (DocumentWindow &window, Graphics &g,int w, int h, int titleSpaceX, int titleSpaceW, const Image *icon, bool drawTitleTextOnLeft); //[/UserMethods] void paint (Graphics& g); void resized(); // Binary resources: static const char* close_window_png; static const int close_window_pngSize; static const char* maximize_window_png; static const int maximize_window_pngSize; //============================================================================== juce_UseDebuggingNewOperator private: //[UserVariables] -- You can add your own custom variables in this section. //[/UserVariables] //============================================================================== //============================================================================== // (prevent copy constructor and operator= being generated..) sklepSeqSkin (const sklepSeqSkin&); const sklepSeqSkin& operator= (const sklepSeqSkin&); }; #endif // __JUCER_HEADER_SKLEPSEQSKIN_SKLEPSEQSKIN_B664AADE__
[ "kubiak.roman@0c9c7eae-764f-0410-aff0-6774c5161e44" ]
[ [ [ 1, 78 ] ] ]
307763b591962209963b0f9284f3f7e2d6e79beb
0c930838cc851594c9eceab6d3bafe2ceb62500d
/include/jflib/timeseries/impl/numericts_impl.hpp
f7827e01b50b52d99de5102da667db2229f49195
[ "BSD-3-Clause" ]
permissive
quantmind/jflib
377a394c17733be9294bbf7056dd8082675cc111
cc240d2982f1f1e7e9a8629a5db3be434d0f207d
refs/heads/master
2021-01-19T07:42:43.692197
2010-04-19T22:04:51
2010-04-19T22:04:51
439,289
4
3
null
null
null
null
UTF-8
C++
false
false
8,694
hpp
namespace jflib { namespace timeseries { namespace numeric { namespace { ///////////////////////////////////////////////////////////////////////////////////////// // 1. number - tserie template<class tstype, template<class,class> class Op> class tsoperator<tstype, typename tstype::mapped_type, Op, tstype>: public tsOperImpl<tstype> { public: typedef tsOperImpl<tstype> basetype; typedef typename tstype::key_type key_type; typedef typename tstype::mapped_type numtype; typedef typename tstype::const_iterator const_iterator; typedef typename basetype::pairptr pairptr; typedef Op<numtype,numtype> optype; tsoperator(numtype lhs, const tstype& rhs):m_num(lhs),m_ts(rhs){} bool iterable() const {return true;} pairptr find(const key_type& key) const { const_iterator it = m_ts->find(key); if(it != m_ts->end()) return m_pair->available(key,optype::apply(m_num,it->second)); else return 0; } void fill(tstype& ts) const { for(const_iterator it=m_ts.begin(); it!=m_ts.end(); ++it) { ts.insert(value_type(it->first,optype::apply(m_num,it->second))); } } protected: friend class tsoper; numtype m_num; tstype m_ts; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 2. timeseries - number template<template<class,class> class Op> class tsoperator<tsoper::tstype,Op,double>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tstype& lhs, numtype rhs):m_num(rhs),m_ts(&lhs){} pairptr find(const key_type& key) const { const_iterator it = m_ts->find(key); if(it != m_ts->end()) return m_pair->available(key,optype::apply(it->second,m_num)); else return 0; } void fill(tstype& ts) const { for(const_iterator it=m_ts->begin(); it!=m_ts->end(); ++it) { ts.insert(value_type(it->first,optype::apply(it->second,m_num))); } } protected: friend class tsoper; numtype m_num; const tstype* m_ts; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 3. number - tsoper template<template<class,class> class Op> class tsoperator<double,Op,tsoper>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(numtype lhs, const tsoper& rhs):m_num(lhs),m_ts(rhs){} pairptr find(const key_type& key) const { pairptr it = m_ts.find(key); if(it) { it->second = optype::apply(m_num,it->second); return it; } else return 0; } void fill(tstype& ts) const { m_ts.fill(ts); for(tstype::iterator it=ts.begin();it!=ts.end();++it) { it->second = optype::apply(m_num,it->second); } } protected: friend class tsoper; numtype m_num; tsoper m_ts; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 4. tsoper - number template<template<class,class> class Op> class tsoperator<tsoper,Op,double>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tsoper& lhs, numtype rhs):m_num(rhs),m_ts(lhs){} pairptr find(const key_type& key) const { pairptr it = m_ts.find(key); if(it) { it->second = optype::apply(it->second,m_num); return it; } else return 0; } void fill(tstype& ts) const { m_ts.fill(ts); for(tstype::iterator it=ts.begin();it!=ts.end();++it) { it->second = optype::apply(it->second,m_num); } } protected: friend class tsoper; numtype m_num; tsoper m_ts; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 5. tstype - tstype template<template<class,class> class Op> class tsoperator<tsoper::tstype,Op,tsoper::tstype>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tstype& elem1, const tstype& elem2):m_elem1(&elem1),m_elem2(&elem2){} pairptr find(const key_type& key) const { const_iterator il = m_elem1->find(key); const_iterator ir = m_elem2->find(key); if(il != m_elem1->end() && ir != m_elem2->end()) return m_pair->available(key,optype::apply(il->second,ir->second)); else return 0; } void fill(tstype& ts) const { const_iterator ir; for(const_iterator il=m_elem1->begin(); il!=m_elem1->end(); ++il) { ir = m_elem2->find(il->first); if(ir != m_elem2->end()) { ts.insert(value_type(ir->first,optype::apply(il->second,ir->second))); } } } protected: friend class tsoper; const tstype* m_elem1; const tstype* m_elem2; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 6. tstype - tsoper template<template<class,class> class Op> class tsoperator<tsoper::tstype,Op,tsoper>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tstype& elem1, const tsoper& elem2):m_elem1(&elem1),m_elem2(elem2){} pairptr find(const key_type& key) const { const_iterator it = m_elem1->find(key); if(it != m_elem1->end()) { pairptr pa = m_elem2.find(key); if(pa) { pa->second = optype::apply(it->second,pa->second); return pa; } } return 0; } void fill(tstype& ts) const { const_iterator ir; pairptr pa; for(const_iterator it=m_elem1->begin(); it!=m_elem1->end(); ++it) { pa = m_elem2.find(it->first); if(pa) { pa->second = optype::apply(it->second,pa->second); ts.insert(value_type(pa->first,pa->second)); } } } protected: friend class tsoper; const tstype* m_elem1; tsoper m_elem2; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 7. tsoper - tstype template<template<class,class> class Op> class tsoperator<tsoper,Op,tsoper::tstype>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tsoper& elem1, const tstype& elem2):m_elem1(&elem2),m_elem2(elem1){} pairptr find(const key_type& key) const { const_iterator it = m_elem1->find(key); if(it != m_elem1->end()) { pairptr pa = m_elem2.find(key); if(pa) { pa->second = optype::apply(pa->second,it->second); return pa; } } return 0; } void fill(tstype& ts) const { pairptr pa; for(const_iterator it=m_elem1->begin(); it!=m_elem1->end(); ++it) { pa = m_elem2.find(it->first); if(pa) { pa->second = optype::apply(pa->second,it->second); ts.insert(value_type(pa->first,pa->second)); } } } protected: friend class tsoper; const tstype* m_elem1; tsoper m_elem2; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; ///////////////////////////////////////////////////////////////////////////////////////// // 8. tsoper - tsoper // This is the most inefficient of operations since it requires a double search template<template<class,class> class Op> class tsoperator<tsoper,Op,tsoper>: public tsOperImpl { public: typedef Op<numtype,numtype> optype; tsoperator(const tsoper& elem1, const tsoper& elem2):m_elem1(elem1),m_elem2(elem2){} pairptr find(const key_type& key) const { pairptr il = m_elem1.find(key); if(il) { pairptr ir = m_elem2.find(key); if(ir) { ir->second = optype::apply(il->second,ir->second); return ir; } } return 0; } void fill(tstype& ts) const { m_elem1.fill(ts); pairptr pa; for(iterator it = ts.begin(); it != ts.end(); ++it) { pa = m_elem2.find(it->first); if(pa) it->second = optype::apply(it->second, pa->second); else { ts.erase(it++); } } } protected: friend class tsoper; tsoper m_elem1; tsoper m_elem2; private: tsoperator(const tsoperator& rhs); tsoperator& operator = (const tsoperator& rhs); }; }}}}
[ [ [ 1, 308 ] ] ]
5b2f4cd9d14e6dede341d2f20ac37a12c12aab06
4b61c42390888ca65455051932ddc9f6996b0db4
/Vector2.h
3b3dee272d199882471ef57e6fc15cd75434b823
[]
no_license
miyabiarts/math
916558fb152c67286931494a62909a5bcdf1be0b
eceefff9604f58559eb000876172c4fc3e3ced7c
refs/heads/master
2016-09-06T16:21:14.864762
2011-04-18T13:48:04
2011-04-18T13:48:04
1,630,636
0
0
null
null
null
null
UTF-8
C++
false
false
5,158
h
#pragma once #include <cmath> //! 2D vector template < typename T = double > struct Vector2 { Vector2< T >(); Vector2< T >( const Vector2< T > & ); Vector2< T >( T x, T y ); template < typename T2 > operator Vector2< T2 > () const { return Vector2< T2 >( static_cast< T2 >( x ), static_cast< T2 >( y ) ); } Vector2< T > operator + () const; Vector2< T > operator - () const; Vector2< T > operator + ( const Vector2< T > &v ) const; Vector2< T > operator - ( const Vector2< T > &v ) const; Vector2< T > operator * ( T s ) const; Vector2< T > operator / ( T s ) const; Vector2< T > &operator += ( const Vector2< T > &); Vector2< T > &operator -= ( const Vector2< T > &); Vector2< T > &operator *= ( T ); Vector2< T > &operator /= ( T ); bool operator == ( const Vector2< T >& ) const; bool operator != ( const Vector2< T >& ) const; // static function /*! @brief normalize vector */ static Vector2< T > &normalize( Vector2< T > &v,const Vector2< T > &v0 ); /*! @brief calculate length */ static T length( const Vector2< T > &v ); /*! @brief calculate norm */ static T norm( const Vector2< T > &v ); /*! @brief calculate distance between vectors */ static T distance( const Vector2< T > &v1, const Vector2< T > &v2 ); /*! @brief calucalate inner product */ static T dot( const Vector2< T > &v1,const Vector2< T > &v2 ); /*! @brief calucalate outer product */ static T ccw( const Vector2< T > &v1, const Vector2< T > &v2 ); union { struct { T x, y; }; T v[ 2 ]; }; }; // template< typename T > inline Vector2< T >::Vector2() { x = y = 0; } // template< typename T > inline Vector2< T >::Vector2( T x, T y ) { this->x = x; this->y = y; } // template< typename T > inline Vector2< T >::Vector2( const Vector2< T > &v ) { x = v.x; y = v.y; } // template< typename T > inline Vector2< T > Vector2< T >::operator +() const { return Vector2< T >( x, y ); } // template< typename T > inline Vector2< T > Vector2< T >::operator -() const { return Vector2< T >( -x, -y ); } // template< typename T > inline Vector2< T > Vector2< T >::operator +( const Vector2< T > &v ) const { return Vector2< T >( x + v.x,y + v.y ); } // template< typename T > inline Vector2< T > Vector2< T >::operator -( const Vector2< T > &v ) const { return Vector2< T >( x - v.x, y - v.y ); } // template< typename T > inline Vector2< T > Vector2< T >::operator *( T s ) const { return Vector2< T >(x*s,y*s); } // template< typename T > inline Vector2< T > Vector2< T >::operator /( T s ) const { return Vector2< T >( x / s, y / s ); } // template< typename T > inline Vector2< T > &Vector2< T >::operator +=( const Vector2< T > &v ) { x += v.x; y += v.y; return *this; } // template< typename T > inline Vector2< T > &Vector2< T >::operator -=( const Vector2< T > &v ) { x -= v.x; y -= v.y; return *this; } // template< typename T > inline Vector2< T > &Vector2< T >::operator *=( T s ) { x *= s; y *= s; return *this; } // template< typename T > inline Vector2< T > &Vector2< T >::operator /=(T s) { x /= s; y /= s; return *this; } // template< typename T > inline bool Vector2< T >::operator ==( const Vector2< T > &v ) const { return ( x == v.x && y == v.y ); } // template< typename T > inline bool Vector2< T >::operator !=(const Vector2< T > &v) const { return !operator==(v); } // template< typename T, typename T2 > inline Vector2< T > operator * ( T2 s, const Vector2< T > &v ) { return Vector2< T >( v.x * s, v.y * s ); } // template< typename T > inline Vector2< T > &Vector2< T >::normalize( Vector2< T > &v, const Vector2< T > &v0 ) { T l = length( v0 ); if( l == 0.0 ) { v = Vector2< T >(); return v; } v = v0 / l; return v; } // template< typename T > inline T Vector2< T >::length( const Vector2< T > &v ) { return static_cast< T >( sqrt( static_cast< double >( v.x * v.x + v.y * v.y ) ) ); } // template< typename T > inline T Vector2< T >::norm( const Vector2< T > &v ) { return v.x * v.x + v.y * v.y; } // template< typename T > inline T Vector2< T >::distance( const Vector2< T > &v1, const Vector2< T > &v2 ) { Vector2< T > v = v1 - v2; return length(v); } // template< typename T > inline T Vector2< T >::dot( const Vector2< T > &v1, const Vector2< T > &v2 ) { return v1.x * v2.x + v1.y * v2.y; } // template< typename T > inline T Vector2< T >::ccw( const Vector2< T > &v1, const Vector2< T > &v2 ) { return v1.x * v2.y - v1.y * v2.x; } /*! output stream */ template< typename T > std::ostream &operator<<( std::ostream &os, const Vector2< T > &v ) { os << v.x << ", " << v.y; return os; } typedef Vector2< unsigned char > Vector2UC; typedef Vector2< int > Vector2I; typedef Vector2< float> Vector2F; typedef Vector2< double > Vector2D;
[ [ [ 1, 256 ] ] ]
d8f0caa1e453a6b3626a23ac8dd3b007e503a435
49f5a108a2ac593b9861f9747bd82eb597b01e24
/src/JSON/JsonOutput.cpp
cd8c6c5885d4238785ffca9e441b84635ce257c3
[]
no_license
gpascale/iSynth
5801b9a1b988303ad77872fad98d4bf76d86e8fe
e45e24590fabb252a5ffd10895b2cddcc988b83d
refs/heads/master
2021-03-19T06:01:57.451784
2010-08-02T02:22:54
2010-08-02T02:22:54
811,695
0
1
null
null
null
null
UTF-8
C++
false
false
9,023
cpp
//#include "Stable.h" #include "JsonOutput.h" int JsonOutBase::nInstances_ = 0; void JsonOutAtom::set(int rhs) { JsonOStringStream s; s<<rhs; set_item(s.str()); } void JsonOutAtom::set(double rhs) { JsonOStringStream oss; oss<<rhs; JsonString s = oss.str(); // ensure no weird characters, e.g. NaN, 1.#ind, etc. if (JsonString::npos != s.find_first_not_of(ToJsonString("0123456789.eE+-"))) { JsonThrow(ToJsonString("bad double in json output")); } set_item(s); } JsonStringW JsonOutAtom::as_wide() const { JsonStringW result; if (item_.size()>=2) { if (item_[0] == JsonChar('"')) { if (item_[item_.size()-1] != JsonChar('"')) { JsonThrow(ToJsonString("unbalanced quotes")); } result = DecodeJsonStringToW(item_.substr(1,item_.size()-2)); } } else { result = ToJsonStringW(item_.c_str()); } return result; } JsonOutArray::JsonOutArray(const JsonOutArray & rhs) : JsonOutBase(rhs), multiline_(rhs.multiline_), items_(rhs.items_.size(), true) { const size_t n = rhs.items_.size(); for (size_t i=0; i<n; ++i) { const JsonOutBase * r = rhs.items_[i]; Refp<JsonOutBase> & p = items_[i]; if (r->is_atom ()) { p = new JsonOutAtom (*((const JsonOutAtom *)r)); } else if (r->is_array()) { p = new JsonOutArray(*((const JsonOutArray *)r)); } else if (r->is_dict ()) { p = new JsonOutDict (*((const JsonOutDict *)r)); } else { b_assert(false); } // corrupt or unknown type? } } JsonOutDict::JsonOutDict(const JsonOutDict & rhs) : JsonOutBase(rhs), multiline_(rhs.multiline_) { Dict::const_iterator it, it1 = rhs.dict_.end(); for (it = rhs.dict_.begin(); it!=it1; ++it) { const JsonString & key = it->first; const JsonOutBase * r = it->second; Refp<JsonOutBase> p; if (r->is_atom ()) { p = new JsonOutAtom (*((const JsonOutAtom *)r)); } else if (r->is_array()) { p = new JsonOutArray(*((const JsonOutArray *)r)); } else if (r->is_dict ()) { p = new JsonOutDict (*((const JsonOutDict *)r)); } else { b_assert(false); } // corrupt or unknown type? bool inserted = dict_.insert(Dict::value_type(key, p)).second; b_assert(inserted); // duplicate key? } } static void indent(JsonOStream & out, int indentLevel) { if (indentLevel >= 0) { out << ToJsonString("\n"); for (int i=0; i<indentLevel; ++i) { out << ToJsonString(" "); } } } void JsonOutAtom::serialize(JsonOStream & out, int indentLevel) const { indent(out, indentLevel); out << item_; } JsonOutArray::~JsonOutArray() {} void JsonOutArray::add(JsonOutBase * o) { add_item(o); } void JsonOutArray::add(JsonOutAtom * o) { add_item(o); } void JsonOutArray::add(JsonOutArray * o) { add_item(o); } void JsonOutArray::add(JsonOutDict * o) { add_item(o); } #ifdef JSON_SEADRAGON_TYPES JsonOutArray::JsonOutArray(const DPoint & o) : JsonOutBase(JsonOutTypeArray, true), multiline_(false) { add(o.x); add(o.y); } JsonOutArray::JsonOutArray(const DPoint3 & o) : JsonOutBase(JsonOutTypeArray, true), multiline_(false) { add(o.x); add(o.y); add(o.z); } JsonOutArray::JsonOutArray(const DPoint4 & o) : JsonOutBase(JsonOutTypeArray, true), multiline_(false) { add(o.x); add(o.y); add(o.z); add(o.w); } JsonOutArray::JsonOutArray(const DMatrix4 & o) : JsonOutBase(JsonOutTypeArray, false), multiline_(true) { for (int i=0; i<4; ++i) { add(o[i]); } } void JsonOutArray::add(const DPoint & o) { add_item(new JsonOutArray(o)); } void JsonOutArray::add(const DPoint3 & o) { add_item(new JsonOutArray(o)); } void JsonOutArray::add(const DPoint4 & o) { add_item(new JsonOutArray(o)); } void JsonOutArray::add(const DMatrix4 & o) { add_item(new JsonOutArray(o)); } #endif // JSON_SEADRAGON_TYPES void JsonOutArray::serialize(JsonOStream & out, int indentLevel) const { const int n = int(items_.size()); indent(out, indentLevel); out << ToJsonString("["); if (multiline_ && indentLevel>=0 && n>0) { for (int i=0; i<n; ++i) { if (i) out<<ToJsonString(","); items_[i]->serialize(out, indentLevel+1); } indent(out, indentLevel); } else { for (int i=0; i<n; ++i) { if (i) out<<ToJsonString(","); items_[i]->serialize(out, -1); } } out << ToJsonString("]"); } JsonOutDict::~JsonOutDict() {} void JsonOutDict::add(const JsonString & name, JsonOutBase * value) { Dict::value_type v(name, value); std::pair<Dict::iterator,bool> p = dict_.insert(v); if (!p.second) { // duplicate key b_assert(p.first->first == name); if (value->is_dict()) { const JsonOutDict * src = (const JsonOutDict *)value; if (p.first->second->is_dict()) { // (recursively) copy instead of moving-- JsonOutDict * match = (JsonOutDict *)(&(*(p.first->second))); Dict::const_iterator it, it1 = src->dict_.end(); for (it=src->dict_.begin(); it!=it1; ++it) { match->add(it->first, it->second); } } else { JsonThrow(ToJsonString("attempt to zipper dict into non-dict")); } } else { // value isn't a dict-- OK if atomic and values in perfect agreement JsonOutBase * matchBase = &(*(p.first->second)); if (value->is_atom() && matchBase->is_atom()) { const JsonOutAtom * valueAtom = (const JsonOutAtom *)value; const JsonOutAtom * matchAtom = (const JsonOutAtom *)matchBase; if (*matchAtom != *valueAtom) { JsonThrow(ToJsonString("attempt to zipper nonequal atoms")); } } else { JsonThrow(ToJsonString("attempt to zipper mismatched types")); } } } } void JsonOutDict::add(const JsonString & name, JsonOutAtom * value) { b_assert(value); Dict::value_type v(name, value); std::pair<Dict::iterator,bool> p = dict_.insert(v); if (!p.second) { // duplicate key JsonOutBase * matchBase = &(*(p.first->second)); if (matchBase->is_atom()) { const JsonOutAtom * matchAtom = (const JsonOutAtom *)matchBase; if (*matchAtom != *value) { JsonThrow(ToJsonString("attempt to insert duplicate key with non-equal value")); } } else { JsonThrow(ToJsonString("attempt to insert duplicate key with non-atomic and non-dict value")); } } } #ifdef JSON_SEADRAGON_TYPES void JsonOutDict::add(const JsonString & name, const DPoint & value) { add(name, new JsonOutArray(value)); } void JsonOutDict::add(const JsonString & name, const DPoint3 & value) { add(name, new JsonOutArray(value)); } void JsonOutDict::add(const JsonString & name, const DPoint4 & value) { add(name, new JsonOutArray(value)); } void JsonOutDict::add(const JsonString & name, const DMatrix4 & value) { add(name, new JsonOutArray(value)); } #endif // JSON_SEADRAGON_TYPES void JsonOutDict::zipper_in(const JsonOutBase * rhs) { if (!(rhs->is_dict())) { JsonThrow(ToJsonString("attempt to zipper_in from non-dict")); } const JsonOutDict * src = (const JsonOutDict *)rhs; // (recursively) copy instead of moving-- Dict::const_iterator it, it1 = src->dict_.end(); for (it=src->dict_.begin(); it!=it1; ++it) { add(it->first, it->second); } } void JsonOutDict::serialize(JsonOStream & out, int indentLevel) const { indent(out, indentLevel); out << ToJsonString("{"); bool first = true; Dict::const_iterator it = dict_.begin(), it1 = dict_.end(); if (multiline_ && indentLevel>=0 && it!=it1) { for ( ; it!=it1; ++it) { if (!first) { out<<ToJsonString(","); } first = false; indent(out, indentLevel+1); out << ToJsonString("\"") << it->first << ToJsonString("\": "); const JsonOutBase * item = it->second; const int childIndent = item->trivial() ? -1 : indentLevel+2; item->serialize(out, childIndent); } indent(out, indentLevel); } else { for (it=dict_.begin(); it!=it1; ++it) { if (!first) { out<<ToJsonString(","); } first = false; out << ToJsonString("\"") << it->first << ToJsonString("\":"); it->second->serialize(out, -1); } } out << ToJsonString("}"); }
[ [ [ 1, 254 ] ] ]
d18f6a61180a25bbc2178610e74971d8598af5a3
78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5
/guidriverCEGUIOgre/include/guceCEGUIOgre_CEditboxImp.h
fde50be172ceb3f4bca30363c82c4757104771bd
[]
no_license
LiberatorUSA/GUCE
a2d193e78d91657ccc4eab50fab06de31bc38021
a4d6aa5421f8799cedc7c9f7dc496df4327ac37f
refs/heads/master
2021-01-02T08:14:08.541536
2011-09-08T03:00:46
2011-09-08T03:00:46
41,840,441
0
0
null
null
null
null
UTF-8
C++
false
false
4,422
h
/* * guceCEGUIOgre: glue module for the CEGUI+Ogre GUI backend * Copyright (C) 2002 - 2008. Dinand Vanvelzen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef GUCE_CEGUIOGRE_CEDITBOXIMP_H #define GUCE_CEGUIOGRE_CEDITBOXIMP_H /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #ifndef _CEGUIEditbox_h_ #include "elements/CEGUIEditbox.h" #define _CEGUIEditbox_h_ #endif /* _CEGUIEditbox_h_ ? */ #ifndef GUCE_CEGUIOGRE_CWIDGETIMP_H #include "guceCEGUIOgre_CWidgetImp.h" #define GUCE_CEGUIOGRE_CWIDGETIMP_H #endif /* GUCE_CEGUIOGRE_CWIDGETIMP_H ? */ #ifndef GUCEF_GUI_CEDITBOX_H #include "gucefGUI_CEditbox.h" #define GUCEF_GUI_CEDITBOX_H #endif /* GUCEF_GUI_CEDITBOX_H ? */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCE { namespace CEGUIOGRE { /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ class GUCE_CEGUIOGRE_EXPORT_CPP CEditboxImp : public CWidgetImp< GUCEF::GUI::CEditbox > { public: CEditboxImp( void ); virtual ~CEditboxImp(); virtual bool SetText( const CString& text ); virtual bool GetText( CString& text ); virtual bool SetSelectedText( const CString& text ); virtual bool GetSelectedText( CString& text ); virtual void Clear( void ); void Hook( CEGUI::Editbox* editbox ); private: CEditboxImp( const CEditboxImp& src ); CEditboxImp& operator=( const CEditboxImp& src ); private: CEGUI::Editbox* m_editbox; }; /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace CEGUIOGRE */ }; /* namespace GUCE */ /*-------------------------------------------------------------------------*/ #endif /* GUCE_CEGUIOGRE_CEDITBOXIMP_H ? */ /*-------------------------------------------------------------------------// // // // Info & Changes // // // //-------------------------------------------------------------------------// - 18-08-2007 : - Dinand: Initial implementation -----------------------------------------------------------------------------*/
[ [ [ 1, 111 ] ] ]
fc11559afdaefb45fdcbdbc41b6ffcf43f67a2df
89d2197ed4531892f005d7ee3804774202b1cb8d
/GWEN/src/PlatformWIN32.cpp
c1d254185ebd0b9297daf8d1077a22f7a717ae2c
[ "MIT", "Zlib" ]
permissive
hpidcock/gbsfml
ef8172b6c62b1c17d71d59aec9a7ff2da0131d23
e3aa990dff8c6b95aef92bab3e94affb978409f2
refs/heads/master
2020-05-30T15:01:19.182234
2010-09-29T06:53:53
2010-09-29T06:53:53
35,650,825
0
0
null
null
null
null
UTF-8
C++
false
false
5,145
cpp
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #include "stdafx.h" #include "Gwen/Platform.h" #include <windows.h> #include <mmsystem.h> #pragma comment( lib, "winmm.lib" ) // Ifdef WIN32? using namespace Gwen; using namespace Gwen::Platform; #ifdef UNICODE static LPWSTR iCursorConvertion[] = #else static LPSTR iCursorConvertion[] = #endif { IDC_ARROW, IDC_IBEAM, IDC_SIZENS, IDC_SIZEWE, IDC_SIZENWSE, IDC_SIZENESW, IDC_SIZEALL, IDC_NO, IDC_WAIT, IDC_HAND }; void Gwen::Platform::SetCursor( unsigned char iCursor ) { // Todo.. Properly. ::SetCursor( LoadCursor( NULL, iCursorConvertion[iCursor] ) ); } Gwen::UnicodeString Gwen::Platform::GetClipboardText() { if ( !OpenClipboard( NULL ) ) return L""; HANDLE hData = GetClipboardData( CF_UNICODETEXT ); if( hData == NULL ) { CloseClipboard(); return L""; } wchar_t* buffer = (wchar_t *)GlobalLock( hData ); UnicodeString str = buffer; GlobalUnlock( hData ); CloseClipboard(); return str; } bool Gwen::Platform::SetClipboardText( const Gwen::UnicodeString& str ) { if ( !OpenClipboard( NULL ) ) return false; EmptyClipboard(); // Create a buffer to hold the string size_t iDataSize = (str.length()+1) * sizeof(wchar_t); HGLOBAL clipbuffer = GlobalAlloc( GMEM_DDESHARE, iDataSize ); // Copy the string into the buffer wchar_t* buffer = (wchar_t*) GlobalLock( clipbuffer ); wcscpy_s( buffer, iDataSize, str.c_str() ); GlobalUnlock(clipbuffer); // Place it on the clipboard SetClipboardData( CF_UNICODETEXT, clipbuffer ); CloseClipboard(); return true; } double GetPerformanceFrequency() { static double Frequency = 0.0f; if ( Frequency == 0.0f ) { __int64 perfFreq; QueryPerformanceFrequency( (LARGE_INTEGER*)&perfFreq ); Frequency = 1.0 / (double)perfFreq; } return Frequency; } float Gwen::Platform::GetTimeInSeconds() { #if 1 static float fCurrentTime = 0.0f; static __int64 iLastTime = 0; __int64 thistime; QueryPerformanceCounter( (LARGE_INTEGER*)&thistime ); float fSecondsDifference = (double)( thistime - iLastTime ) * GetPerformanceFrequency(); if ( fSecondsDifference > 0.1f ) fSecondsDifference = 0.1f; fCurrentTime += fSecondsDifference; iLastTime = thistime; return fCurrentTime; #else return timeGetTime() / 1000.0; #endif } bool Gwen::Platform::FileOpen( const String& Name, const String& StartPath, const String& Extension, Gwen::Event::Handler* pHandler, Gwen::Event::FunctionStr fnCallback ) { char Filestring[256]; String returnstring; char FilterBuffer[512]; { memset( FilterBuffer, 0, sizeof(FilterBuffer) ); memcpy( FilterBuffer, Extension.c_str(), min( Extension.size(), 512 ) ); for (int i=0; i<512; i++) { if ( FilterBuffer[i] == '|' ) FilterBuffer[i] = 0; } } OPENFILENAMEA opf; opf.hwndOwner = 0; opf.lpstrFilter = FilterBuffer; opf.lpstrCustomFilter = 0; opf.nMaxCustFilter = 0L; opf.nFilterIndex = 1L; opf.lpstrFile = Filestring; opf.lpstrFile[0] = '\0'; opf.nMaxFile = 256; opf.lpstrFileTitle = 0; opf.nMaxFileTitle=50; opf.lpstrInitialDir = StartPath.c_str(); opf.lpstrTitle = Name.c_str(); opf.nFileOffset = 0; opf.nFileExtension = 0; opf.lpstrDefExt = "*.*"; opf.lpfnHook = NULL; opf.lCustData = 0; opf.Flags = (OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR) & ~OFN_ALLOWMULTISELECT; opf.lStructSize = sizeof(OPENFILENAME); if ( GetOpenFileNameA( &opf ) ) { if ( pHandler && fnCallback ) { (pHandler->*fnCallback)( opf.lpstrFile ); } } else { if ( pHandler && fnCallback ) { (pHandler->*fnCallback)( "" ); } } return true; } bool Gwen::Platform::FileSave( const String& Name, const String& StartPath, const String& Extension, Gwen::Event::Handler* pHandler, Gwen::Event::FunctionStr fnCallback ) { char Filestring[256]; String returnstring; char FilterBuffer[512]; { memset( FilterBuffer, 0, sizeof(FilterBuffer) ); memcpy( FilterBuffer, Extension.c_str(), min( Extension.size(), 512 ) ); for (int i=0; i<512; i++) { if ( FilterBuffer[i] == '|' ) FilterBuffer[i] = 0; } } OPENFILENAMEA opf; opf.hwndOwner = 0; opf.lpstrFilter = FilterBuffer; opf.lpstrCustomFilter = 0; opf.nMaxCustFilter = 0L; opf.nFilterIndex = 1L; opf.lpstrFile = Filestring; opf.lpstrFile[0] = '\0'; opf.nMaxFile = 256; opf.lpstrFileTitle = 0; opf.nMaxFileTitle=50; opf.lpstrInitialDir = StartPath.c_str(); opf.lpstrTitle = Name.c_str(); opf.nFileOffset = 0; opf.nFileExtension = 0; opf.lpstrDefExt = "*.*"; opf.lpfnHook = NULL; opf.lCustData = 0; opf.Flags = (OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR) & ~OFN_ALLOWMULTISELECT; opf.lStructSize = sizeof(OPENFILENAME); if ( GetSaveFileNameA( &opf ) ) { if ( pHandler && fnCallback ) { (pHandler->*fnCallback)( opf.lpstrFile ); } } else { if ( pHandler && fnCallback ) { (pHandler->*fnCallback)( "" ); } } return true; }
[ "haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793" ]
[ [ [ 1, 232 ] ] ]
5a9f38eb78dc0ecb4a35c9d09a1255cd25de8e51
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/mxqedcom.hpp
20caef2d57593b213a80a08efde115dfced90485
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
13,853
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'MXQEDCOM.pas' rev: 6.00 #ifndef MXQEDCOMHPP #define MXQEDCOMHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Windows.hpp> // Pascal unit #include <ComObj.hpp> // Pascal unit #include <ActiveX.hpp> // Pascal unit #include <BDE.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Mxqedcom { //-- type declarations ------------------------------------------------------- typedef Word UINT16; typedef Word *pUINT16; typedef unsigned UINT32; typedef void *pVOID; #pragma option push -b- enum StmtType { sTypeSelect, sTypeInsert, sTypeDelete, sTypeUpdate, sTypeDDL }; #pragma option pop #pragma option push -b- enum JoinType { joinNone, joinInner, joinLeft, joinRight, joinFull }; #pragma option pop #pragma option push -b enum QNodeType { qnodeNA, qnodeAdd, qnodeAvg, qnodeCount, qnodeMax, qnodeMin, qnodeTotal, qnodeAlias, qnodeAnd, qnodeConstant, qnodeDivide, qnodeEqual, qnodeField, qnodeGreaterEq, qnodeGreater, qnodeLessEq, qnodeLike, qnodeLess, qnodeMultiply, qnodeNotEqual, qnodeNot, qnodeOr, qnodeSubtract, qnodeColumn, qnodeCast, qnodeAssign, qnodeIsNull, qnodeExists, qnodeVariable, qnodeSelect, qnodeNegate, qnodeUdf, qnodeIN, qnodeANY, qnodeALL, qnodeTrim, qnodeLower, qnodeUpper, qnodeSubstring, qnodeList, qnodeExtract, qnodeCorrVar, qnodeTrue, qnodeNotAnd, qnodeNotOr, qnodeUnknown, qnodeConcatenate, qnodeGetDateTime }; #pragma option pop class DELPHICLASS IExpr; typedef IExpr* *pIExpr; class DELPHICLASS IField; typedef IField* *pIField; class DELPHICLASS ITable; typedef ITable* *pITable; class DELPHICLASS IProjector; typedef IProjector* *pIProjector; class DELPHICLASS IOrderBy; typedef IOrderBy* *pIOrderBy; class DELPHICLASS IGroupBy; typedef IGroupBy* *pIGroupBy; class DELPHICLASS IJoinExpr; typedef IJoinExpr* *pIJoinExpr; class DELPHICLASS IJoin; typedef IJoin* *pIJoin; __interface IQStmt; typedef System::DelphiInterface<IQStmt> _di_IQStmt; typedef _di_IQStmt *pIQStmt; #pragma option push -b enum ExprCat { exprCatWhere, exprCatHaving }; #pragma option pop #pragma option push -b enum dialect_ansi { DIALECT, ANSI, DIALECTANSI }; #pragma option pop #pragma pack(push, 4) struct DeletedObj { Word iNumProjector; Word iNumWhere; Word iNumJoin; Word iNumGroupBy; Word iNumHaving; Word iNumOrderBy; IProjector* *pProjector; IExpr* *pWhere; IJoin* *pJoin; IGroupBy* *pGroupBy; IExpr* *pHaving; IOrderBy* *pOrderBy; } ; #pragma pack(pop) typedef DeletedObj *pDeletedObj; typedef pDeletedObj *ppDeletedObj; class PASCALIMPLEMENTATION ITable : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall GetName(char * &Name) = 0 ; virtual Word __stdcall GetDbName(char * &DbName) = 0 ; virtual Word __stdcall GetDrvType(char * &DrvType) = 0 ; virtual Word __stdcall GetAlias(char * &Alias) = 0 ; virtual Word __stdcall FetchField(Word FldIndex, IField* &pField) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall ITable(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~ITable(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IProjector : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall GetQualifier(char * &Qualifier) = 0 ; virtual Word __stdcall GetName(char * &Name) = 0 ; virtual Word __stdcall GetIsAliased(BOOL &IsAliased) = 0 ; virtual Word __stdcall GetBaseName(char * &BaseName) = 0 ; virtual Word __stdcall FetchExpr(IExpr* &ppExpr) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IProjector(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IProjector(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IGroupBy : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall FetchField(IField* &ppField) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IGroupBy(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IGroupBy(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IOrderBy : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall GetPosition(Word &Position) = 0 ; virtual Word __stdcall GetIsDescend(BOOL &IsDescend) = 0 ; virtual Word __stdcall ChangeDescend(BOOL bDescend) = 0 ; virtual Word __stdcall FetchProjector(IProjector* &ppProjector) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IOrderBy(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IOrderBy(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IField : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall GetName(char * &ppFldName) = 0 ; virtual Word __stdcall FetchTable(ITable* &ppTable) = 0 ; virtual Word __stdcall GetDataType(Word &iFldType, Word &iSubType) = 0 ; virtual Word __stdcall GetTable_Field(char * &Tbl_Fld) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IField(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IField(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IExpr : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall GetNodeType(QNodeType &nodeType) = 0 ; virtual Word __stdcall GetNumbSubExprs(Word &number) = 0 ; virtual Word __stdcall GetSQLText(char * &ppSQLText) = 0 ; virtual Word __stdcall FetchSubExpr(Word number, IExpr* &ppExpr) = 0 ; virtual Word __stdcall AddSubExpr_Text(char * sqlText, IExpr* &pObj, IExpr* pBefThisObj) = 0 ; virtual Word __stdcall AddSubExpr_node(QNodeType qNodeType, IExpr* &pObj, IExpr* pBefThisObj) = 0 ; virtual Word __stdcall AddSubExpr_field(IField* pField, IExpr* &pObj, pIExpr pBefThisObj) = 0 ; virtual Word __stdcall ChangeNodeType(QNodeType nodeType) = 0 ; virtual Word __stdcall DeleteSubExpr(IExpr* pObj) = 0 ; virtual Word __stdcall MoveSubExpr(IExpr* pObj, IExpr* pBefThisObj) = 0 ; virtual Word __stdcall GetParentExpr(IExpr* pRootExpr, IExpr* &ppParentExpr, IExpr* &ppNextSiblingExpr) = 0 ; virtual Word __stdcall GetNumCells(Word &nCells) = 0 ; virtual Word __stdcall GetCell(Word index, IExpr* &ppCell, char * &ppText1, char * &ppText2) = 0 ; virtual Word __stdcall FetchField(IField* &ppField) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IExpr(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IExpr(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IJoinExpr : public IExpr { typedef IExpr inherited; public: virtual Word __stdcall FetchFieldLeft(IField* &ppField) = 0 ; virtual Word __stdcall FetchFieldRight(IField* &ppField) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IJoinExpr(void) : IExpr() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IJoinExpr(void) { } #pragma option pop }; class PASCALIMPLEMENTATION IJoin : public System::TObject { typedef System::TObject inherited; public: virtual Word __stdcall FetchTableLeft(ITable* &ppTable) = 0 ; virtual Word __stdcall FetchTableRight(ITable* &ppTable) = 0 ; virtual Word __stdcall GetJoinType(JoinType &joinType) = 0 ; virtual Word __stdcall GetNumExprs(Word &number) = 0 ; virtual Word __stdcall GetSQLText(char * &ppSQLText) = 0 ; virtual Word __stdcall FetchJoinExpr(Word number, IExpr* &ppExpr) = 0 ; virtual Word __stdcall GetIndexForJoinExpr(IJoinExpr* pJoinExpr, Word &index) = 0 ; virtual Word __stdcall AddJoinExpr(Word FldNumLeft, Word FldNumRight, QNodeType MathOp, IExpr* &ppObj, IExpr* pBefThisObj) = 0 ; virtual Word __stdcall AddJoinExpr_useFldName(char * FldNameLeft, char * FldNameRight, QNodeType MathOp, IExpr* &ppObj, IExpr* pBefThisObj) = 0 ; virtual Word __stdcall DeleteJoinExpr(IExpr* pObj) = 0 ; virtual Word __stdcall ChangeJoinType(JoinType JoinType_input) = 0 ; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall IJoin(void) : System::TObject() { } #pragma option pop #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~IJoin(void) { } #pragma option pop }; __interface IQStmt : public IInterface { public: virtual Word __stdcall Initialize(Bde::hDBIDb hDb, char * pszQuery) = 0 ; virtual Word __stdcall GetStmtType(StmtType &stmtType) = 0 ; virtual Word __stdcall GetNumInputTables(Word &Num) = 0 ; virtual Word __stdcall GetNumProjectors(Word &Num) = 0 ; virtual Word __stdcall GetNumGroupBy(Word &Num) = 0 ; virtual Word __stdcall GetNumOrderBy(Word &Num) = 0 ; virtual Word __stdcall GetNumJoins(Word &Num) = 0 ; virtual Word __stdcall GetHasWherePred(BOOL &Has) = 0 ; virtual Word __stdcall GetHasHavingPred(BOOL &Has) = 0 ; virtual Word __stdcall GetIsDistinct(BOOL &IsDistinct) = 0 ; virtual Word __stdcall SetDistinct(BOOL IsDistinct) = 0 ; virtual Word __stdcall GetSQLText(char * &sqlText, unsigned &DialectDrvType, BOOL bInnerJoinUseKeyword, dialect_ansi lang) = 0 ; virtual Word __stdcall FetchInputTable(Word index, ITable* &pTable) = 0 ; virtual Word __stdcall FetchProjector(Word index, IProjector* &pProjector) = 0 ; virtual Word __stdcall FetchGroupBy(Word index, IGroupBy* &pGroupBy) = 0 ; virtual Word __stdcall FetchOrderBy(Word index, IOrderBy* &pOrderBy) = 0 ; virtual Word __stdcall FetchJoin(Word index, IJoin* &pJoin) = 0 ; virtual Word __stdcall FetchWhereExpr(IExpr* &Expr) = 0 ; virtual Word __stdcall FetchHavingExpr(IExpr* &Expr) = 0 ; virtual Word __stdcall GetIndexForInputTable(ITable* pObj, Word &index) = 0 ; virtual Word __stdcall GetIndexForJoin(IJoin* pObj, Word &index) = 0 ; virtual Word __stdcall GetIndexForProjector(IProjector* pObj, Word &index) = 0 ; virtual Word __stdcall GetIndexForGroupBy(IGroupBy* pObj, Word &index) = 0 ; virtual Word __stdcall GetIndexForOrderBy(IOrderBy* pObj, Word &index) = 0 ; virtual Word __stdcall AddInputTable(char * Name, char * DbName, char * DrvType, char * Alias, ITable* &pObj, ITable* BefThisObj) = 0 ; virtual Word __stdcall DeleteInputTable(ITable* Table, pDeletedObj &pDelObj) = 0 ; virtual Word __stdcall AddJoin(ITable* TableLeft, ITable* TableRight, JoinType eJoinType, IJoin* &pObj, IJoin* BefThisObj) = 0 ; virtual Word __stdcall DeleteJoin(IJoin* Obj) = 0 ; virtual Word __stdcall AddProjector_FldNum(ITable* Table, Word FldSeqNum, IProjector* &pObj, IProjector* BefThisObj, BOOL bAddGroupBY) = 0 ; virtual Word __stdcall AddProjector_field(IField* Field, IProjector* &pObj, IProjector* BefThisObj, BOOL bAddGroupBY) = 0 ; virtual Word __stdcall AddProjector_text(char * sqlText, IProjector* &pObj, IProjector* BefThisObj) = 0 ; virtual Word __stdcall AddProjector_node(QNodeType qNodeType, IProjector* &pObj, IProjector* BefThisObj, BOOL bAddGroupBy) = 0 ; virtual Word __stdcall DeleteProjector(IProjector* pObj, pDeletedObj &pDelObj) = 0 ; virtual Word __stdcall GenerateDefProjName(IProjector* Proj) = 0 ; virtual Word __stdcall IsField(char * sqlText, IField* &pField) = 0 ; virtual Word __stdcall AddGroupBy_FieldNo(ITable* pTable, Word FldIndex, IGroupBy* &pObj, IGroupBy* pBefThisObj) = 0 ; virtual Word __stdcall AddGroupBy_Field(IField* pField, IGroupBy* &pObj, IGroupBy* pBefThisObj) = 0 ; virtual Word __stdcall DeleteGroupBy(IGroupBy* pObj) = 0 ; virtual Word __stdcall AddGroupBy_automatic(void) = 0 ; virtual Word __stdcall AddOrderBy(IProjector* pProjector, Word iPosition, BOOL bDesc, IOrderBy* &pObj, IOrderBy* pBefThisObj) = 0 ; virtual Word __stdcall DeleteOrderBy(IOrderBy* pObj) = 0 ; virtual Word __stdcall SetTableAlias(ITable* pTable, char * newAlias) = 0 ; virtual Word __stdcall SetProjectorName(IProjector* pProj, char * newName) = 0 ; virtual Word __stdcall MoveProjector(IProjector* pObj, IProjector* pBefThisObj) = 0 ; virtual Word __stdcall MoveTable(ITable* pObj, ITable* pBefThisObj) = 0 ; virtual Word __stdcall MoveGroupBy(IGroupBy* pObj, IGroupBy* pBefThisObj) = 0 ; virtual Word __stdcall MoveOrderBy(IOrderBy* pObj, IOrderBy* pBefThisObj) = 0 ; virtual Word __stdcall MakeComment(char * pComment, BOOL bFront) = 0 ; virtual Word __stdcall ExprTextToObj(IExpr* &pExpr, ExprCat ec, IExpr* rootExpr) = 0 ; virtual Word __stdcall ExprObjToText(IExpr* &pExpr, IExpr* rootExpr) = 0 ; virtual Word __stdcall ProjTextToObj(IProjector* pProj) = 0 ; virtual Word __stdcall ProjObjToText(IProjector* pProj) = 0 ; }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE GUID CLSID_IDSQL32; extern PACKAGE GUID IID_IQStmt; } /* namespace Mxqedcom */ using namespace Mxqedcom; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // MXQEDCOM
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 346 ] ] ]
b8cf50577e9e5a21213843ae2c6b8ba3cdc314fa
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCSrvSvc/stdafx.h
57675db7ecda9118dc27674a7f89bea828b9732c
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
1,347
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include <afx.h> #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxmt.h> #include <afxsock.h> #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <iostream> #include <vector> #include <SolidSBCNetLib.h> #include <SolidSBCTestSDK.h> #include <SolidSBCDatabaseLib.h> #include "defines.h" #include "SolidSBCSrvServiceWnd.h" #include "SolidSBCResultClientHandlerSocket.h" #include "SolidSBCConfigClientSocket.h" #include "SolidSBCResultClientSocket.h" #include "SolidSBCClientConfigInfo.h" #include "SolidSBCClientResultInfo.h" #include "SolidSBCClientList.h"
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 46 ] ] ]
82f32f75547440192005fc9e9f11b5cf4fc68e2c
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/matrix/matrix_qr.h
0433b82b482ab24202b7869b9b1ffaae83c10c81
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
12,098
h
// Copyright (C) 2009 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. // This code was adapted from code from the JAMA part of NIST's TNT library. // See: http://math.nist.gov/tnt/ #ifndef DLIB_MATRIX_QR_DECOMPOSITION_H #define DLIB_MATRIX_QR_DECOMPOSITION_H #include "matrix.h" #include "matrix_utilities.h" #include "matrix_subexp.h" namespace dlib { template < typename matrix_exp_type > class qr_decomposition { public: const static long NR = matrix_exp_type::NR; const static long NC = matrix_exp_type::NC; typedef typename matrix_exp_type::type type; typedef typename matrix_exp_type::mem_manager_type mem_manager_type; typedef typename matrix_exp_type::layout_type layout_type; typedef matrix<type,0,0,mem_manager_type,layout_type> matrix_type; typedef matrix<type,0,1,mem_manager_type,layout_type> column_vector_type; // You have supplied an invalid type of matrix_exp_type. You have // to use this object with matrices that contain float or double type data. COMPILE_TIME_ASSERT((is_same_type<float, type>::value || is_same_type<double, type>::value )); template <typename EXP> qr_decomposition( const matrix_exp<EXP>& A ); bool is_full_rank( ) const; long nr( ) const; long nc( ) const; const matrix_type get_householder ( ) const; const matrix_type get_r ( ) const; const matrix_type get_q ( ) const; template <typename EXP> const matrix_type solve ( const matrix_exp<EXP>& B ) const; private: template <typename EXP> const matrix_type solve_mat ( const matrix_exp<EXP>& B ) const; template <typename EXP> const matrix_type solve_vect ( const matrix_exp<EXP>& B ) const; /** Array for internal storage of decomposition. @serial internal array storage. */ matrix_type QR_; /** Row and column dimensions. @serial column dimension. @serial row dimension. */ long m, n; /** Array for internal storage of diagonal of R. @serial diagonal of R. */ column_vector_type Rdiag; }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // Member functions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> template <typename EXP> qr_decomposition<matrix_exp_type>:: qr_decomposition( const matrix_exp<EXP>& A ) { COMPILE_TIME_ASSERT((is_same_type<type, typename EXP::type>::value)); // make sure requires clause is not broken DLIB_ASSERT(A.nr() >= A.nc() && A.size() > 0, "\tqr_decomposition::qr_decomposition(A)" << "\n\tInvalid inputs were given to this function" << "\n\tA.nr(): " << A.nr() << "\n\tA.nc(): " << A.nc() << "\n\tA.size(): " << A.size() << "\n\tthis: " << this ); QR_ = A; m = A.nr(); n = A.nc(); Rdiag.set_size(n); long i=0, j=0, k=0; // Main loop. for (k = 0; k < n; k++) { // Compute 2-norm of k-th column without under/overflow. type nrm = 0; for (i = k; i < m; i++) { nrm = hypot(nrm,QR_(i,k)); } if (nrm != 0.0) { // Form k-th Householder vector. if (QR_(k,k) < 0) { nrm = -nrm; } for (i = k; i < m; i++) { QR_(i,k) /= nrm; } QR_(k,k) += 1.0; // Apply transformation to remaining columns. for (j = k+1; j < n; j++) { type s = 0.0; for (i = k; i < m; i++) { s += QR_(i,k)*QR_(i,j); } s = -s/QR_(k,k); for (i = k; i < m; i++) { QR_(i,j) += s*QR_(i,k); } } } Rdiag(k) = -nrm; } } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> long qr_decomposition<matrix_exp_type>:: nr ( ) const { return m; } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> long qr_decomposition<matrix_exp_type>:: nc ( ) const { return n; } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> bool qr_decomposition<matrix_exp_type>:: is_full_rank( ) const { type eps = max(abs(Rdiag)); if (eps != 0) eps *= std::sqrt(std::numeric_limits<type>::epsilon())/100; else eps = 1; // there is no max so just use 1 // check if any of the elements of Rdiag are effectively 0 return min(abs(Rdiag)) > eps; } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: get_householder ( ) const { return lowerm(QR_); } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: get_r( ) const { matrix_type R(n,n); for (long i = 0; i < n; i++) { for (long j = 0; j < n; j++) { if (i < j) { R(i,j) = QR_(i,j); } else if (i == j) { R(i,j) = Rdiag(i); } else { R(i,j) = 0.0; } } } return R; } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: get_q( ) const { long i=0, j=0, k=0; matrix_type Q(m,n); for (k = n-1; k >= 0; k--) { for (i = 0; i < m; i++) { Q(i,k) = 0.0; } Q(k,k) = 1.0; for (j = k; j < n; j++) { if (QR_(k,k) != 0) { type s = 0.0; for (i = k; i < m; i++) { s += QR_(i,k)*Q(i,j); } s = -s/QR_(k,k); for (i = k; i < m; i++) { Q(i,j) += s*QR_(i,k); } } } } return Q; } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> template <typename EXP> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: solve( const matrix_exp<EXP>& B ) const { COMPILE_TIME_ASSERT((is_same_type<type, typename EXP::type>::value)); // make sure requires clause is not broken DLIB_ASSERT(B.nr() == nr(), "\tconst matrix_type qr_decomposition::solve(B)" << "\n\tInvalid inputs were given to this function" << "\n\tB.nr(): " << B.nr() << "\n\tnr(): " << nr() << "\n\tthis: " << this ); // just call the right version of the solve function if (B.nc() == 1) return solve_vect(B); else return solve_mat(B); } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // Private member functions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> template <typename EXP> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: solve_vect( const matrix_exp<EXP>& B ) const { column_vector_type x(B); // Compute Y = transpose(Q)*B for (long k = 0; k < n; k++) { type s = 0.0; for (long i = k; i < m; i++) { s += QR_(i,k)*x(i); } s = -s/QR_(k,k); for (long i = k; i < m; i++) { x(i) += s*QR_(i,k); } } // Solve R*X = Y; for (long k = n-1; k >= 0; k--) { x(k) /= Rdiag(k); for (long i = 0; i < k; i++) { x(i) -= x(k)*QR_(i,k); } } /* return n x 1 portion of x */ return colm(x,0,n); } // ---------------------------------------------------------------------------------------- template <typename matrix_exp_type> template <typename EXP> const typename qr_decomposition<matrix_exp_type>::matrix_type qr_decomposition<matrix_exp_type>:: solve_mat( const matrix_exp<EXP>& B ) const { const long nx = B.nc(); matrix_type X(B); long i=0, j=0, k=0; // Compute Y = transpose(Q)*B for (k = 0; k < n; k++) { for (j = 0; j < nx; j++) { type s = 0.0; for (i = k; i < m; i++) { s += QR_(i,k)*X(i,j); } s = -s/QR_(k,k); for (i = k; i < m; i++) { X(i,j) += s*QR_(i,k); } } } // Solve R*X = Y; for (k = n-1; k >= 0; k--) { for (j = 0; j < nx; j++) { X(k,j) /= Rdiag(k); } for (i = 0; i < k; i++) { for (j = 0; j < nx; j++) { X(i,j) -= X(k,j)*QR_(i,k); } } } /* return n x nx portion of X */ return subm(X,0,0,n,nx); } // ---------------------------------------------------------------------------------------- } #endif // DLIB_MATRIX_QR_DECOMPOSITION_H
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 416 ] ] ]
88fd3d8cd3fc26ef560ce6b2b0d8ac5dc54da55b
68127d36b179fd5548a1e593e2c20791db6b48e3
/programacaoC/arquivos.cpp
a6887df02a66b3b0031bf77a67b66d12a579671c
[]
no_license
renatomb/engComp
fa50b962dbdf4f9387fd02a28b3dc130b683ed02
b533c876b50427d44cfdb92c507a6e74b1b7fa79
refs/heads/master
2020-04-11T06:22:05.209022
2006-04-26T13:40:08
2018-12-13T04:25:08
161,578,821
1
0
null
null
null
null
ISO-8859-1
C++
false
false
1,160
cpp
/* Operações com Arquivos: * Objetos STREAM fstream{iostream(istream,ostream)} *Gravando linha a linha em arquivos disco: Exemplo:*/ #include <fstream.h>//1 void main() { ostream fout ("Teste.txt"); fout<<"universidade potiguar\n"; fout<<" curso de engenharia de computação \n"; fout<<" programação cinentífica \n"; } // lendo arquivos #include<fstream.h> void main() { const int max=80; char buff[max]; ifstream fin("teste.txt"); while(fin) { fin.getline(buff,max); cout<<buff<<'\n'; } } //2 #include<fstream> void main() { const int max=80; char buff[max]; ifstream fin("teste.txt"); while(fin.getline(buff,max))//enquanto não eof cout<<buff<<'\n'; } // Lendo e gravando arquivos em caracter por vez no arquivo #include<fstream.h> void main() { ofstream fout("teste1.txt"); char ch; while (cin.get(ch)) fout.put(ch); } // ================================================================================= #include<fstream.h> void main() { ifstream fin("teste1.txt"); char ch; while (fin.get(ch)) cout.put(ch); }
[ [ [ 1, 61 ] ] ]
1909f94374cc173fe6cc6d85c3de8c65b5be02ab
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CItemData.h
68f54254b34ed1f7182cff6cd7af54737dd523de
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
242
h
#ifndef _CITEMDATA_H #define _CITEMDATA_H 1 #include "window.h" #include "CItemSheet.h" class CItemData { public: LPARAM m_lParam; CItemSheet * m_pSheet; CItemData(); virtual ~CItemData(); }; #endif // _CITEMDATA_H
[ [ [ 1, 17 ] ] ]