text
stringlengths
8
6.88M
#pragma once #include "entity.h" #include "..\\input\input_system.h" #include "..\\renderer\texture.h" #include "..\\audio\audio_system.h" #include "..\\resource\resource_manager.h" class Scene; class EntityEventDispatcher : public EventDispatcher<Event<Entity>> { public: EntityEventDispatcher(Engine* engine) : EventDispatcher<Event<Entity>>(engine) {} }; class Engine { public: Engine() {} ~Engine() {} bool Startup(); void Update(); void Shutdown(); bool LoadScene(const char* scene_name); void DestroyScene(); Scene* GetScene() { return scene_; } bool Quit() const { return quit_; } ResourceManager<Resource>* GetResourceManager() { return resource_mgr_; } template <typename T> T* GetSystem() { T* system = nullptr; for (System* _system : systems_) { system = dynamic_cast<T*>(_system); if (system != nullptr) break; } return system; } private: bool quit_ = false; std::vector<System*> systems_; Scene* scene_ = nullptr; ResourceManager<Resource>* resource_mgr_ = nullptr; };
#include "task_widget.h" #include "task_box.h" #include "time_dialog.h" #include <QPushButton> #include <QVBoxLayout> #include <QSpinBox> #include <QCheckBox> #include <QLabel> TaskWidget::TaskWidget( void ) { workTimeBox = new QSpinBox; restTimeBox = new QSpinBox; startButton = new QPushButton( tr("start") ); connect( startButton, SIGNAL(clicked()), this, SLOT(doStart()) ); connect( workTimeBox, SIGNAL(valueChanged(int)), this, SLOT(workTime(int)) ); connect( restTimeBox, SIGNAL(valueChanged(int)), this, SLOT(restTime(int)) ); showFinish = new QCheckBox( tr("finish?") ); midLayout = new QVBoxLayout; midLayout->addStretch( 0 ); midLayout->addWidget( workTimeBox ); midLayout->addWidget( restTimeBox ); midLayout->addWidget( startButton ); midLayout->addStretch( 0 ); leftLayout = new QVBoxLayout; QHBoxLayout* taskTitle = new QHBoxLayout; taskTitle->addWidget( showFinish ); taskTitle->addWidget( new QLabel( tr("using") ) ); taskTitle->addWidget( new QLabel( tr("needing") ) ); taskTitle->addWidget( new QLabel( tr("tag") ) ); taskTitle->addWidget( new QLabel( tr("name") ) ); taskTitle->addWidget( new QLabel( tr("choose?") ) ); connect( showFinish, SIGNAL(stateChanged(int)), this, SLOT(hideTask(int)) ); showFinish->setCheckState( Qt::Unchecked ); leftLayout->addStretch( 1 ); leftLayout->addLayout( taskTitle ); mainLayout = new QHBoxLayout; mainLayout->addLayout( leftLayout ); mainLayout->addLayout( midLayout ); setLayout( mainLayout ); } TaskWidget::~TaskWidget( void ) { delete midLayout; delete leftLayout; delete mainLayout; delete startButton; delete restTimeBox; delete workTimeBox; for( std::vector<TaskBox*>::iterator i = taskGroup.begin(); i != taskGroup.end(); ++i ) { //delete *i; } taskGroup.clear(); } void TaskWidget::load( void ) { workTimeBox->setValue( 25 ); restTimeBox->setValue( 5 ); } void TaskWidget::finishChildTask( int id, bool status ) { emit finishTask( id, status ); } void TaskWidget::chooseChildTask( int id, bool status ) { emit chooseTask( id, status ); } void TaskWidget::updateTask( QTask qtask ) { size_t ptr = 0; size_t taskNumber = taskGroup.size(); for( ; ptr < taskNumber; ++ptr ) { if( taskGroup[ptr]->getID() == qtask.id ) { break; } } if( ptr == taskNumber ) { TaskBox* tmp = new TaskBox( qtask, showFinish->checkState(), this ); taskGroup.push_back( tmp ); leftLayout->addLayout( tmp ); } else { taskGroup[ptr]->updateTask( qtask ); taskGroup[ptr]->updateDisplay(); } } void TaskWidget::updateTask( const std::vector<QTask> &qtasks ) { for( std::vector<QTask>::const_iterator i=qtasks.begin(); i != qtasks.end(); ++i ) { this->updateTask( *i ); } } void TaskWidget::doStart( void ) { emit start(); } void TaskWidget::hideTask( int state ) { bool isHidingTask = state==Qt::Checked?false:true; for( std::vector<TaskBox*>::iterator i=taskGroup.begin(); i != taskGroup.end(); ++i ) { (*i)->setHidingState( isHidingTask ); } } void TaskWidget::workTime( int minutes ) { emit workTimeChanged( minutes ); } void TaskWidget::restTime( int minutes ) { emit restTimeChanged( minutes ); }
#include <cstdio> #include <cmath> #include <iostream> using namespace std; const int maxn = 100002; int arr[maxn]; long long quick_mod(long long a, long long b) { long long ans = 1; while(b > 1) { if(b % 2 != 0) { ans = ans * a % 29; b--; } else { a = (a * a) % 29; b /= 2; } } return a * ans % 29; } int main() { int n; while(scanf("%d", &n) != EOF && n) { int cnt1 = quick_mod(2, 2 * n + 1); int cnt2 = quick_mod(3, n + 1); int cnt3 = quick_mod(22, n + 1); cout << (cnt1 - 1)*(cnt2 - 1) * 15 * (cnt3 - 1) * 18 % 29 << endl; } return 0; }
//---------------------------------------------------------------- // MultifieldSort.cpp // // Routines for performing multi-field sorts on idList's // // Copyright 2002-2005 Raven Software //---------------------------------------------------------------- #ifndef __MULTIFIELD_SORT_H__ #define __MULTIFIELD_SORT_H__ template< class type > class rvMultifieldSort { public: void Clear( void ); void AddCompareFunction( typename idList<type>::cmp_t* fn ); void AddFilterFunction( typename idList<type>::filter_t* fn ); void Sort( idList<type>& list ); private: void QSort_Iterative( idList<type>& list, int low, int n ); int Median3( type* list, int a, int b, int c ); int Compare( const type* lhs, const type* rhs ); // sortingFields - pointers to sorting functions, in order to be sorted idList<typename idList<type>::cmp_t*> sortingFields; // filterFields - pointers to filter functions, in order to be filtered idList<typename idList<type>::filter_t*> filterFields; }; template< class type > void rvMultifieldSort< type >::Clear( void ) { sortingFields.Clear(); filterFields.Clear(); } template< class type > int rvMultifieldSort< type >::Compare( const type* lhs, const type* rhs ) { for( int i = 0; i < sortingFields.Num(); i++ ) { int result = (*sortingFields[ i ])( lhs, rhs ); if( result != 0 ) { return result; } } // items are equal on all fields return 0; } template< class type > ID_INLINE void rvMultifieldSort< type >::AddCompareFunction( typename idList<type>::cmp_t* fn ) { sortingFields.Append( fn ); } template< class type > ID_INLINE void rvMultifieldSort< type >::AddFilterFunction( typename idList<type>::filter_t* fn ) { filterFields.Append( fn ); } template< class type > void rvMultifieldSort< type >::Sort( idList<type>& list ) { int i, j; if ( filterFields.Num() ) { for ( i = 0; i < list.Num(); i++ ) { for ( j = 0; j < filterFields.Num(); j++ ) { if( (*filterFields[ j ])( (const type*)(&list[ i ]) ) ) { list.RemoveIndex( i ); i--; break; } } } } QSort_Iterative( list, 0, list.Num() ); } template< class type > ID_INLINE int rvMultifieldSort< type >::Median3( type* list, int a, int b, int c ) { return Compare( &list[ a ], &list[ b ] ) < 0 ? ( Compare( &list[ b ], &list[ c ] ) < 0 ? b : ( Compare( &list[ a ], &list[ c ] ) < 0 ? c : a ) ) : ( Compare( &list[ b ], &list[ c ] ) > 0 ? b : ( Compare( &list[ a ], &list[ c ] ) < 0 ? a : c )); } template< class type > void rvMultifieldSort< type >::QSort_Iterative( idList<type>& list, int low, int n ) { int swap_cnt, pivot, lowBound, highBound; loop: swap_cnt = 0; // insertion sort on small arrays if( n < 7 ) { for( int i = low + 1; i < low + n; i++ ) { for( int j = i; j > low && Compare( &list[ j - 1 ], &list[ j ] ) > 0; j-- ) { type t = list[ j - 1 ]; list[ j - 1 ] = list[ j ]; list[ j ] = t; } } return; } // pivot selection pivot = n / 2 + low; if( n > 7 ) { lowBound = low; highBound = low + n - 1; if (n > 40) { int d = (n / 8); lowBound = Median3( list.Ptr(), lowBound, lowBound + d, lowBound + 2 * d ); pivot = Median3( list.Ptr(), pivot - d, pivot, pivot + d ); highBound = Median3( list.Ptr(), highBound - 2 * d, highBound - d, highBound ); } pivot = Median3( list.Ptr(), lowBound, pivot, highBound ); } type t = list[ low ]; list[ low ] = list[ pivot ]; list[ pivot ] = t; // qsort int leftA, leftB, rightC, rightD, r; leftA = leftB = low + 1; rightC = rightD = low + n - 1; for (;;) { while ( leftB <= rightC && (r = Compare( &list[ leftB ], &list[ low ] )) <= 0) { if (r == 0) { swap_cnt = 1; type t = list[ leftA ]; list[ leftA ] = list[ leftB ]; list[ leftB ] = t; leftA++; } leftB++; } while (leftB <= rightC && (r = Compare( &list[ rightC ], &list[ low ] )) >= 0) { if (r == 0) { swap_cnt = 1; type t = list[ rightC ]; list[ rightC ] = list[ rightD ]; list[ rightD ] = t; rightD--; } rightC--; } if( leftB > rightC ) { break; } type t = list[ leftB ]; list[ leftB ] = list[ rightC ]; list[ rightC ] = t; swap_cnt = 1; leftB++; rightC--; } if (swap_cnt == 0) { /* Switch to insertion sort */ for( int i = low + 1; i < low + n; i++ ) { for( int j = i; j > low && Compare( &list[ j - 1 ], &list[ j ] ) > 0; j-- ) { type t = list[ j ]; list[ j ] = list[ j - 1 ]; list[ j - 1 ] = t; } } return; } highBound = low + n; r = Min( leftA - low, leftB - leftA ); for( int i = 0; i < r; i++ ) { type t = list[ low + i ]; list[ low + i ] = list[ leftB - r + i ]; list[ leftB - r + i ] = t; } r = Min( rightD - rightC, highBound - rightD - 1 ); for( int i = 0; i < r; i++ ) { type t = list[ leftB + i ]; list[ leftB + i ] = list[ highBound - r + i ]; list[ highBound - r + i ] = t; } if ( (r = leftB - leftA) > 1 ) { QSort_Iterative( list, low, r ); } if ((r = rightD - rightC) > 1) { /* Iterate rather than recurse to save stack space */ low = highBound - r; n = r; goto loop; } /* qsort(pn - r, r / es, es, cmp);*/ } ///////// #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef COCOAMACOPPLATFORMEVENT_H #define COCOAMACOPPLATFORMEVENT_H #ifdef NS4P_COMPONENT_PLUGINS #include "platforms/mac/pi/MacOpPlatformEvent.h" #include "modules/ns4plugins/src/plug-inc/npapi.h" class CocoaMacOpPlatformEvent : public MacOpPlatformEvent { public: OpAutoVector<NPCocoaEvent> m_events; public: CocoaMacOpPlatformEvent() {} virtual ~CocoaMacOpPlatformEvent() {} // Implement MacOpPlatformEvent virtual int GetEventDataCount(); virtual void* GetEventData(uint index) const; // Implement OpPlatformEvent virtual void* GetEventData() const; }; #endif // NS4P_COMPONENT_PLUGINS #endif //!COCOAMACOPPLATFORMEVENT_H
/* * File: tcpsocket.h * Author: dangnq * * Created on January 31, 2015, 9:18 PM */ #ifndef TCPSOCKET_H #define TCPSOCKET_H #include <string.h> #include <cstdlib> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <arpa/inet.h> class CTcpSocket { public: CTcpSocket(int hSocket); CTcpSocket(); virtual ~CTcpSocket(); bool write(char* pData, int nSize); bool write(const char* pData, int nSize); int read(char* pData, int nSize); int read(unsigned char* pData, int nSize); int bytesAvailable() const; bool waitForReadyRead(int nMSecond = 3000); bool waitForBytesWritten(int nMSecond = 3000); void disconnect(); bool connectToServer(char* szServer, unsigned short nPort); bool isConnected(); private: int m_hSocket; bool m_bIsConnected; } ; #endif /* TCPSOCKET_H */
#ifndef GETLINE_H #define GETLINE_H #include "opencv2/imgcodecs/imgcodecs.hpp" #include "opencv2/opencv.hpp" #include "opencv2/core/core.hpp" class getline { public: getline(); void getl(); float getD(float,float,float,float,float); float jisuan(float,float,float,float); }; #endif // GETLINE_H
#include "sudoku.h" // ---------------------------------------------------------------------- // Klasse Sudoku // Ein-/Ausgabeoperatoren ostream& operator<< (ostream& out, const Sudoku& S) { for (int r=1; r<=9; ++r) { for (int c=1; c<=9; ++c) { const int z= S(r,c); if (z==0) out << ". "; else out << z << ' '; } out << endl; } return out; } istream& operator>> (istream& in, Sudoku& S) { for (int r=1; r<=9; ++r) for (int c=1; c<=9; ++c) in >> S(r,c); return in; } // Sudoku-Methoden void Sudoku::check( int& idx) const { if (idx < 1) { cout << "Index " << idx << " ist ungueltig." << endl; idx= 1; } if (idx > 9) { cout << "Index " << idx << " ist ungueltig." << endl; idx= 9; } } int Sudoku::getNumEmpty() const { int numEmpty= 0; for (int i=0; i<81; ++i) if (Data[i]==0) ++numEmpty; return numEmpty; } bool Sudoku::validRow( int r) const { int haeufigkeit[10]= {}; // mit Nullen initialisiert for (int c=1; c<=9; ++c) { int z= (*this)(r,c); if (z != 0) { haeufigkeit[z]++; if (haeufigkeit[z] > 1) // z kommt mehr als einmal vor return false; } } return true; } bool Sudoku::validCol( int c) const { int haeufigkeit[10]= {}; // mit Nullen initialisiert for (int r=1; r<=9; ++r) { int z= (*this)(r,c); if (z != 0) { haeufigkeit[z]++; if (haeufigkeit[z] > 1) return false; } } return true; } bool Sudoku::validSqr( int a, int b) const { int haeufigkeit[10]= {}; // mit Nullen initialisiert // Eintrag oben links ist (r,c) const int r= 3*(a-1)+1, c= 3*(b-1)+1; for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) { int z= (*this)(r+i,c+j); if (z != 0) { haeufigkeit[z]++; if (haeufigkeit[z] > 1) return false; } } } return true; } bool Sudoku::valid() const { bool val= true; for (int i=1; i<=9; ++i) { val= val && validRow(i) && validCol(i); } for (int i=1; i<=3; ++i) for (int j=1; j<=3; ++j) val= val && validSqr( i, j); return val; } // ---------------------------------------------------------------------- // Klasse possibleDigits fuer die Hilfszahlen ostream& operator<<( ostream& out, const possibleDigits& a) { /*hier fehlt was*/ } possibleDigits operator&&( const possibleDigits& a, const possibleDigits& b) { /*hier fehlt was*/ } // possibleDigits-Methoden int possibleDigits::numPossible() const { /*hier fehlt was*/ } // ---------------------------------------------------------------------- // Klasse SudokuSolver SudokuSolver::SudokuSolver( Sudoku& S) : /*hier fehlt was*/ Sudo(S) { /*hier fehlt was*/ } void SudokuSolver::setDigit( int r, int c, int digit) { /*hier fehlt was*/ } void SudokuSolver::unsetDigit( int r, int c) { /*hier fehlt was*/ } possibleDigits SudokuSolver::getPossible( int r, int c) const { /*hier fehlt was*/ } void SudokuSolver::getNextCell( int& r_min, int& c_min) const { /*hier fehlt was*/ } bool SudokuSolver::solve( int numEmpty) { /*hier fehlt was*/ }
#include "save.h" #include "Timer.h" #include "Entity.h" #include "Terrain.h" #include "graphics.h" #include "camera.h" #include "console.h" #include "unit.h" extern Graphics *renderer; extern Camera * camera; extern Terrain *terrain; extern Console *console; extern Timer *timer; extern EntityContainer *ents; using std::string; void SaveWorldState(const char *filename) { MapHeader head; MapEntity ent; FILE * fout = fopen(filename,"w"); strcpy(head.magic,"ASGE07"); head.size_x = terrain->width; head.size_y = terrain->height; strcpy(head.terrainName,terrain->terrainName.c_str()); head.entityCount = (int)ents->entities.size(); fwrite(&head,sizeof(MapHeader),1,fout); for (int i=0;i<head.entityCount;i++) { if (ents->entities[i] && ents->entities[i]->alive && ents->entities[i]->family > 0) { strcpy(ent.entityName, ((Unit*)ents->entities[i])->classname.c_str()); ent.x = ents->entities[i]->position.x; ent.y = ents->entities[i]->position.z; fwrite(&ent,sizeof(ent),1,fout); } } fclose(fout); } void LoadWorldState(const char *filename) { MapHeader head; console->Printf("Loading world: %s",filename); FILE *fin = fopen(filename,"r"); memset(&head,0,sizeof(MapHeader)); if (!fin) { console->Printf("*** Critical: Error opening world file ***"); return; } fread(&head,sizeof(MapHeader),1,fin); if (strncmp(head.magic,"ASGE07",6)!=0) { // error console->Printf("world magic number incorrect!"); return; } char textureName[255]; sprintf(textureName,"data/topographical/%s.JPG",head.terrainName); terrain = new Terrain(head.terrainName, renderer->LoadTexture(textureName),renderer->LoadTexture("data/models/water_surface.JPG"), camera); ents->AddEntity((Entity*)terrain); MapEntity e; for (int i=0;i<head.entityCount && !feof(fin);i++) { fread(&e,sizeof(MapEntity),1,fin); Unit *unit = new Unit(e.entityName); unit->position = Vector(e.x,0,e.y); unit->completed = 100; ents->AddEntity(unit); } fclose(fin); }
#include "stdafx.h" #include "EthernetFrame.h" EthernetFrame::EthernetFrame(void) { memset(m_DestAddress, 0, 6); memset(m_SourceAddress, 0, 6); m_EtherType = 0; m_MACDATA = NULL; } EthernetFrame::EthernetFrame(BYTE *DestAddress,BYTE *SourceAddress,WORD EtherType) { memcpy(m_DestAddress, DestAddress, 6); memcpy(m_SourceAddress, SourceAddress, 6); m_EtherType = EtherType; m_MACDATA = NULL; } void EthernetFrame::SetDestAddress(BYTE *DestAddress) { memcpy(m_DestAddress, DestAddress, 6); } void EthernetFrame::SetSourceAddress(BYTE *SourceAddress) { memcpy(m_SourceAddress, SourceAddress, 6); } void EthernetFrame::SetEtherType(WORD EtherType) { m_EtherType = EtherType; } BOOL EthernetFrame::SetMACDATA(PDU * DATA) { m_MACDATA = DATA; return TRUE; } const PDU *EthernetFrame::GetMACDATA() const { return m_MACDATA; } BOOL EthernetFrame::Write(BYTE *link) { memcpy(link, m_DestAddress, 6); memcpy(link+6, m_SourceAddress, 6); memcpy(link+12, &m_EtherType, 2); m_MACDATA->Write(link+14); return TRUE; } BOOL EthernetFrame::Read(BYTE *link) { memcpy(m_DestAddress, link, 6); memcpy(m_SourceAddress, link+6, 6); memcpy(&m_EtherType, link+12, 2); m_MACDATA->Read(link+14); return TRUE; }
#pragma once #include "cocos2d.h" USING_NS_CC; class Enemy : public Sprite { private: DWORD m_UID; public: Enemy(); ~Enemy(); static Enemy* SpriteWithFile(const char* pszFileName); virtual bool init(); };
#include <iostream> #include <algorithm> using namespace std; int main() { int n, a[200001], ans = 0; cin >> n; for(int i = 0; i < n; i++) cin >> a[i]; sort(a, a + n); int k = 1, idx = 0; while(idx < n) { if(a[idx] >= k) { ans++; k++; } idx++; continue; } cout << ans<< endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SVG_TEXT_ELEMENT_STATE_CONTEXT #define SVG_TEXT_ELEMENT_STATE_CONTEXT #ifdef SVG_SUPPORT #include "modules/unicode/unicode_bidiutils.h" #include "modules/util/simset.h" #include "modules/svg/src/SVGElementStateContext.h" #include "modules/svg/src/SVGGlyphCache.h" class BidiCalculation; #ifndef NEEDS_RISC_ALIGNMENT ///< Packing causes memory corruption. # pragma pack(1) #endif struct SVGTextFragment { union { struct { unsigned int wordinfo : 16; ///< The index to the WordInfo for this fragment unsigned int next : 16; ///< The index of the next fragment in left-to-right order } idx; unsigned int idx_init; }; union { struct { unsigned char bidi : 4; ///< The bidi-direction unsigned char level : 4; ///< The bidi-level } packed; unsigned char packed_init; }; }; #ifndef NEEDS_RISC_ALIGNMENT # pragma pack() #endif // Potentially make this (explicitely) single linked class SVGTextCache : public ListElement<SVGTextCache> { private: HTML_Element* text_content_element; WordInfo* word_info_array; SVGTextFragment* text_fragment_list; union { struct { /** Number of words (and size of word_info_array) */ unsigned word_count:16; /** Word info needs to be recalculated. */ unsigned remove_word_info:1; /** One or more fragments are RTL */ unsigned has_rtl_frag:1; /** Space handling (preserve) */ unsigned preserve_spaces:1; /** Keeps a leading whitespace */ unsigned keep_leading_ws:1; /** Keeps a trailing whitespace */ unsigned keep_trailing_ws:1; } packed; /* 21 bits */ unsigned int packed_init; }; public: SVGTextCache() : text_content_element(NULL), word_info_array(NULL), text_fragment_list(NULL), packed_init(0) {} ~SVGTextCache() { Out(); DeleteWordInfoArray(); } /** Sets the HTML_Element for which this text cache corresponds */ void SetTextContentElement(HTML_Element* text_cont_elm) { text_content_element = text_cont_elm; } /** Set whether spaces should be preserved */ void SetPreserveSpaces(BOOL preserve_spaces) { packed.preserve_spaces = preserve_spaces ? 1 : 0; } /** Set whether a leading whitespace should be preserved */ void SetKeepLeadingWS(BOOL keep_leading) { packed.keep_leading_ws = keep_leading ? 1 : 0; } /** Set whether a trailing whitespace should be preserved */ void SetKeepTrailingWS(BOOL keep_trailing) { packed.keep_trailing_ws = keep_trailing ? 1 : 0; } /** Indicate that this text cache has RTL fragments */ void SetHasRTLFragments(BOOL has_rtl) { packed.has_rtl_frag = has_rtl ? 1 : 0; } /** Allocate word_info_array, and update word_count. Precondition: empty array. */ BOOL AllocateWordInfoArray(unsigned int new_word_count); /** Delete word_info_array, and update word_count. */ void DeleteWordInfoArray(); /** Mark this text cache as valid (having valid representation) */ void SetIsValid() { packed.remove_word_info = 0; } BOOL IsValid() const { return packed.remove_word_info == 0 && word_info_array; } /** Remove cached info */ BOOL RemoveCachedInfo(); void AdoptTextFragmentList(SVGTextFragment* tflist) { if (text_fragment_list) OP_DELETEA(text_fragment_list); text_fragment_list = tflist; } /** Returns if any fragment is RTL */ BOOL HasRTLFragments() const { return packed.has_rtl_frag; } /** Returns number of words in box. */ unsigned int GetWordCount() const { return packed.word_count; } /** Returns word array. */ WordInfo* GetWords() const { return word_info_array; } /** Returns the textfragment list, only used for complex text */ SVGTextFragment* GetTextFragments() { return text_fragment_list; } /** Returns the HTML_Element for which this text cache corresponds */ HTML_Element* GetTextContentElement() const { return text_content_element; } /** Returns if spaces should be preserved */ BOOL GetPreserveSpaces() const { return packed.preserve_spaces; } /** Returns if there should be leading whitespace */ BOOL GetKeepLeadingWS() const { return packed.keep_leading_ws; } /** Returns if there should be trailing whitespace */ BOOL GetKeepTrailingWS() const { return packed.keep_trailing_ws; } }; /** 'Virtual' context for text nodes */ class SVGTextNode : public SVGElementContext { private: SVGTextCache m_textcache; public: SVGTextNode(HTML_Element* element) : SVGElementContext(element) {} virtual void AddInvalidState(SVGElementInvalidState state); virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual SVGTextCache* GetTextCache() { return &m_textcache; } }; class SVGTBreakElement : public SVGElementContext { public: SVGTBreakElement(HTML_Element* element) : SVGElementContext(element) {} virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info); }; /** Base class for _any_ text element that can have children */ class SVGTextContainer : public SVGContainer { public: SVGTextContainer(HTML_Element* element) : SVGContainer(element) {} virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual BOOL EvaluateChild(HTML_Element* child); SVGNumber GetTextExtent() { return m_text_extent; } void SetTextExtent(SVGNumber text_extent) { m_text_extent = text_extent; } void SetGlyphScale(SVGNumber new_glyph_scale) { m_glyph_scale = new_glyph_scale; } SVGNumber GetGlyphScale() { return m_glyph_scale; } void SetExtraSpacing(SVGNumber new_extra_spacing) { m_extra_spacing = new_extra_spacing; } SVGNumber GetExtraSpacing() { return m_extra_spacing; } void ResetCache() { m_text_extent = 0; m_extra_spacing = 0; m_glyph_scale = 1; } private: SVGNumber m_text_extent; SVGNumber m_glyph_scale; SVGNumber m_extra_spacing; }; class SVGAltGlyphElement : public SVGTextContainer { public: SVGAltGlyphElement(HTML_Element* element) : SVGTextContainer(element) {} virtual BOOL EvaluateChild(HTML_Element* child); OpVector<GlyphInfo>& GetGlyphVector() { return m_glyphs; } private: OpAutoVector<GlyphInfo> m_glyphs; }; class SVGTRefElement : public SVGTextContainer { private: SVGTextCache m_textcache; public: SVGTRefElement(HTML_Element* element) : SVGTextContainer(element) {} virtual void AddInvalidState(SVGElementInvalidState state); virtual BOOL EvaluateChild(HTML_Element* child) { return FALSE; } virtual SVGTextCache* GetTextCache() { return &m_textcache; } }; /** Base class for elements with a 'transparent' content model - <a> * and <switch>. * Inherits from SVGTextContainer because both these elements are * allowed in text subtrees, and thus need to be able to handle * textnodes. */ class SVGTransparentContainer : public SVGTextContainer { public: SVGTransparentContainer(HTML_Element* element) : SVGTextContainer(element) {} virtual BOOL EvaluateChild(HTML_Element* child); }; class SVGAElement : public SVGTransparentContainer { public: SVGAElement(HTML_Element* element) : SVGTransparentContainer(element) {} virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); }; class SVGTextGroupElement : public SVGTransparentContainer { public: SVGTextGroupElement(HTML_Element* element) : SVGTransparentContainer(element) {} virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info) { return OpStatus::OK; } virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); }; class SVGSwitchElement : public SVGTransparentContainer { public: SVGSwitchElement(HTML_Element* element) : SVGTransparentContainer(element) {} virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS HandleContent(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual void AddInvalidState(SVGElementInvalidState state); virtual BOOL EvaluateChild(HTML_Element* child); virtual void AppendChild(HTML_Element* child, List<SVGElementContext>* childlist); }; class SVGEditable; /** Common base for <text> and <textArea> - currently only to carry * state for 'editable', so maybe this entire class should be * ifdeffed? */ class SVGTextRootContainer : public SVGTextContainer { public: SVGTextRootContainer(HTML_Element* element) : SVGTextContainer(element) #ifdef SVG_SUPPORT_EDITABLE , m_edit_context(NULL) #endif // SVG_SUPPORT_EDITABLE #ifdef SUPPORT_TEXT_DIRECTION , m_bidi_calculation(NULL) #endif // SUPPORT_TEXT_DIRECTION {} #if defined(SVG_SUPPORT_EDITABLE) || defined(SUPPORT_TEXT_DIRECTION) virtual ~SVGTextRootContainer(); #endif // SVG_SUPPORT_EDITABLE || SUPPORT_TEXT_DIRECTION #ifdef SVG_SUPPORT_EDITABLE SVGEditable* GetEditable(BOOL construct = TRUE); BOOL IsEditing(); BOOL IsCaretVisible(); #endif // SVG_SUPPORT_EDITABLE #ifdef SUPPORT_TEXT_DIRECTION # ifdef _DEBUG void PrintDebugInfo(); # endif // _DEBUG void ResetBidi(); /** Initialize bidi calculation. */ BOOL InitBidiCalculation(const HTMLayoutProperties* props); /** Compute bidi segments for this line. */ OP_STATUS ResolveBidiSegments(WordInfo* wordinfo_array, int wordinfo_array_len, SVGTextFragment*& tflist); /** Push new inline bidi properties onto stack. * * @return FALSE om OOM */ BOOL PushBidiProperties(const HTMLayoutProperties* props); /** Pop inline bidi properties from stack. * * @return FALSE on OOM */ BOOL PopBidiProperties(); /** Get bidi segments */ const Head& GetBidiSegments() const { return m_bidi_segments; } // ED: consider protecting this BidiCalculation* GetBidiCalculation() { return m_bidi_calculation; } #endif virtual SVGTextRootContainer* GetAsTextRootContainer() { return this; } private: #ifdef SVG_SUPPORT_EDITABLE SVGEditable* m_edit_context; #endif // SVG_SUPPORT_EDITABLE #ifdef SUPPORT_TEXT_DIRECTION Head m_bidi_segments; BidiCalculation* m_bidi_calculation; #endif // SUPPORT_TEXT_DIRECTION }; #include "modules/svg/src/SVGTextLayout.h" // For SVGLineInfo and SVGTextChunk /** */ class SVGTextElement : public SVGTextRootContainer { public: SVGTextElement(HTML_Element* element) : SVGTextRootContainer(element) {} virtual ~SVGTextElement() { m_chunk_list.DeleteAll(); } virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual BOOL EvaluateChild(HTML_Element* child); OpVector<SVGTextChunk>& GetChunkList() { return m_chunk_list; } private: OpVector<SVGTextChunk> m_chunk_list; }; /** */ class SVGTextAreaElement : public SVGTextRootContainer { public: SVGTextAreaElement(HTML_Element* element) : SVGTextRootContainer(element) {} virtual ~SVGTextAreaElement() { ClearLineInfo(); } virtual OP_STATUS Enter(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual OP_STATUS Leave(SVGTraversalObject* traversal_object, SVGElementInfo& info); virtual BOOL EvaluateChild(HTML_Element* child); void ClearLineInfo() { m_lineinfo.DeleteAll(); } OpVector<SVGLineInfo>* GetLineInfo() { return &m_lineinfo; } private: OpVector<SVGLineInfo> m_lineinfo; }; #endif // SVG_SUPPORT #endif // SVG_TEXT_ELEMENT_STATE_CONTEXT
#include "MxRenderStateManager.h" #include "../../MixEngine.h" #include "MxGPUParams.h" namespace Mix { std::shared_ptr<GPUPipelineParamsInfo> RenderStateManager::createGPUPipelineParamsInfo(const GraphicsParamsDesc& _desc) const { return std::shared_ptr<GPUPipelineParamsInfo>(new GPUPipelineParamsInfo(_desc)); } std::shared_ptr<GPUPipelineParamsInfo> RenderStateManager::createGPUPipelineParamsInfo(const ComputeParamsDesc& _desc) const { return std::shared_ptr<GPUPipelineParamsInfo>(new GPUPipelineParamsInfo(_desc)); } std::shared_ptr<GPUParams> RenderStateManager::createGPUParams(const std::shared_ptr<GPUPipelineParamsInfo>& _info) const { return std::shared_ptr<GPUParams>(new GPUParams(_info)); } std::shared_ptr<GraphicsPipelineState> RenderStateManager::createGraphicsPipelineState(const GraphicsPipelineStateDesc& _desc) { return std::shared_ptr<GraphicsPipelineState>(new GraphicsPipelineState(_desc)); } }
//////////////////////////////////////////////////////// // GUI EDITOR OUTPUT START (by Casperento, v1.063, #Quxufi) //////////////////////////////////////////////////////// class cxp_actualdead_List { idd = 52900; name = "cxp_actualdead_List"; movingEnable = false; enableSimulation = true; class ControlsBackground { class CXP_DLST_MAINBG { type = 0; idc = -1; x = safeZoneX + safeZoneW * 0.23875; y = safeZoneY + safeZoneH * 0.19111112; w = safeZoneW * 0.523125; h = safeZoneH * 0.65666667; style = 0; text = ""; colorBackground[] = {0,0,0,0.8413}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_TIT { type = 0; idc = -1; x = safeZoneX + safeZoneW * 0.23875; y = safeZoneY + safeZoneH * 0.16111112; w = safeZoneW * 0.52375; h = safeZoneH * 0.02888889; style = 2; text = "CXP DEAD LIST"; colorBackground[] = {1,0,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_STATUSPAC { type = 0; idc = -1; x = safeZoneX + safeZoneW * 0.470625; y = safeZoneY + safeZoneH * 0.21333334; w = safeZoneW * 0.28875; h = safeZoneH * 0.05666667; style = 1; text = "Sobre o paciente:"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_PACLISTtIT { type = 0; idc = -1; x = safeZoneX + safeZoneW * 0.24875; y = safeZoneY + safeZoneH * 0.22222223; w = safeZoneW * 0.176875; h = safeZoneH * 0.04; style = 0; text = "Pacientes disponiveis:"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; }; class Controls { class CXP_DLST_MapPacLocate : Cxp_RscMapControl { idc = 1650; x = safeZoneX + safeZoneW * 0.431875; y = safeZoneY + safeZoneH * 0.38111112; w = safeZoneW * 0.319375; h = safeZoneH * 0.30777778; maxSatelliteAlpha = 0.75; alphaFadeStartScale = 1.15;//0.15; alphaFadeEndScale = 1.29;//0.29; }; class CXP_DLST_ListBoxPac { type = 5; idc = 52901; x = safeZoneX + safeZoneW * 0.248125; y = safeZoneY + safeZoneH * 0.26888889; w = safeZoneW * 0.173125; h = safeZoneH * 0.55333334; style = 16; colorBackground[] = {0,0,0,1}; colorDisabled[] = {0,0,0,1}; colorSelect[] = {0.2541,1,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; maxHistoryDelay = 0; rowHeight = 0; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; soundSelect[] = {"\A3\ui_f\data\sound\RscListbox\soundSelect",0.09,1.0}; class ListScrollBar { color[] = {1,1,1,1}; thumb = "\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa"; arrowFull = "\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa"; arrowEmpty = "\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa"; border = "\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa"; }; onLBSelChanged = "_this call cxp_fnc_onLbChangeDeadList;"; }; class CXP_DLST_BtnCancel { type = 1; idc = 0; x = safeZoneX + safeZoneW * 0.433125; y = safeZoneY + safeZoneH * 0.77333334; w = safeZoneW * 0.08375; h = safeZoneH * 0.04222223; style = 0+2; text = "CANCELAR"; onButtonClick = "closeDialog 0;[] spawn cxp_fnc_cancelarChamado;"; borderSize = 0; colorBackground[] = {0.6,0,0,1}; colorBackgroundActive[] = {0.702,0.702,0.702,1}; colorBackgroundDisabled[] = {0.2,0.2,0.2,1}; colorBorder[] = {0,0,0,0}; colorDisabled[] = {0.2,0.2,0.2,1}; colorFocused[] = {0.2,0.2,0.2,1}; colorShadow[] = {0,0,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; offsetPressedX = 0.01; offsetPressedY = 0.01; offsetX = 0.01; offsetY = 0.01; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1.0}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1.0}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1.0}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1.0}; tooltip = "Cancelar chamado atual..."; }; class CXP_DLST_BtnLock { type = 1; idc = 52962; x = safeZoneX + safeZoneW * 0.43375; y = safeZoneY + safeZoneH * 0.71555556; w = safeZoneW * 0.08375; h = safeZoneH * 0.04222223; style = 0+2; text = "LOCALIZAR"; onButtonClick = "[] spawn cxp_fnc_localizarDefunto;"; borderSize = 0; colorBackground[] = {0.6,0,0,1}; colorBackgroundActive[] = {0.702,0.702,0.702,1}; colorBackgroundDisabled[] = {0.2,0.2,0.2,1}; colorBorder[] = {0,0,0,0}; colorDisabled[] = {0.2,0.2,0.2,1}; colorFocused[] = {0.2,0.2,0.2,1}; colorShadow[] = {0,0,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; offsetPressedX = 0.01; offsetPressedY = 0.01; offsetX = 0.01; offsetY = 0.01; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1.0}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1.0}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1.0}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1.0}; tooltip = "Localizar paciente selecionado..."; }; class CXP_DLST_BtnRemove { type = 1; idc = 52961; x = safeZoneX + safeZoneW * 0.524375; y = safeZoneY + safeZoneH * 0.77333334; w = safeZoneW * 0.08375; h = safeZoneH * 0.04222223; style = 0+2; text = "REMOVER"; onButtonClick = "closeDialog 0;[] call cxp_fnc_apagarItemLista;"; borderSize = 0; colorBackground[] = {0.6,0,0,1}; colorBackgroundActive[] = {0.702,0.702,0.702,1}; colorBackgroundDisabled[] = {0.2,0.2,0.2,1}; colorBorder[] = {0,0,0,0}; colorDisabled[] = {0.2,0.2,0.2,1}; colorFocused[] = {0.2,0.2,0.2,1}; colorShadow[] = {0,0,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; offsetPressedX = 0.01; offsetPressedY = 0.01; offsetX = 0.01; offsetY = 0.01; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1.0}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1.0}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1.0}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1.0}; tooltip = "Remover item da lista..."; }; class CXP_DLST_BtnClose { type = 1; idc = -1; x = safeZoneX + safeZoneW * 0.615625; y = safeZoneY + safeZoneH * 0.77333334; w = safeZoneW * 0.08375; h = safeZoneH * 0.04222223; style = 0+2; text = "FECHAR"; borderSize = 0; colorBackground[] = {0.6,0,0,1}; colorBackgroundActive[] = {0.702,0.702,0.702,1}; colorBackgroundDisabled[] = {0.2,0.2,0.2,1}; colorBorder[] = {0,0,0,0}; colorDisabled[] = {0.2,0.2,0.2,1}; colorFocused[] = {0.2,0.2,0.2,1}; colorShadow[] = {0,0,0,1}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; offsetPressedX = 0.01; offsetPressedY = 0.01; offsetX = 0.01; offsetY = 0.01; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; soundClick[] = {"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1.0}; soundEnter[] = {"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1.0}; soundEscape[] = {"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1.0}; soundPush[] = {"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1.0}; tooltip = "Fechar menu..."; onButtonClick = "closeDialog 0;"; }; class CXP_DLST_Team { type = 0; idc = 1649; x = safeZoneX + safeZoneW * 0.436875; y = safeZoneY + safeZoneH * 0.33888889; w = safeZoneW * 0.310625; h = safeZoneH * 0.04222223; style = 0; text = "Time: ?"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_NamePac { type = 0; idc = 1648; x = safeZoneX + safeZoneW * 0.436875; y = safeZoneY + safeZoneH * 0.28333334; w = safeZoneW * 0.31125; h = safeZoneH * 0.04222223; style = 0; text = "Nome do paciente: ?"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_DeadBy { type = 0; idc = 1647; x = safeZoneX + safeZoneW * 0.436875; y = safeZoneY + safeZoneH * 0.31111112; w = safeZoneW * 0.3125; h = safeZoneH * 0.04222223; style = 0; text = "Morreu de: ?"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class CXP_DLST_NbAtualPac { type = 0; idc = 1646; x = safeZoneX + safeZoneW * 0.449375; y = safeZoneY + safeZoneH * 0.69444445; w = safeZoneW * 0.305; h = safeZoneH * 0.08; style = 1; text = "Numero de pacientes atuais: 0"; colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; font = "RobotoCondensed"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; }; }; //////////////////////////////////////////////////////// // GUI EDITOR OUTPUT END //////////////////////////////////////////////////////// /* Author: Casperento */
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef FMT_HPP_ #define FMT_HPP_ /*! \brief Standard Data Formats * */ namespace fmt { }; #include "fmt/Bmp.hpp" #include "fmt/Wav.hpp" #include "fmt/Xml.hpp" #include "fmt/Son.hpp" using namespace fmt; #endif /* FMT_HPP_ */
#pragma once class UIAnimator; class ModeSelectBack :public GameObject { public: ModeSelectBack(); void OnDestroy(); void Update(); enum eMode { enNone, endundeon, enpvp, ennetpvp, enAIedit }; //切り替え ダンジョン void Dungeon(); //切り替え PVP void PVP(); //切り替え NETPVP void NetPVP(); //切り替え AIEdhit void AIedit(); //スプライト ALL kill void delSprits(); void moveDungeon(); void movePVP(); void moveNETPVP(); void moveAIedit(); private: SkinModelRender* m_back = nullptr; //haikei SpriteRender* m_backS = nullptr; //haikei(sprite) eMode m_mode = enNone; //いまの状態 CEffect* m_effect = nullptr; //effect; std::vector<SpriteRender*> m_dungeon;//ダンジョンスプライト std::vector<SpriteRender*> m_pvp; //pvpスプライト std::vector<SpriteRender*> m_netpvp;//netpvpスプライト std::vector<SpriteRender*> m_AIedit;//AIedit sprite std::vector<SpriteRender*> m_sprits;//sprite集合体 UIAnimator* m_uia = nullptr; //UIAnimator bool m_isfirst = false; //初めてか? };
#include <iostream> typedef long long ll; using namespace std; int main() { ll t, n, b, w, h, p, bestArea, curArea; bool found; cin >> t; for(int i = 0; i < t; i++) { cin >> n >> b; found = false; bestArea = -1; for(int j = 0; j < n; j++) { cin >> w >> h >> p; if(p <= b) { found = true; curArea = w * h; if(curArea > bestArea) bestArea = curArea; } } if(found) cout << bestArea << endl; else cout << "no tablet" << endl; } }
/* ** EPITECH PROJECT, 2018 ** utils ** File description: ** utils */ #include "include.hpp" #include <string> std::string wchar_to_string(const wchar_t *str); const wchar_t *char_to_wchar(const char *str);
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #define INF 10000000 int n, m; int Map[101][101] = { 0, }; void Floyd() { for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (Map[i][j] > Map[i][k] + Map[k][j]) { Map[i][j] = Map[i][k] + Map[k][j]; } } } } } int main(void) { int Temp1, Temp2, Temp3; scanf("%d", &n); scanf("%d", &m); // 초기화 과정 for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == j) { Map[i][j] = 0; } else { Map[i][j] = INF; } } } for (int i = 0; i < m; i++) { scanf("%d%d%d", &Temp1, &Temp2, &Temp3); if (Map[Temp1][Temp2] != INF) { if (Map[Temp1][Temp2] > Temp3) { Map[Temp1][Temp2] = Temp3; } } else { Map[Temp1][Temp2] = Temp3; } } Floyd(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (Map[i][j] == INF) { printf("%d ", 0); } else { printf("%d ", Map[i][j]); } } printf("\n"); } return 0; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} typedef long long ll; int main() { int n; cin >> n; vector<int> p; rep(i, n){ int tmp; cin >> tmp; p.push_back(tmp);} int minn = MOD; int ans = 0; rep(i, n){ if (minn >= p[i]){ ans++; minn = p[i]; } } cout << ans << endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * George Refseth, rfz@opera.com */ #ifndef APPLE_MAIL_IMPORTER_H #define APPLE_MAIL_IMPORTER_H #if defined (_MACINTOSH_) #include "modules/pi/system/OpFolderLister.h" #include "adjunct/m2/src/import/MboxImporter.h" class AppleMailImporter : public MboxImporter { public: AppleMailImporter(); virtual ~AppleMailImporter(); OP_STATUS Init(); OP_STATUS ImportSettings(); virtual void GetDefaultImportFolder(OpString& path); INT32 GetAccountsVersion() const { return m_accounts_version; } protected: virtual BOOL OnContinueImport(); private: OP_STATUS InsertAllMailBoxes(); OP_STATUS InsertMailBoxes(const OpStringC& accountName, const OpStringC& m2FolderPath, INT32 parentIndex, CFDictionaryRef dict); void InsertMailboxIfValid(const OpStringC& mailboxPath, const OpStringC& account, const OpStringC& m2FolderPath, INT32 parentIndex = -1); OP_STATUS InsertAccount(CFDictionaryRef dict); OP_STATUS ImportAccount(const OpStringC& accountName); BOOL FindAccountDictionary(const OpStringC& accountName, CFDictionaryRef &dict); CFDictionaryRef GetLocalAccountDictionary(); void ParseEmlxFile(const uni_char* path); CFDictionaryRef m_dictionary; CFDictionaryRef m_localaccount_dictionary; OpFolderLister* m_folder_lister; INT32 m_accounts_version; }; #endif // _MACINTOSH_ || UNIX #endif //APPLE_MAIL_IMPORTER_H
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<map> using namespace std; class Solution { public: int getSum(int a, int b) { //迭代:位运算,a^b是无进位的相加;a&b<<1得到每一位的进位 int carry,sum; sum=a^b; carry=static_cast<unsigned int>(a&b)<<1; while(carry!=0) { a=sum,b=carry; sum=a^b; carry=static_cast<unsigned int>(a&b)<<1; } return sum; } }; class Solution1 { public: int getSum(int a, int b) { //基本思想:位运算,a^b是无进位的相加;a&b<<1得到每一位的进位; //让无进位相加的结果与进位不断的异或,直到进位为0 int carry,sum; sum=a^b; carry=static_cast<unsigned int>(a&b)<<1; if(carry!=0) return getSum(sum,carry); return sum; } }; int main() { Solution solute; int a=1,b=3; cout<<solute.getSum(a,b)<<endl; return 0; }
/** * Description: find sqrt of integer via a prime * Source: http://www.math.vt.edu/people/brown/class_homepages/shanks_tonelli.pdf * Verification: https://www.spoj.com/problems/CRYPTO1 */ int modsqrt(int a) { int p = po(a,(MOD-1)/2); if (p != 1) return p == 0 ? 0 : -1; int s = MOD-1, e = 0; while (s % 2 == 0) s /= 2, e ++; int n = 1; while (po(n,(MOD-1)/2) == 1) n ++; // find non-square residue int x = po(a,(s+1)/2), b = po(a,s), g = po(n,s), r = e; while (1) { int B = b, m = 0; while (B != 1) B = mul(B,B), m ++; if (m == 0) break; F0R(i,r-m-1) MUL(g,g); MUL(x,g); MUL(g,g); MUL(b,g); r = m; /* Explanation: * Initially, x^2=ab, ord(b) = 2^m, ord(g) = 2^r where m<r * g = g^{2^{r-m-1}} -> ord(g) = 2^{m+1} * if x'=x*g, then b' = b*g^2 (b')^{2^{m-1}} = (b*g^2)^{2^{m-1}} = b^{2^{m-1}}*g^{2^m} = -1*-1 = 1 -> ord(b')|ord(b)/2 * m decreases by at least one each iteration */ } ckmin(x,MOD-x); return x; }
#include <bits/stdc++.h> using namespace std; int main() { string s; stringstream ss; double num; scanf("%lE", &num); ss << num; ss >> s; ss.clear(); if(s[0]=='-') printf("%.4lE\n", num); else printf("+%.4lE\n", num); return 0; }
#pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int main(int argc, char* argv[]) { abhisheknaiidu(); vector<int> nums1{3, 4, 6, 10, 11, 15}; vector<int> nums2{1, 5, 8, 12, 14, 19}; int l1 = 0; int l2 = 0; int n1 = nums1.size(); int n2 = nums2.size(); vector<int> ans; while(l1 < n1 && l2 < n2) { if(nums1[l1] < nums2[l2]) { ans.push_back(nums1[l1]); l1++; } else if(nums1[l1] > nums2[l2]) { ans.push_back(nums2[l2]); l2++; } } if(l1 == n1) { for(int i=l2; i<n2; i++) { ans.push_back(nums2[i]); } } else if(l2 == n2) { for(int i=l1; i<n1; i++) { ans.push_back(nums1[i]); } } cout << l1 << " " << l2 << endl; for(auto x: ans) { cout << x << " "; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SCOPE_DESKTOP_WINDOW_MANAGER_H #define SCOPE_DESKTOP_WINDOW_MANAGER_H #include "modules/scope/src/scope_service.h" #include "adjunct/desktop_scope/src/generated/g_scope_desktop_window_manager_interface.h" #include "adjunct/quick/windows/DocumentWindowListener.h" #include "adjunct/quick_toolkit/windows/DesktopWindow.h" #include "adjunct/quick_toolkit/widgets/DesktopWidgetWindow.h" class OpWidget; class SystemInputPI; /* class OpScopeDesktopWidgetLister { public: virtual OP_STATUS ListWidgets(QuickWidgetInfoList &out); }; */ class OpScopeDesktopWindowManager : public OpScopeDesktopWindowManager_SI , public DesktopWindowListener , public DocumentWindowListener , public WidgetWindow::Listener { public: OpScopeDesktopWindowManager(); virtual ~OpScopeDesktopWindowManager(); // DesktopWindow::Listener virtual void OnDesktopWindowChanged(DesktopWindow* desktop_window); virtual void OnDesktopWindowActivated(DesktopWindow* desktop_window, BOOL active); virtual void OnDesktopWindowClosing(DesktopWindow* desktop_window, BOOL user_initiated); virtual void OnDesktopWindowShown(DesktopWindow* desktop_window, BOOL shown); virtual void OnDesktopWindowPageChanged(DesktopWindow* desktop_window); // DesktopMenuHandler void OnMenuShown(BOOL shown, QuickMenuInfo& info); // DocumentWindowListener virtual void OnLoadingFinished(DocumentDesktopWindow* document_window, OpLoadingListener::LoadingFinishStatus status, BOOL was_stopped_by_user = FALSE); // WidgetWindow::Listener virtual void OnClose(WidgetWindow* window); virtual void OnShow(WidgetWindow* window, BOOL shown); // OpScopeService virtual OP_STATUS OnServiceEnabled(); // Puts all the widget info into a string to display in a tooltip void GetQuickWidgetInfoToolTip(OpWidget *widget, OpString &tooltip_text); // Called when a menu item is pressed OP_STATUS MenuItemPressed(const OpStringC& menu_text, BOOL popmenu = FALSE); SystemInputPI *GetSystemInputPI() { return m_system_input_pi; } void PageLoaded(DesktopWindow* desktop_window); // Request/Response functions OP_STATUS DoGetActiveWindow(DesktopWindowID &out); OP_STATUS DoListWindows(DesktopWindowList &out); OP_STATUS DoListQuickWidgets(const DesktopWindowID &in, QuickWidgetInfoList &out); OP_STATUS DoGetQuickWidget(const QuickWidgetSearch &in, QuickWidgetInfo &out); OP_STATUS DoListQuickMenus(QuickMenuList &out); OP_STATUS DoPressQuickMenuItem(const QuickMenuItemID &in); OpScopeDesktopWindowManager_SI::QuickWidgetInfo::QuickWidgetType GetWidgetType(OpWidget *widget); private: void GetQuickWidgetInfoToolTip(QuickWidgetInfo &widget_info, OpString &tooltip_text, OpString &watir_access_path, BOOL add_to_path, BOOL next_parent, OpWidget *widget = NULL, BOOL skip_parents = FALSE); void BuildWatirAccessString(QuickWidgetInfo& widget_info, OpString& access_path, BOOL insert_first); void GetWatirWidgetType(QuickWidgetInfo::QuickWidgetType type, OpString& widget_type); // Sets the data in the proto message structure from the Opera opject OP_STATUS SetQuickWidgetInfo(QuickWidgetInfo& info, OpWidget* wdg); OP_STATUS SetDesktopWindowInfo(DesktopWindowInfo &info, DesktopWindow *win); OP_STATUS SetDesktopWindowInfo(DesktopWindowInfo &info, DesktopWidgetWindow *win); // Convert between the Opera enum and the proto enums OpScopeDesktopWindowManager_SI::DesktopWindowInfo::DesktopWindowType GetWindowType(OpTypedObject::Type type); OpScopeDesktopWindowManager_SI::DesktopWindowInfo::DesktopWindowState GetWindowState(OpWindow::State state); OpWidget* GetWidgetByText(DesktopWindow* window, OpString8& text); OpWidget* GetParentToolbar(OpWidget* widget); OpWidget* GetParentTab(OpWidget* widget); DesktopWidgetWindow* GetDesktopWidgetWindow(INT32 id); OP_STATUS GetWidgetInWidgetWindow(DesktopWidgetWindow* window, const QuickWidgetSearch& in, QuickWidgetInfo& out); void CopyDesktopWindowInfo(DesktopWindowInfo &from, DesktopWindowInfo &to); DesktopWindowInfo m_last_closed; DesktopWindowInfo m_last_activated; // All open DesktopWidgetWindows are referenced in this collection // Listing windows lists the windows in the DesktopWindowCollection pluss these OpVector<DesktopWidgetWindow> m_widget_windows; SystemInputPI *m_system_input_pi; }; #endif // SCOPE_DESKTOP_WINDOW_MANAGER_H
#include <iostream> #include <string> #include <cstring> #include <algorithm> using namespace std; int main() { char a[50]; while(cin >> a && (strcmp(a,"#")!=0)) { if(next_permutation(a,a+strlen(a))) cout << a << endl; else cout << "No Successor" << endl; } return 0; }
#pragma once #include "stdafx.h" #include "DataTypes/vec.h" #include <map> #include <string> #include <GL\gl.h> typedef std::map<std::string, Vec3f> intMap; #define nbFixColor 10 Vec3f fixColor[nbFixColor] = {Vec3f(0,0,1), Vec3f(0,1,0), Vec3f(1,0,0), Vec3f(1,0,1), Vec3f(0,1,1), Vec3f(0,0.5,1), Vec3f(0,1,.5), Vec3f(1,0.5,0), Vec3f(0.5,0,1), Vec3f(0,1,0.5)}; #define rand0_1 ((double) rand() / (RAND_MAX)) class ColorGL { public: ColorGL(){}; ~ColorGL(){}; static void setGLColorForKey(char *key) { if (final) return; intMap::const_iterator pos = colorMap.find(key); if (pos == colorMap.end()) { //Create new color if (++idx < nbFixColor){ (colorMap)[key] = fixColor[idx]; } else{ (colorMap)[key] = Vec3f(rand0_1, rand0_1, rand0_1); } pos = colorMap.find(key); } Vec3f c = pos->second; glColor3f(c[0], c[1], c[2]); } static void finalize() { final = true; } private: static intMap colorMap; static int idx; static bool final; }; bool ColorGL:: final = false; int ColorGL::idx = 0; intMap ColorGL::colorMap;
#ifndef __VARDECL__ #define __VARDECL__ // Заголовочный файл с описанием параметров переменных // Standard C++ library #include <iostream> #include <fstream> #include <sstream> // Declares clang::SyntaxOnlyAction. #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" // Declares llvm::cl::extrahelp. #include "llvm/Support/CommandLine.h" #include "llvm/ADT/StringRef.h" //#include "clang/ASTMatchers/ASTMatchers.h" //#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/OperationKinds.h" #include "clang/AST/RecursiveASTVisitor.h" using namespace clang::tooling; using namespace llvm; using namespace clang; //using namespace clang::ast_matchers; using namespace clang; // Определение и тестовый вывод основных параметров описания переменных void getVarDeclParameters(const VarDecl *VD); // Анализ полученного начального значения с последующим использованием void initValueAnalysis(const VarDecl *VD); #endif // __VARDECL__
#include "_pch.h" #include "ViewFav.h" using namespace wh; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class wxDVModel : public wxDataViewModel { const wxDataViewItem NullDataViewItem = wxDataViewItem(nullptr); public: wxDVModel() {}; ~wxDVModel() {}; virtual unsigned int GetColumnCount() const override { return 2; } virtual wxString GetColumnType(unsigned int col) const override { switch (col) { case 0: return "wxDataViewIconText"; case 1: return "string"; default: break; } return "string"; } virtual bool HasContainerColumns(const wxDataViewItem& WXUNUSED(item)) const override { return true; } virtual bool IsContainer(const wxDataViewItem &item)const override { if (!item.IsOk()) return true; const auto node = static_cast<const IIdent64*> (item.GetID()); const auto cls = dynamic_cast<const ICls64*>(node); return (bool)cls; //if(cls) // return false; //return (ClsKind::Abstract == cls->GetKind()); } void GetErrorValue(wxVariant &variant, unsigned int col) const { switch (col) { case 0:variant << wxDataViewIconText("*ERROR*", wxNullIcon); break; default: variant = "*ERROR*"; break; } } void GetValue(wxVariant &variant, unsigned int col , const FavAProp& prop) const { switch (col) { case 0: { auto mgr = ResMgr::GetInstance(); wxString str = wxString::Format("%s : %s" , prop.mAct->GetTitle() , FavAPropInfo2Text(prop.mInfo)); const wxIcon& ico = GetIcon(prop.mInfo); variant << wxDataViewIconText(str, ico); }break; case 1: variant = "Данные последнего действия"; break; default: break; }//switch } void GetValue(wxVariant &variant, unsigned int col , const ObjProp& prop) const { switch (col) { case 0: { auto mgr = ResMgr::GetInstance(); const wxIcon& ico = mgr->m_ico_classprop24; variant << wxDataViewIconText(prop.GetTitle(), ico); }break; case 1: variant = "Свойство объекта"; break; default: break; }//switch } void GetValue(wxVariant &variant, unsigned int col , const IProp64& prop) const { switch (col) { case 0: { auto mgr = ResMgr::GetInstance(); const wxIcon& ico = mgr->m_ico_classprop24; variant << wxDataViewIconText(prop.GetTitle(), ico); }break; case 1: variant = "Свойство класса"; break; default: break; }//switch } void GetValue(wxVariant &variant, unsigned int col , const ICls64& cls) const { auto mgr = ResMgr::GetInstance(); const wxIcon* ico(&wxNullIcon); switch (col) { case 0: { switch (cls.GetKind()) { case ClsKind::Abstract: ico = &mgr->m_ico_type_abstract24; break; case ClsKind::Single: ico = &mgr->m_ico_type_num24; break; case ClsKind::QtyByOne: case ClsKind::QtyByFloat: default: ico = &mgr->m_ico_type_qty24; break; }//switch variant << wxDataViewIconText(cls.GetTitle(), *ico); }break; default: break; } } virtual void GetValue(wxVariant &variant, const wxDataViewItem &dvitem, unsigned int col) const override { const auto iobj = static_cast<const IObject*> (dvitem.GetID()); const auto cls = dynamic_cast<const ICls64*>(iobj); if (cls) { GetValue(variant, col, *cls); return; } const auto oprop = dynamic_cast<const ObjProp*>(iobj); if (oprop) { GetValue(variant, col, *oprop); return; } const auto cprop = dynamic_cast<const IProp64*>(iobj); if (cprop) { GetValue(variant, col, *cprop); return; } const auto act_prop = dynamic_cast<const FavAProp*>(iobj); if (act_prop) { GetValue(variant, col, *act_prop); return; } GetErrorValue(variant, col); } virtual bool SetValue(const wxVariant &variant, const wxDataViewItem &item, unsigned int col)override { return false; } virtual wxDataViewItem GetParent(const wxDataViewItem &item) const override { if (!item.IsOk()) return NullDataViewItem; const auto ident = static_cast<const IIdent64*> (item.GetID()); const auto cls = dynamic_cast<const ICls64*>(ident); if (cls) { const auto parent = cls->GetParent(); if (!parent) return NullDataViewItem; return wxDataViewItem((void*)parent.get()); } const auto it = mPropParent.find(item); if (mPropParent.cend() != it) return it->second; return NullDataViewItem; } virtual unsigned int GetChildren(const wxDataViewItem &parent , wxDataViewItemArray &arr) const override { if (!parent.IsOk()) { for (const auto& cls : mClsBranch) { wxDataViewItem item((void*)cls); arr.Add(item); } } else { const auto ident = static_cast<const IIdent64*> (parent.GetID()); const auto cls = dynamic_cast<const ICls64*>(ident); if (cls) { const auto fav_prop_table = cls->GetFavCPropValue(); for (const auto& fp : fav_prop_table) { wxDataViewItem item((void*)fp->mProp.get()); arr.Add(item); } const auto fav_oprop_table = cls->GetFavOProp(); for (const auto& fp : fav_oprop_table) { wxDataViewItem item((void*)fp.get()); arr.Add(item); } const auto fav_act_table = cls->GetFavAProp(); for (const auto& p : fav_act_table) { wxDataViewItem item((void*)p.get()); arr.Add(item); } } } return arr.size(); } std::vector<const ICls64*> mClsBranch; std::map<wxDataViewItem, wxDataViewItem> mPropParent; void SetClsBranch(const std::vector<const ICls64*>& cls_branch) { mPropParent.clear(); mClsBranch = cls_branch; for (const auto& cls : cls_branch) { wxDataViewItem parent((void*)cls); const auto fav_prop_table = cls->GetFavCPropValue(); for (const auto& fp : fav_prop_table) { wxDataViewItem item((void*)fp->mProp.get()); mPropParent.insert(std::make_pair(item, parent)); } const auto fav_oprop_table = cls->GetFavOProp(); for (const auto& fp : fav_oprop_table) { wxDataViewItem item((void*)fp.get()); mPropParent.insert(std::make_pair(item, parent)); } const auto fav_act_table = cls->GetFavAProp(); for (const auto& p : fav_act_table) { wxDataViewItem item((void*)p.get()); mPropParent.insert(std::make_pair(item, parent)); } } Cleared(); } }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- class wxAuiPanel : public wxPanel { public: wxAuiPanel(wxWindow* wnd) :wxPanel(wnd) { mAuiMgr.SetManagedWindow(this); } ~wxAuiPanel() { mAuiMgr.UnInit(); } wxAuiManager mAuiMgr; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ViewFav::ViewFav(const std::shared_ptr<IViewWindow>& parent) :ViewFav(parent->GetWnd()) { } //----------------------------------------------------------------------------- ViewFav::ViewFav(wxWindow* parent) { auto mgr = ResMgr::GetInstance(); mPanel = new wxDialog(parent, wxID_ANY, "Favorite attribute" , wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); wxSizer* szrMain = new wxBoxSizer(wxVERTICAL); mPanel->SetSizer(szrMain); long style = wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_PLAIN_BACKGROUND | wxAUI_TB_TEXT //| wxAUI_TB_HORZ_TEXT | wxAUI_TB_OVERFLOW ; mToolBar = new wxAuiToolBar(mPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, style); mToolBar->AddTool(wxID_REFRESH, "Обновить", mgr->m_ico_refresh24, "Обновить (CTRL+R или CTRL+F5)"); auto add_tool = mToolBar->AddTool(wxID_ADD, "Добавить", mgr->m_ico_plus24, "Добавить новое свойство для отображения (CTRL+INSERT)"); add_tool->SetHasDropDown(true); mToolBar->AddTool(wxID_DELETE, "Удалить", mgr->m_ico_delete24, "Удалить выбранное свойство (F8)"); mToolBar->AddTool(wxID_HELP_INDEX, "Справка", wxArtProvider::GetBitmap(wxART_HELP, wxART_TOOLBAR), "Справка (F1)"); mToolBar->Realize(); szrMain->Add(mToolBar, 0, wxEXPAND, 0); mToolBar->Bind(wxEVT_AUITOOLBAR_TOOL_DROPDOWN , [this, mgr](wxCommandEvent& evt) { wxAuiToolBar* tb = static_cast<wxAuiToolBar*>(evt.GetEventObject()); tb->SetToolSticky(evt.GetId(), true); wxMenu add_menu; AppendBitmapMenu(&add_menu, wxID_FILE1, "свойство типа", mgr->m_ico_folder_type24 ); AppendBitmapMenu(&add_menu, wxID_FILE2, "свойство объекта", mgr->m_ico_obj24); AppendBitmapMenu(&add_menu, wxID_FILE3, "дату предыдущего действия", mgr->m_ico_act_previos16); AppendBitmapMenu(&add_menu, wxID_FILE4, "период действия", mgr->m_ico_act_period16); AppendBitmapMenu(&add_menu, wxID_FILE5, "дату следующего действия", mgr->m_ico_act_next16); AppendBitmapMenu(&add_menu, wxID_FILE6, "остаток дней до след.действия", mgr->m_ico_act_left16); wxRect rect = tb->GetToolRect(evt.GetId()); wxPoint pt = tb->ClientToScreen(rect.GetBottomLeft()); pt = tb->ScreenToClient(pt); tb->PopupMenu(&add_menu, pt); tb->SetToolSticky(evt.GetId(), false); tb->Refresh(); } , wxID_ADD); mTable = new wxDataViewCtrl(mPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize , wxDV_ROW_LINES | wxDV_VERT_RULES //| wxDV_HORIZ_RULES //| wxDV_MULTIPLE //| wxDV_NO_HEADER ); auto dv_model = new wxDVModel(); mTable->AssociateModel(dv_model); dv_model->DecRef(); #define ICON_HEIGHT 24+2 int row_height = mTable->GetCharHeight() + 2;// + 1px in bottom and top if (ICON_HEIGHT > row_height) row_height = ICON_HEIGHT; mTable->SetRowHeight(row_height); auto col0 = mTable->AppendIconTextColumn("Тип", 0, wxDATAVIEW_CELL_INERT, -1 , wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE); auto col1 = mTable->AppendTextColumn("Описание", 1, wxDATAVIEW_CELL_INERT, -1 , wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE); szrMain->Add(mTable, 1, wxALL | wxEXPAND, 2); wxSizer* szrBtn = new wxBoxSizer(wxHORIZONTAL); //auto btnOK = new wxButton(mPanel, wxID_OK); auto btnCancel = new wxButton(mPanel, wxID_CANCEL,"Закрыть"); szrBtn->Add(0, 0, 1, wxEXPAND, 2); //szrBtn->Add(btnOK, 0, wxALL, 2); szrBtn->Add(btnCancel, 0, wxALL , 2); szrMain->Add(szrBtn, 0, wxEXPAND, 0); mPanel->Layout(); mPanel->SetSize(500, 400); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigRefresh(); }, wxID_REFRESH); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddClsProp(); }, wxID_FILE1); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddObjProp(); }, wxID_FILE2); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddPrevios(); }, wxID_FILE3); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddPeriod(); }, wxID_FILE4); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddNext(); }, wxID_FILE5); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_AddLeft(); }, wxID_FILE6); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {OnCmd_Remove(); }, wxID_DELETE); mToolBar->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent&) {sigShowHelp("PageBrowserByType_favorite"); }, wxID_HELP_INDEX); } //----------------------------------------------------------------------------- //virtual void ViewFav::SetShow() { mPanel->ShowModal(); } //----------------------------------------------------------------------------- //virtual void ViewFav::SetUpdateTitle(const wxString& str, const wxIcon& ico) { mPanel->SetTitle(str); mPanel->SetIcon(ico); } //----------------------------------------------------------------------------- //virtual void ViewFav::SetBeforeUpdate(const std::vector<const ICls64*>& cls_branch, const ICls64&) { auto dvmodel = dynamic_cast<wxDVModel*>(mTable->GetModel()); if (!dvmodel) return; dvmodel->SetClsBranch(cls_branch); } //----------------------------------------------------------------------------- //virtual void ViewFav::SetAfterUpdate(const std::vector<const ICls64*>& cls_branch, const ICls64&) //override; { auto dvmodel = dynamic_cast<wxDVModel*>(mTable->GetModel()); if (!dvmodel) return; dvmodel->SetClsBranch(cls_branch); std::for_each(cls_branch.cbegin(), cls_branch.cend(), [this](const ICls64* cls) { wxDataViewItem item((void*)cls); mTable->Expand(item); }); for (size_t i = 0; i < mTable->GetColumnCount(); i++) { auto col_pos = mTable->GetModelColumnIndex(i); auto col = mTable->GetColumn(col_pos); if (col) col->SetWidth(mTable->GetBestColumnWidth(i)); } auto top_item = mTable->GetTopItem(); if (top_item.IsOk()) mTable->Select(top_item); } //----------------------------------------------------------------------------- const ICls64* ViewFav::GetSelectedItemCls()const { auto dvmodel = dynamic_cast<wxDVModel*>(mTable->GetModel()); if (!dvmodel) return nullptr; wxDataViewItem item = mTable->GetCurrentItem(); const IObject* ident = static_cast<const IObject *> (item.GetID()); if (!ident) return nullptr; auto cls = dynamic_cast<const ICls64*>(ident); if (!cls) { auto parent = dvmodel->GetParent(item); if (!parent.IsOk()) return nullptr; cls = static_cast<const ICls64*>(parent.GetID()); } return cls; } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddClsProp(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddClsProp(cls->GetId() ); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddObjProp(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddObjProp(cls->GetId()); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddPrevios(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddActProp(cls->GetId(), FavAPropInfo::PreviosDate); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddPeriod(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddActProp(cls->GetId(), FavAPropInfo::PeriodDay); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddNext(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddActProp(cls->GetId(), FavAPropInfo::NextDate); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_AddLeft(wxCommandEvent& evt ) { const auto cls = GetSelectedItemCls(); if (cls) sigAddActProp(cls->GetId(), FavAPropInfo::LeftDay); } //----------------------------------------------------------------------------- void ViewFav::OnCmd_Remove(wxCommandEvent & evt) { wxDataViewItem item = mTable->GetCurrentItem(); const IObject* ident = static_cast<const IObject *> (item.GetID()); if (!ident) return; auto dvmodel = dynamic_cast<wxDVModel*>(mTable->GetModel()); if (!dvmodel) return; const auto oprop = dynamic_cast<const ObjProp*>(ident); if (oprop) { auto parent = dvmodel->GetParent(item); if (!parent.IsOk()) return; const auto cls = static_cast<const ICls64*>(parent.GetID()); sigRemoveObjProp(cls->GetId(), oprop->GetId()); return; } const auto cprop = dynamic_cast<const IProp64*>(ident); if (cprop) { auto parent = dvmodel->GetParent(item); if (!parent.IsOk()) return; const auto cls = static_cast<const ICls64*>(parent.GetID()); sigRemoveClsProp(cls->GetId(), cprop->GetId()); return; } const auto act_prop = dynamic_cast<const FavAProp*>(ident); if (act_prop) { auto parent = dvmodel->GetParent(item); if (!parent.IsOk()) return; const auto cls = static_cast<const ICls64*>(parent.GetID()); sigRemoveActProp(cls->GetId(), act_prop->mAct->GetId(), act_prop->mInfo ); return; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 2012 * * @author Andreas Farre */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/vm/es_allocation_context.h" ES_Allocation_Context::ES_Allocation_Context(ES_Runtime *runtime) : ES_Context(runtime->GetRuntimeData(), runtime->GetHeap(), runtime, FALSE), next(NULL) { SetHeap(heap); } ES_Allocation_Context::ES_Allocation_Context(ESRT_Data *rt_data) : ES_Context(rt_data, rt_data->heap, NULL, FALSE), next(NULL) { SetHeap(heap); } ES_Allocation_Context::~ES_Allocation_Context() { if (heap) heap->DecContexts(); Remove(); } void ES_Allocation_Context::SetHeap(ES_Heap *new_heap) { OP_ASSERT(!new_heap->InCollector()); next = new_heap->GetAllocationContext(); new_heap->SetAllocationContext(this); heap = new_heap; } void ES_Allocation_Context::Remove() { heap->SetAllocationContext(next); next = NULL; heap = NULL; } void ES_Allocation_Context::MoveToHeap(ES_Heap *new_heap) { Remove(); SetHeap(new_heap); }
#include "stdEntity.h" stdEntity::stdEntity(void) { } stdEntity::~stdEntity(void) { } void stdEntity::Init() { Entity::Init(); RegisterComponent(&tf); RegisterComponent(&render); RegisterComponent(&bc); RegisterComponent(&animComp); } void stdEntity::Update() { Entity::Update(); }
//算法:Floyd求多源最短路 //少有的Floyd的题 //输入数据,用邻接表存边 //然后初始化map[i][i]等于0,即i点到i点的距离为0 //因为可以选择的点包括想去的点,所以要提前初始化,不然Floyd跑一遍后会出错 //然后跑Floyd //之后枚举每一个点,计算他们到达要求点的距离之和, //选出其中和最小的点的编号 //输出即可 #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MARX=0xf; int p,f,c,ans; double minn=999999999; int map[510][510]; int want[510]; int main() { memset(map,MARX,sizeof(map));//初始化极大值 scanf("%d%d%d",&p,&f,&c); for(int i=1;i<=f;i++) scanf("%d",&want[i]); for(int i=1;i<=c;i++)//邻接矩阵存边 { int u,v,w; scanf("%d%d%d",&u,&v,&w); map[u][v]=map[v][u]=w; } for(int i=1;i<=p;i++)//初始化map map[i][i]=0; for(int i=1;i<=p;i++)//floyd for(int j=1;j<=p;j++) for(int k=1;k<=p;k++) if(map[j][k]>map[j][i]+map[i][k]) map[j][k]=map[j][i]+map[i][k]; for(int i=1;i<=p;i++)//枚举每个点,计算最小和 { int sum=0; for(int j=1;j<=f;j++) sum+=map[i][want[j]]; if(minn>(1.0*sum/f))//注意平均值存double形 { minn=1.0*sum/f; ans=i; } } printf("%d",ans); }
#include <vector> #include <string> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <list> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <bitset> #include <deque> #include <random> #include <stdlib.h> const long long LINF = (1e18); const int INF = (1<<28); const int sINF = (1<<23); const int MOD = 1000000007; const double EPS = 1e-6; using namespace std; class DivisorsPower { public: long long powl(long long b, long long e) { long long res = 1; while (e > 0) { if (e&1) res *= b; b = b*b; e >>= 1; } return res; } int count(int n) { int c = 0; for (int i=1; i<=n/i; ++i) { if (n%i == 0) { ++c; if (n / i != i) ++c; } } return c; } long long findArgument(long long hn) { if (hn == 1) return 1; for (int dn=2; dn<=63; ++dn) { double e = 1.0/dn; double candidate = pow(hn, e) + 0.5; if (hn == powl(candidate, dn) && dn == count(candidate)) return candidate; } return -1; } // 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 long long &Expected, const long long &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() { long long Arg0 = 4LL; long long Arg1 = 2LL; verify_case(0, Arg1, findArgument(Arg0)); } void test_case_1() { long long Arg0 = 10LL; long long Arg1 = -1LL; verify_case(1, Arg1, findArgument(Arg0)); } void test_case_2() { long long Arg0 = 64LL; long long Arg1 = 4LL; verify_case(2, Arg1, findArgument(Arg0)); } void test_case_3() { long long Arg0 = 10000LL; long long Arg1 = 10LL; verify_case(3, Arg1, findArgument(Arg0)); } void test_case_4() { long long Arg0 = 2498388559757689LL; long long Arg1 = 49983883LL; verify_case(4, Arg1, findArgument(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { DivisorsPower ___test; ___test.run_test(-1); } // END CUT HERE
#include <QObject> #include <QPainter> #include <stdio.h> #include <math.h> #include "window.h" #include <QLineEdit> #include <QLabel> #include <QHBoxLayout> #include <QSpacerItem> #include <QPushButton> #include <QDebug> #include <QMessageBox> #include <QRadioButton> #define DEFAULT_A -10 #define DEFAULT_B 10 #define DEFAULT_N 10 #define DELTA 0.1 static inline double f_0 (double x) { // return x; // return 3*x*x+2*x+1; //return x*x*x+3*x*x+2*x+1; return sin(x); } static inline double df_0 (double x) { // return 1 + x - x; // return 6*x+2; //return 3*x*x+6*x+2; return cos(x); } Window::Window (QWidget *parent) : QWidget (parent) { a = DEFAULT_A; b = DEFAULT_B; n = DEFAULT_N; parent_save = parent; f = f_0; df = df_0; x = 0; f_array = 0; ksi = 0; v = 0; func = 0; c_1 = 0; c_2 = 0; c_3 = 0; ak_1 = 0; ak_2 = 0; ak_3 = 0; ak_4 = 0; res1 = 0; res2 = 0; change_func (); } Window::~Window() { delete [] x; delete [] f_array; delete [] ksi; delete [] v; delete [] func; delete [] c_1; delete [] c_2; delete [] c_3; delete[]ak_1; delete[]ak_2; delete[]ak_3; delete[]ak_4; } void Window::exit_all () { parent_save->close(); delete this; } QSize Window::minimumSizeHint () const { return QSize (100, 100); } QSize Window::sizeHint () const { return QSize (1000, 1000); } int Window::parse_command_line (int argc, char *argv[]) { if (argc == 1) return -1; if (argc == 2) return -2; if (sscanf (argv[1], "%lf", &a) != 1 || sscanf (argv[2], "%lf", &b) != 1 || b - a < MIN_FOR_COMPARE || (argc > 3 && sscanf (argv[3], "%d", &n) != 1) || n <= 0) return -3; scale_coeff = 1.0; func_id = 0; idx_delta_function = 0; val_delta_function = 0; return 1; } void Window::init_drawing_plane (QPainter &painter) { double w = width(), h = height(); painter.translate (0.5 * w, 0.5 * h); painter.scale (scale_coeff, -scale_coeff); painter.setPen ("red"); painter.drawLine (-w/2, 0., w/2, 0.); painter.drawLine (0., -h/2, 0., h/2); painter.setPen("black"); painter.drawLine (1.0, 1, 1.0, -1); painter.drawLine (1, 1.0, -1, 1.0); } void Window::paintEvent (QPaintEvent*) { QPainter painter(this); painter.save (); int i, N = n; double x1, x2, y1, y2; if (n < 4) N = 4; else if (n > 3000) N = 3000; double step = (b-a)/width(); init_drawing_plane (painter); /// draw real graph if (func_id < 3) { painter.setPen ("blue"); x1 = a; y1 = f (a); func[idx_delta_function] += val_delta_function; for (i = 1, x2 = x1 + step; i < width(); i++, x2 += step) { y2 = f (x2); if (fabs (x[idx_delta_function] - x2) <= step) y2 += val_delta_function; painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); x1 = x2, y1 = y2; } x2 = b; y2 = f(x2); } /// draw Akima if (func_id == 0) { painter.setPen ("green"); x1 = a; y1 = f(a); res1 = 0; res2 = 0; for (i = 0; i < width(); i++) { x2 = x1 + step; y2 = AkimaSolve(x2, N); if (fabs(y2 - f(x2)) > res1) { res1 = fabs(y2 - f(x2)); } painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); x1 = x2, y1 = y2; } x2 = b; y2 = f(x2); painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); } /// draw Spline if (func_id == 1) { painter.setPen ("black"); x1 = a; y1 = f (a); res2 = 0; res1 = 0; for (i = 0; i < width(); i++) { x2 = x1 + step; y2 = SplineSolve(x2, N); if (fabs(y2 - f(x2)) > res2) { res2 = fabs(y2 - f(x2)); } painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); x1 = x2, y1 = y2; } x2 = b; y2 = f(x2); painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); } /// draw Residual if (func_id == 2) { painter.setPen ("green"); x1 = a; y1 = 0.;//f (x1); res1 = 0; for (i = 1; i < width (); i++) { x2 = x1 + step; y2 = f(x2) - AkimaSolve(x2, N); if (fabs(y2) > res1) { res1 = fabs(y2); } painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); x1 = x2, y1 = y2; } x2 = b; y2 = 0.; painter.drawLine (QPointF (x1, y1), QPointF (x2, y2)); painter.setPen ("black"); x1 = a; y1 = 0.;//f (x1); res2 = 0; for (i = 1; i < width (); i++) { x2 = x1 + step; y2 = f(x2) - SplineSolve(x2, N); if (fabs(y2) > res2) { res2 = fabs(y2); } painter.drawLine(QPointF (x1, y1), QPointF (x2, y2)); x1 = x2, y1 = y2; } x2 = b; y2 = 0.; painter.drawLine(QPointF (x1, y1), QPointF (x2, y2)); } f_name.clear(); switch (func_id) { case 0: f_name.append("Akima; n="); break; case 1: f_name.append("Spline; n="); break; case 2: f_name.append("Residual; n="); } painter.scale(1.0/scale_coeff, -1.0/scale_coeff); painter.setPen("black"); f_name.append(QString::number(N)); painter.drawText(-1*width()/2 + 5, -1*height()/2 + 20, f_name); f_name.clear(); f_name.append(" a = "); f_name.append(QString::number(a)); f_name.append(" b = "); f_name.append(QString::number(b)); painter.drawText(-1*width()/2 + 5, -1*height()/2 + 40, f_name); f_name.clear(); f_name.append(" res1 = "); f_name.append(QString::number(res1)); f_name.append(" res2 = "); f_name.append(QString::number(res2)); painter.drawText(-1*width()/2 + 5, -1*height()/2 + 60, f_name); f_name.clear(); // f_name.clear(); // f_name.append(QString::number(1)); // painter.drawText(1, -1, f_name); painter.restore(); } static inline void free_array (double *arr) { if (arr) delete [] arr; arr = 0; } void Window::update_arrays (int n) { free_array (x); free_array (f_array); free_array (ksi); free_array (v); free_array (func); free_array (c_1); free_array (c_2); free_array (c_3); free_array (ak_1); free_array (ak_2); free_array (ak_3); free_array (ak_4); x = new double [n]; f_array = new double [n]; ksi = new double [n]; v = new double [n]; func = new double [n]; c_1 = new double [n]; c_2 = new double [n]; c_3 = new double [n]; ak_1 = new double [n]; ak_2 = new double [n]; ak_3 = new double [n]; ak_4 = new double [n]; }
#ifndef F3LIB_UTILS_VALUECONVERTER_H_ #define F3LIB_UTILS_VALUECONVERTER_H_ namespace f3 { namespace utils { template<typename T> inline T getValue(const std::string& input, const f3::types::DefineMap& defineMap) { f3::types::DefineMap::const_iterator it = defineMap.find(input); if (it != defineMap.end()) { return static_cast<T>(it->second); } return static_cast<T>(std::atoi(input.c_str())); } } // namespace utils } // namespace f3 #endif // F3LIB_UTILS_VALUECONVERTER_H_
#include "scran.h" /* This computes the mean and CV2 for every gene, while also dividing through by the size factors. */ template <typename T> SEXP compute_CV2_internal(const T* ptr, const matrix_info& MAT, SEXP subset_row, SEXP size_factors) { subset_values rsubout=check_subset_vector(subset_row, MAT.nrow); const int rslen=rsubout.first; const int* rsptr=rsubout.second; const size_t& ncells=MAT.ncol; if (ncells < 2) { throw std::runtime_error("need two or more cells to compute variances"); } if (!isReal(size_factors)) { throw std::runtime_error("size factors should be double-precision"); } else if (LENGTH(size_factors)!=int(ncells)) { throw std::runtime_error("number of size factors is not equal to number of cells"); } const double* sfptr=REAL(size_factors); // Temporaries. double* tmp=(double*)R_alloc(MAT.ncol, sizeof(double)); size_t col; const T* ptr_cpy; double diff; SEXP output=PROTECT(allocVector(VECSXP, 2)); try { SET_VECTOR_ELT(output, 0, allocVector(REALSXP, rslen)); double* omptr=REAL(VECTOR_ELT(output, 0)); SET_VECTOR_ELT(output, 1, allocVector(REALSXP, rslen)); double* ovptr=REAL(VECTOR_ELT(output, 1)); for (int ri=0; ri<rslen; ++ri) { ptr_cpy=ptr+rsptr[ri]; for (col=0; col<ncells; ++col) { tmp[col]=ptr_cpy[col*MAT.nrow]/sfptr[col]; } // Computing the mean. double& curmean=(omptr[ri]=0); for (col=0; col<ncells; ++col) { curmean+=tmp[col]; } curmean/=ncells; // Computing the variance. double& curvar=(ovptr[ri]=0); for (col=0; col<ncells; ++col) { diff=tmp[col]-curmean; curvar+=diff*diff; } curvar/=(ncells-1); } } catch (std::exception& e) { UNPROTECT(1); throw; } UNPROTECT(1); return output; } SEXP compute_CV2(SEXP exprs, SEXP subset_row, SEXP size_factors) try { const matrix_info MAT=check_matrix(exprs); if (MAT.is_integer) { return compute_CV2_internal<int>(MAT.iptr, MAT, subset_row, size_factors); } else { return compute_CV2_internal<double>(MAT.dptr, MAT, subset_row, size_factors); } } catch (std::exception& e) { return mkString(e.what()); }
#include <signal.h> #include "CDLReactor.h" #include "Configure.h" #include "Logger.h" #include "Version.h" #include "RobotSvrConfig.h" #include "GameServerConnect.h" #include "ClientHandler.h" #include "ProcessManager.h" #include "GameCmd.h" #include "Protocol.h" #include "Packet.h" #include "Util.h" #include "NamePool.h" int initGameConnector() { RobotSvrConfig& svf = RobotSvrConfig::getInstance(); svf.initServerConf(Configure::getInstance().serverxml.c_str()); for(int i =0; i<svf.getServerListSize();++i) { ServerNode* node = svf.getServerNode(i); GameConnector* gameserver = new GameConnector(node->svid); if(gameserver && gameserver->connect(node->ip, node->port) !=0) { LOGGER(E_LOG_ERROR) << "Svid[" << node->svid << "] Connect BackServer error[" << node->ip << ":" << node->port; delete gameserver; exit(1); } BackGameConnectManager::addGameNode(node->svid, gameserver); } return 0; } int main(int argc, char* argv[]) { CDLReactor::Instance()->Init(); #ifndef WIN32 srand((unsigned int)time(0)^getpid()); Util::registerSignal(); #endif if(!Configure::getInstance().LoadConfig(argc, argv)) { LOGGER(E_LOG_ERROR) << "ReadConfig Failed."; return -1; } AddressInfo addrLog; Util::parseAddress(Configure::getInstance().m_sLogAddr.c_str(), addrLog); CLogger::InitLogger(Configure::getInstance().m_nLogLevel, Configure::getInstance().GetGameTag(), Configure::getInstance().id, addrLog.ip, addrLog.port); NamePool::getInstance()->Initialize("../conf/names.txt"); // RobotServer robotserver(Configure::getInstance().m_sListenIp.c_str(), Configure::getInstance().m_nPort); // if (CDLReactor::Instance()->RegistServer(&robotserver) == -1) // { // LOGGER(E_LOG_ERROR) << "register server failed!"; // return -1; // } // else // { // LOGGER(E_LOG_DEBUG) << "RobotServer have been started,listen port:" << Configure::getInstance().port; // } if(initGameConnector()<0) { LOGGER(E_LOG_ERROR) << "Init Alloc Server Connector fault,System exit!"; return -1; } return CDLReactor::Instance()->RunEventLoop(); }
#include <touchgfx/hal/Types.hpp> FONT_GLYPH_LOCATION_FLASH_PRAGMA KEEP extern const uint8_t unicodes_verdana_40_4bpp_0[] FONT_GLYPH_LOCATION_FLASH_ATTRIBUTE = { // Unicode: [0x0030] 0x00, 0x00, 0x00, 0x00, 0x64, 0x67, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xE9, 0xFF, 0xFF, 0xFF, 0x5C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE5, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x00, 0x00, 0x00, 0x40, 0xFF, 0xFF, 0xEF, 0xED, 0xFF, 0xFF, 0xAF, 0x00, 0x00, 0x00, 0xE1, 0xFF, 0xCF, 0x04, 0x00, 0x71, 0xFF, 0xFF, 0x06, 0x00, 0x00, 0xF8, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0xF4, 0xFF, 0x0E, 0x00, 0x00, 0xFE, 0xEF, 0x02, 0x00, 0x00, 0x00, 0x90, 0xFF, 0x6F, 0x00, 0x50, 0xFF, 0x9F, 0x00, 0x00, 0x00, 0x00, 0x20, 0xFF, 0xBF, 0x00, 0x90, 0xFF, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xEF, 0x00, 0xC0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF9, 0xFF, 0x03, 0xE0, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0xFF, 0x06, 0xF1, 0xFF, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5, 0xFF, 0x08, 0xF3, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0xFF, 0x0A, 0xF4, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0A, 0xF5, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0B, 0xF5, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0C, 0xF5, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0C, 0xF5, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0B, 0xF4, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0B, 0xF3, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0xFF, 0x0A, 0xF1, 0xFF, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xFF, 0x08, 0xE0, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0xFF, 0x06, 0xC0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0xFF, 0x04, 0x90, 0xFF, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xFF, 0x01, 0x50, 0xFF, 0x9F, 0x00, 0x00, 0x00, 0x00, 0x20, 0xFF, 0xCF, 0x00, 0x10, 0xFE, 0xEF, 0x02, 0x00, 0x00, 0x00, 0x90, 0xFF, 0x7F, 0x00, 0x00, 0xF8, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0xF4, 0xFF, 0x1E, 0x00, 0x00, 0xE1, 0xFF, 0xBF, 0x03, 0x00, 0x71, 0xFF, 0xFF, 0x07, 0x00, 0x00, 0x40, 0xFF, 0xFF, 0xEF, 0xED, 0xFF, 0xFF, 0xAF, 0x00, 0x00, 0x00, 0x00, 0xE5, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x00, 0x00, 0x00, 0x00, 0x20, 0xEA, 0xFF, 0xFF, 0xFF, 0x5C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x64, 0x67, 0x25, 0x00, 0x00, 0x00, 0x00, // Unicode: [0x0033] 0x00, 0x00, 0x10, 0x64, 0x77, 0x57, 0x03, 0x00, 0x00, 0x00, 0x00, 0x83, 0xFC, 0xFF, 0xFF, 0xFF, 0xEF, 0x29, 0x00, 0x00, 0xB0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x06, 0x00, 0xD0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x6F, 0x00, 0xD0, 0xFF, 0x9E, 0x25, 0x00, 0x31, 0xF8, 0xFF, 0xEF, 0x02, 0xD0, 0x5D, 0x00, 0x00, 0x00, 0x00, 0x30, 0xFE, 0xFF, 0x07, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0xFF, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x73, 0xFD, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0x4C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0x8F, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xFF, 0xFF, 0xFF, 0xAF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x50, 0x65, 0x97, 0xFD, 0xFF, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xFF, 0xEF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xFF, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0xFF, 0x6F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0xFF, 0x6F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB0, 0xFF, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF1, 0xFF, 0x1F, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0xFF, 0x0C, 0xEB, 0x28, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0x05, 0xFB, 0xFF, 0x7B, 0x13, 0x00, 0x73, 0xFD, 0xFF, 0xBF, 0x00, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1C, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xAF, 0x01, 0x00, 0x20, 0xB7, 0xFE, 0xFF, 0xFF, 0xFF, 0xAF, 0x04, 0x00, 0x00, 0x00, 0x00, 0x30, 0x65, 0x77, 0x46, 0x00, 0x00, 0x00, 0x00, // Unicode: [0x003F] 0x00, 0x10, 0x53, 0x77, 0x57, 0x02, 0x00, 0x00, 0x00, 0x83, 0xFC, 0xFF, 0xFF, 0xFF, 0xDF, 0x17, 0x00, 0x00, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0x02, 0x00, 0xFD, 0xFF, 0xFF, 0xEF, 0xFF, 0xFF, 0xFF, 0x2E, 0x00, 0xFD, 0x9E, 0x15, 0x00, 0x41, 0xFA, 0xFF, 0xBF, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x00, 0x60, 0xFF, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0xFF, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6, 0xFF, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFF, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC1, 0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xFC, 0xFF, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD3, 0xFF, 0xDF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x81, 0xFF, 0xFF, 0x2C, 0x00, 0x00, 0x00, 0x00, 0x60, 0xFE, 0xFF, 0x9F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0xDF, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xFF, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x44, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF1, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF1, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF1, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF1, 0xFF, 0x0E, 0x00, 0x00, 0x00, 0x00 };
#pragma once #ifndef SCENE_H #define SCENE_H #include "Entity.h" #include "Camera.h" class Scene : public Entity{ public: Scene(); virtual ~Scene(); //update the scene void updateScene(float deltaTime); //update all entities in the scene void updateEntity(Entity* entity, float deltaTime); //check if the scene is still running or if the user has quit bool isRunning(); //start running the scene void start(); //stop running the scene void stop(); //return the camera Camera* getCamera(); Camera* camera; //move this to private private: bool running; }; #endif // !SCENE_H
#include <iostream> #include <stdlib.h> #include "add.h" // import BasicMath::add() using namespace std; int main(void) { system("cls"); cout << BasicMath::add(4, 3) << '\n'; return 0; }
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // Copyright (C) 2009 Sebastian Redl // // 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) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef LIBLAS_BOOST_PROPERTY_TREE_PTREE_HPP_INCLUDED #define LIBLAS_BOOST_PROPERTY_TREE_PTREE_HPP_INCLUDED #include <liblas/external/property_tree/ptree_fwd.hpp> #include <liblas/external/property_tree/string_path.hpp> #include <liblas/external/property_tree/stream_translator.hpp> #include <liblas/external/property_tree/exceptions.hpp> #include <liblas/external/property_tree/detail/ptree_utils.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/indexed_by.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/utility/enable_if.hpp> #include <boost/throw_exception.hpp> #include <boost/optional.hpp> #include <utility> // for std::pair namespace liblas { namespace property_tree { /** * Property tree main structure. A property tree is a hierarchical data * structure which has one element of type @p Data in each node, as well * as an ordered sequence of sub-nodes, which are additionally identified * by a non-unique key of type @p Key. * * Key equivalency is defined by @p KeyCompare, a predicate defining a * strict weak ordering. * * Property tree defines a Container-like interface to the (key-node) pairs * of its direct sub-nodes. The iterators are bidirectional. The sequence * of nodes is held in insertion order, not key order. */ template<class Key, class Data, class KeyCompare> class basic_ptree { #if defined(BOOST_PROPERTY_TREE_DOXYGEN_INVOKED) public: #endif // Internal types /** * Simpler way to refer to this basic_ptree\<C,K,P,A\> type. * Note that this is private, and made public only for doxygen. */ typedef basic_ptree<Key, Data, KeyCompare> self_type; public: // Basic types typedef Key key_type; typedef Data data_type; typedef KeyCompare key_compare; // Container view types typedef std::pair<const Key, self_type> value_type; typedef std::size_t size_type; // The problem with the iterators is that I can't make them complete // until the container is complete. Sucks. Especially for the reverses. class iterator; class const_iterator; class reverse_iterator; class const_reverse_iterator; // Associative view types class assoc_iterator; class const_assoc_iterator; // Property tree view types typedef typename path_of<Key>::type path_type; // The big five /** Creates a node with no children and default-constructed data. */ basic_ptree(); /** Creates a node with no children and a copy of the given data. */ explicit basic_ptree(const data_type &data); basic_ptree(const self_type &rhs); ~basic_ptree(); /** Basic guarantee only. */ self_type &operator =(const self_type &rhs); /** Swap with other tree. Only constant-time and nothrow if the * data type's swap is. */ void swap(self_type &rhs); // Container view functions /** The number of direct children of this node. */ size_type size() const; size_type max_size() const; /** Whether there are any direct children. */ bool empty() const; iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const; value_type &front(); const value_type &front() const; value_type &back(); const value_type &back() const; /** Insert a copy of the given tree with its key just before the given * position in this node. This operation invalidates no iterators. * @return An iterator to the newly created child. */ iterator insert(iterator where, const value_type &value); /** Range insert. Equivalent to: * @code * for(; first != last; ++first) insert(where, *first); * @endcode */ template<class It> void insert(iterator where, It first, It last); /** Erase the child pointed at by the iterator. This operation * invalidates the given iterator, as well as its equivalent * assoc_iterator. * @return A valid iterator pointing to the element after the erased. */ iterator erase(iterator where); /** Range erase. Equivalent to: * @code * while(first != last;) first = erase(first); * @endcode */ iterator erase(iterator first, iterator last); /** Equivalent to insert(begin(), value). */ iterator push_front(const value_type &value); /** Equivalent to insert(end(), value). */ iterator push_back(const value_type &value); /** Equivalent to erase(begin()). */ void pop_front(); /** Equivalent to erase(boost::prior(end())). */ void pop_back(); /** Reverses the order of direct children in the property tree. */ void reverse(); /** Sorts the direct children of this node according to the predicate. * The predicate is passed the whole pair of key and child. */ template<class Compare> void sort(Compare comp); /** Sorts the direct children of this node according to key order. */ void sort(); // Equality /** Two property trees are the same if they have the same data, the keys * and order of their children are the same, and the children compare * equal, recursively. */ bool operator ==(const self_type &rhs) const; bool operator !=(const self_type &rhs) const; // Associative view /** Returns an iterator to the first child, in order. */ assoc_iterator ordered_begin(); /** Returns an iterator to the first child, in order. */ const_assoc_iterator ordered_begin() const; /** Returns the not-found iterator. Equivalent to end() in a real * associative container. */ assoc_iterator not_found(); /** Returns the not-found iterator. Equivalent to end() in a real * associative container. */ const_assoc_iterator not_found() const; /** Find a child with the given key, or not_found() if there is none. * There is no guarantee about which child is returned if multiple have * the same key. */ assoc_iterator find(const key_type &key); /** Find a child with the given key, or not_found() if there is none. * There is no guarantee about which child is returned if multiple have * the same key. */ const_assoc_iterator find(const key_type &key) const; /** Find the range of children that have the given key. */ std::pair<assoc_iterator, assoc_iterator> equal_range(const key_type &key); /** Find the range of children that have the given key. */ std::pair<const_assoc_iterator, const_assoc_iterator> equal_range(const key_type &key) const; /** Count the number of direct children with the given key. */ size_type count(const key_type &key) const; /** Erase all direct children with the given key and return the count. */ size_type erase(const key_type &key); /** Get the iterator that points to the same element as the argument. * @note A valid assoc_iterator range (a, b) does not imply that * (to_iterator(a), to_iterator(b)) is a valid range. */ iterator to_iterator(assoc_iterator it); /** Get the iterator that points to the same element as the argument. * @note A valid const_assoc_iterator range (a, b) does not imply that * (to_iterator(a), to_iterator(b)) is a valid range. */ const_iterator to_iterator(const_assoc_iterator it) const; // Property tree view /** Reference to the actual data in this node. */ data_type &data(); /** Reference to the actual data in this node. */ const data_type &data() const; /** Clear this tree completely, of both data and children. */ void clear(); /** Get the child at the given path, or throw @c ptree_bad_path. * @note Depending on the path, the result at each level may not be * completely determinate, i.e. if the same key appears multiple * times, which child is chosen is not specified. This can lead * to the path not being resolved even though there is a * descendant with this path. Example: * @code * a -> b -> c * -> b * @endcode * The path "a.b.c" will succeed if the resolution of "b" chooses * the first such node, but fail if it chooses the second. */ self_type &get_child(const path_type &path); /** Get the child at the given path, or throw @c ptree_bad_path. */ const self_type &get_child(const path_type &path) const; /** Get the child at the given path, or return @p default_value. */ self_type &get_child(const path_type &path, self_type &default_value); /** Get the child at the given path, or return @p default_value. */ const self_type &get_child(const path_type &path, const self_type &default_value) const; /** Get the child at the given path, or return boost::null. */ ::boost::optional<self_type &> get_child_optional(const path_type &path); /** Get the child at the given path, or return boost::null. */ ::boost::optional<const self_type &> get_child_optional(const path_type &path) const; /** Set the node at the given path to the given value. Create any * missing parents. If the node at the path already exists, replace it. * @return A reference to the inserted subtree. * @note Because of the way paths work, it is not generally guaranteed * that a node newly created can be accessed using the same path. * @note If the path could refer to multiple nodes, it is unspecified * which one gets replaced. */ self_type &put_child(const path_type &path, const self_type &value); /** Add the node at the given path. Create any missing parents. If there * already is a node at the path, add another one with the same key. * @param path Path to the child. The last fragment must not have an * index. * @return A reference to the inserted subtree. * @note Because of the way paths work, it is not generally guaranteed * that a node newly created can be accessed using the same path. */ self_type &add_child(const path_type &path, const self_type &value); /** Take the value of this node and attempt to translate it to a * @c Type object using the supplied translator. * @throw ptree_bad_data if the conversion fails. */ template<class Type, class Translator> typename boost::enable_if<detail::is_translator<Translator>, Type>::type get_value(Translator tr) const; /** Take the value of this node and attempt to translate it to a * @c Type object using the default translator. * @throw ptree_bad_data if the conversion fails. */ template<class Type> Type get_value() const; /** Take the value of this node and attempt to translate it to a * @c Type object using the supplied translator. Return @p default_value * if this fails. */ template<class Type, class Translator> Type get_value(const Type &default_value, Translator tr) const; /** Make get_value do the right thing for string literals. */ template <class Ch, class Translator> typename boost::enable_if< detail::is_character<Ch>, std::basic_string<Ch> >::type get_value(const Ch *default_value, Translator tr) const; /** Take the value of this node and attempt to translate it to a * @c Type object using the default translator. Return @p default_value * if this fails. */ template<class Type> typename boost::disable_if<detail::is_translator<Type>, Type>::type get_value(const Type &default_value) const; /** Make get_value do the right thing for string literals. */ template <class Ch> typename boost::enable_if< detail::is_character<Ch>, std::basic_string<Ch> >::type get_value(const Ch *default_value) const; /** Take the value of this node and attempt to translate it to a * @c Type object using the supplied translator. Return boost::null if * this fails. */ template<class Type, class Translator> ::boost::optional<Type> get_value_optional(Translator tr) const; /** Take the value of this node and attempt to translate it to a * @c Type object using the default translator. Return boost::null if * this fails. */ template<class Type> ::boost::optional<Type> get_value_optional() const; /** Replace the value at this node with the given value, translated * to the tree's data type using the supplied translator. * @throw ptree_bad_data if the conversion fails. */ template<class Type, class Translator> void put_value(const Type &value, Translator tr); /** Replace the value at this node with the given value, translated * to the tree's data type using the default translator. * @throw ptree_bad_data if the conversion fails. */ template<class Type> void put_value(const Type &value); /** Shorthand for get_child(path).get_value(tr). */ template<class Type, class Translator> typename boost::enable_if<detail::is_translator<Translator>, Type>::type get(const path_type &path, Translator tr) const; /** Shorthand for get_child(path).get_value\<Type\>(). */ template<class Type> Type get(const path_type &path) const; /** Shorthand for get_child(path, empty_ptree()) * .get_value(default_value, tr). * That is, return the translated value if possible, and the default * value if the node doesn't exist or conversion fails. */ template<class Type, class Translator> Type get(const path_type &path, const Type &default_value, Translator tr) const; /** Make get do the right thing for string literals. */ template <class Ch, class Translator> typename boost::enable_if< detail::is_character<Ch>, std::basic_string<Ch> >::type get(const path_type &path, const Ch *default_value, Translator tr)const; /** Shorthand for get_child(path, empty_ptree()) * .get_value(default_value). * That is, return the translated value if possible, and the default * value if the node doesn't exist or conversion fails. */ template<class Type> typename boost::disable_if<detail::is_translator<Type>, Type>::type get(const path_type &path, const Type &default_value) const; /** Make get do the right thing for string literals. */ template <class Ch> typename boost::enable_if< detail::is_character<Ch>, std::basic_string<Ch> >::type get(const path_type &path, const Ch *default_value) const; /** Shorthand for: * @code * if(optional\<self_type&\> node = get_child_optional(path)) * return node->get_value_optional(tr); * return boost::null; * @endcode * That is, return the value if it exists and can be converted, or nil. */ template<class Type, class Translator> ::boost::optional<Type> get_optional(const path_type &path, Translator tr) const; /** Shorthand for: * @code * if(optional\<const self_type&\> node = get_child_optional(path)) * return node->get_value_optional(); * return boost::null; * @endcode */ template<class Type> ::boost::optional<Type> get_optional(const path_type &path) const; /** Set the value of the node at the given path to the supplied value, * translated to the tree's data type. If the node doesn't exist, it is * created, including all its missing parents. * @return The node that had its value changed. * @throw ptree_bad_data if the conversion fails. */ template<class Type, class Translator> self_type &put(const path_type &path, const Type &value, Translator tr); /** Set the value of the node at the given path to the supplied value, * translated to the tree's data type. If the node doesn't exist, it is * created, including all its missing parents. * @return The node that had its value changed. * @throw ptree_bad_data if the conversion fails. */ template<class Type> self_type &put(const path_type &path, const Type &value); /** If the node identified by the path does not exist, create it, * including all its missing parents. * If the node already exists, add a sibling with the same key. * Set the newly created node's value to the given paremeter, * translated with the supplied translator. * @param path Path to the child. The last fragment must not have an * index. * @param value The value to add. * @param tr The translator to use. * @return The node that was added. * @throw ptree_bad_data if the conversion fails. */ template<class Type, class Translator> self_type &add(const path_type &path, const Type &value, Translator tr); /** If the node identified by the path does not exist, create it, * including all its missing parents. * If the node already exists, add a sibling with the same key. * Set the newly created node's value to the given paremeter, * translated with the supplied translator. * @param path Path to the child. The last fragment must not have an * index. * @param value The value to add. * @return The node that was added. * @throw ptree_bad_data if the conversion fails. */ template<class Type> self_type &add(const path_type &path, const Type &value); private: // Hold the data of this node data_type m_data; // Hold the children - this is a void* because we can't complete the // container type within the class. void* m_children; // Getter tree-walk. Not const-safe! Gets the node the path refers to, // or null. Destroys p's value. self_type* walk_path(path_type& p) const; // Modifer tree-walk. Gets the parent of the node referred to by the // path, creating nodes as necessary. p is the path to the remaining // child. self_type& force_path(path_type& p); // This struct contains typedefs for the concrete types. struct subs; friend struct subs; friend class iterator; friend class const_iterator; friend class reverse_iterator; friend class const_reverse_iterator; }; }} #include <liblas/external/property_tree/detail/ptree_implementation.hpp> #endif
#include "PlayerInventoryWnd.h" #include "Single/GameInstance/RPGGameInst.h" #include "Single/PlayerManager/PlayerManager.h" #include "Actor/Controller/PlayerController/GamePlayerController/GamePlayerController.h" #include "Actor/Character/PlayerCharacter/PlayerCharacter.h" #include "Widget/BaseSlot/ItemSlot/PlayerInventoryItemSlot/PlayerInventoryItemSlot.h" #include "Widget/WidgetControllerWidget/WidgetControllerWidget.h" #include "Component/ZoomableSpringArm/ZoomableSpringArmComponent.h" #include "Components/GridPanel.h" #include "Components/GridSlot.h" #include "Components/TextBlock.h" UPlayerInventoryWnd::UPlayerInventoryWnd(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { static ConstructorHelpers::FClassFinder<UPlayerInventoryItemSlot> BP_PLAYER_INVENTORY_ITEM_SLOT( TEXT("WidgetBlueprint'/Game/Blueprints/Widget/Slot/BP_PlayerInventoryItemSlot.BP_PlayerInventoryItemSlot_C'")); if (BP_PLAYER_INVENTORY_ITEM_SLOT.Succeeded()) BP_PlayerInventoryItemSlot = BP_PLAYER_INVENTORY_ITEM_SLOT.Class; } void UPlayerInventoryWnd::NativeConstruct() { Super::NativeConstruct(); WndSize = FVector2D(460.0f, 700.0f); InitializeInventoryWnd(); // 소지금 갱신 UpdateSilver(); for (auto itemSlot : ItemSlots) { auto info = GetManager(UPlayerManager)->GetPlayerInfo()->InventoryItemInfos[itemSlot->GetItemSlotIndex()]; //LOG(TEXT("[%d] itemcode = %s || isEmpty = %d"), // itemSlot->GetItemSlotIndex(), // *info.ItemCode.ToString(), info.IsEmpty()); } } void UPlayerInventoryWnd::InitializeInventoryWnd() { #pragma region Create Inventory Slots // 플레이어 캐릭터 정보를 얻습니다. auto playerInfo = GetManager(UPlayerManager)->GetPlayerInfo(); // 인벤토리 슬롯 개수를 얻습니다. int32 inventorySlotCount = playerInfo->InventorySlotCount; const int32 maxColumnCount = 6; int32 currentColumnCount = 0; // 인벤토리 슬롯들을 생성합니다. for (int32 i = 0; i < inventorySlotCount; ++i) { // 인벤토리 슬롯을 생성합니다. auto newItemSlot = CreateItemSlot(); // 슬롯 초기화 newItemSlot->InitializeItemSlot( ESlotType::ST_InventorySlot, playerInfo->InventoryItemInfos[i].ItemCode, i); // 생성한 슬롯을 정렬합니다. UWidgetControllerWidget::SortGridPanelElem( newItemSlot, maxColumnCount, currentColumnCount); } #pragma endregion #pragma region Lock Camera Zoom // 인벤토리 창이 열리면 카메라 줌을 막습니다. GetManager(UPlayerManager)->GetPlayerCharacter()->GetSpringArm()->SetUseZoom(false); // 인벤토리 창이 닫히면 카메라 줌을 사용할수 있도록 합니다. OnWndClosedEvent.AddLambda([this](UClosableWnd* closableWnd) { GetManager(UPlayerManager)->GetPlayerCharacter()->GetSpringArm()->SetUseZoom(true); }); #pragma endregion } UPlayerInventoryItemSlot* UPlayerInventoryWnd::CreateItemSlot() { // 인벤토리 슬롯을 생성합니다. auto newItemSlot = CreateWidget<UPlayerInventoryItemSlot>( this, BP_PlayerInventoryItemSlot); ItemSlots.Add(newItemSlot); // GridPanel_ItemSlots 의 자식 위젯으로 추가합니다. GridPanel_ItemSlots->AddChild(newItemSlot); // 생성한 인벤토리 슬롯을 반환합니다. return newItemSlot; } void UPlayerInventoryWnd::UpdateInventoryItemSlots() { FPlayerCharacterInfo* playerInfo = GetManager(UPlayerManager)->GetPlayerInfo(); TArray<FItemSlotInfo>& inventoryIteminfos = playerInfo->InventoryItemInfos; for (int32 i = 0; i < ItemSlots.Num(); ++i) { auto itemSlot = ItemSlots[i]; itemSlot->SetItemInfo(inventoryIteminfos[i].ItemCode); itemSlot->UpdateInventoryItemSlot(); itemSlot->InitializeItemSlot( ESlotType::ST_InventorySlot, playerInfo->InventoryItemInfos[i].ItemCode, i); } } void UPlayerInventoryWnd::UpdateSilver() { FText silverToText = FText::FromString(FString::FromInt(GetManager(UPlayerManager)->GetPlayerInfo()->Silver)); Text_Silver->SetText(silverToText); }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> using namespace std; void printChars(int n, char kitu) { for (int i = 0; i < n; i++) { printf("%C", kitu); } } int main() { int a, b; std:ifstream infile; infile.open("labiec11.inp"); infile >> a; infile >> b; if ((a > 2) && (b > 2)) { // In hinh chu nhat dac /*for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { printf("%C%", '*'); } printf("\n"); }*/ // In hinh chu nhat rong printChars(a, '*'); printf("\n"); for (int i = 0; i < b - 2; i++) { printf("%C", '*'); printChars((a - 2 ), ' '); printf("%C", '*'); printf("\n"); } printChars(a, '*'); printf("\n"); } getchar(); return 0; }
#include <iostream> using namespace std; using ll = long long; const ll INF = 1LL << 50; int main() { int N, M; cin >> N >> M; ll asum[N + 1], bsum[M + 1]; asum[0] = bsum[0] = 0; for (int i = 0; i < N; ++i) { ll a; cin >> a; asum[i + 1] = asum[i] + a; } for (int j = 0; j < M; ++j) { ll b; cin >> b; bsum[j + 1] = bsum[j] + b; } ll amin[N + 1], bmin[M + 1]; fill(amin, amin + N + 1, INF); fill(bmin, bmin + M + 1, INF); for (int l = 0; l <= N; ++l) { for (int r = l + 1; r <= N; ++r) { amin[r - l] = min(amin[r - l], asum[r] - asum[l]); } } for (int l = 0; l <= M; ++l) { for (int r = l + 1; r <= M; ++r) { bmin[r - l] = min(bmin[r - l], bsum[r] - bsum[l]); } } ll x; cin >> x; int ans = 0; for (int w = 1; w <= N; ++w) { for (int h = 1; h <= M; ++h) { if (amin[w] * bmin[h] <= x) { ans = max(ans, w * h); } } } cout << ans << endl; return 0; }
// // Created by zhou.lu on 2021/9/2. // #ifndef XPHONEPLAYER_IRESAMPLE_H #define XPHONEPLAYER_IRESAMPLE_H #include "IObserver.h" #include "XParameter.h" class IResample : public IObserver { public: virtual bool Open(XParameter in, XParameter out = XParameter()) = 0; virtual XData Resample(XData indata) = 0; virtual void Close() = 0; virtual void Update(XData data); int outChannels = 2; int outFormat = 1; }; #endif //XPHONEPLAYER_IRESAMPLE_H
// Sharna Hossain // CSC 111 // Lab 6 | grades_logical_operator.cpp #include <iostream> using namespace std; int main() { int grade; string letter_grade; cout << "Enter a grade: "; cin >> grade; if (grade >= 60 && grade <= 62) { letter_grade = "D-"; } else if (grade >= 63 && grade <= 66) { letter_grade = "D"; } else if (grade >= 67 && grade <= 69) { letter_grade = "D+"; } else if (grade >= 70 && grade <= 72) { letter_grade = "C-"; } else if (grade >= 73 && grade <= 76) { letter_grade = "C"; } else if (grade >= 77 && grade <= 79) { letter_grade = "C+"; } else if (grade >= 80 && grade <= 82) { letter_grade = "B-"; } else if (grade >= 83 && grade <= 86) { letter_grade = "B"; } else if (grade >= 87 && grade <= 89) { letter_grade = "B+"; } else if (grade >= 90 && grade <= 92) { letter_grade = "A-"; } else if (grade >= 93) { letter_grade = "A"; } else { letter_grade = "F"; } cout << "Your grade is " << letter_grade << endl; return 0; }
/* ** EPITECH PROJECT, 2018 ** PSU_zappy_2017 ** File description: ** Select.cpp */ #include "Select.hpp" void Select::addFd(int fd) noexcept { _fds.push_back(fd); } void Select::select(int timeOut) { fillFds(); int nfds = getNfds(); struct timeval tv = { timeOut, 0 }; if (::select(nfds, &_rFd, &_wFd, &_eFd, &tv) < 0) throw ExceptSelect("select: " + std::string(strerror(errno))); } int Select::getNfds(void) const noexcept { int nfds = -1; for (int fd : _fds) { nfds = std::max(nfds, fd); } return nfds + 1; } void Select::fillFds(void) noexcept { FD_ZERO(&_rFd); FD_ZERO(&_wFd); FD_ZERO(&_eFd); for (int fd : _fds) { FD_SET(fd, &_rFd); FD_SET(fd, &_wFd); FD_SET(fd, &_eFd); } } bool Select::canRead(int fd) noexcept { return FD_ISSET(fd, &_rFd); } bool Select::canWrite(int fd) noexcept { return FD_ISSET(fd, &_wFd); } bool Select::canError(int fd) noexcept { return FD_ISSET(fd, &_eFd); }
#include <stdio.h> #include <algorithm> #include <iostream> using namespace std; #define maxs 100000000 using namespace std; bool prime[maxs + 1]; int ret[maxs + 1]; int calc(int x, int y) { for(int i = 1; i <= 100; i++) { int t = i, q = 1; while(t % y == 0) t /= y, q++; x -= q; if(x <= 0) return i; } return -1; } int main() { for(int i = 2; i <= maxs; i++) prime[i] = true; for(int i = 2; i * i <= maxs; i++) { if(prime[i]) { for(int j = i + i; j <= maxs; j += i) { prime[j] = false; } } } for(int i = 2; i <= maxs; i++) { if(prime[i]) { for(int j = i; j <= maxs; j += i) { int r = 0, q = j; while(q % i == 0) q /= i, r++; int t = i * calc(r, i); ret[j] = max(ret[j], t); } } } long long res = 0; for(int i = 2; i <= maxs; i++) { res += ret[i]; } cout<<res<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @file * @author Owner: Karianne Ekern (karie) * @author Co-owner: Espen Sand (espen) * */ #include "core/pch.h" #include "adjunct/quick/hotlist/hotlistparser.h" #include "adjunct/m2/src/util/qp.h" #include "adjunct/quick/hotlist/hotlistfileio.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick/managers/DesktopBookmarkManager.h" #include "adjunct/quick/models/BookmarkModel.h" #include "adjunct/quick/models/DesktopBookmark.h" #include "adjunct/quick/models/Bookmark.h" #include "modules/locale/oplanguagemanager.h" #include "modules/logdoc/htm_ldoc.h" #include "modules/util/htmlify.h" #include "modules/util/opfile/unistream.h" #ifdef PREFS_CAP_GENERATE_CLIENTGUID #include "modules/prefs/prefsmanager/collections/pc_network.h" #endif // PREFS_CAP_GENERATE_CLIENTGUID #include "adjunct/quick/Application.h" #include "modules/sqlite/sqlite3.h" #ifndef WIN_CE # include <errno.h> #endif //#define MEASURE_LOADTIME #if defined(MEASURE_LOADTIME) #include <sys/timeb.h> #endif // Defined in modules/doc/logtree/htm_elm.cpp int ReplaceEscapes(uni_char* txt, BOOL require_termination, BOOL remove_tabs, BOOL treat_nbsp_as_space); static const uni_char newline_comma_replacement[3]={2,2,0}; HotlistParser::HotlistParser() : m_current_item_valid(TRUE) , m_current_node(NULL) { } HotlistParser::~HotlistParser() { } // If more bookmark formats are added to DataFormat enum, they MUST be added here too. BOOL HotlistParser::IsBookmarkFormat(int format) { return (format == HotlistModel::OperaBookmark || format == HotlistModel::NetscapeBookmark || format == HotlistModel::ExplorerBookmark || format == HotlistModel::KDE1Bookmark || format == HotlistModel::KonquerorBookmark); } /******************************************************************************* ** ** ParseHeader ** ** Checks if the file is syncable or not ** *******************************************************************************/ OP_STATUS HotlistParser::ParseHeader(HotlistFileReader &reader, HotlistModel &model, BOOL is_import) { int line_length; uni_char *line = reader.Readline(line_length); while (!line) { line = reader.Readline(line_length); } OpStringC hline(line); if (hline.FindI(UNI_L("Hotlist version 2.0")) == KNotFound) return OpStatus::ERR; line = reader.Readline(line_length); // Find next line while (!line) { line = reader.Readline(line_length); } // Should be Options OpStringC sline(line); if (sline.FindI(UNI_L("Options:"))!=KNotFound) { if (sline.FindI(UNI_L("sync=NO")) != KNotFound) { model.SetModelIsSynced(FALSE); } } else { return OpStatus::ERR; } return OpStatus::OK; } OP_STATUS HotlistParser::Parse(const OpStringC &filename, HotlistModel &model, int parent_index, int format, BOOL is_import, BOOL import_into_root_folder) { if ( (model.GetModelType() == HotlistModel::BookmarkRoot && !IsBookmarkFormat(format)) || (model.GetModelType() == HotlistModel::NoteRoot && format != HotlistModel::OperaNote) || (model.GetModelType() == HotlistModel::ContactRoot && format != HotlistModel::OperaContact) || (model.GetModelType() == HotlistModel::UniteServicesRoot && format != HotlistModel::OperaGadget) ) { // Don't import contacts, notes, gadgets into bookmarks model return OpStatus::ERR; } if (parent_index != -1) { if (!model.IsFolderAtIndex(parent_index)) parent_index = -1; HotlistModelItem* hmi = model.GetItemByIndex(parent_index); if (hmi && hmi->GetIsInsideTrashFolder()) parent_index = -1; } model.SetParentIndex(parent_index); // Cleanup from any earlier parsed adr files ResetCurrentNode(); GenericTreeModel::ModelLock lock(&model); if (format == HotlistModel::OperaBookmark ) { return g_desktop_bookmark_manager->ImportAdrBookmark(filename.CStr()); } else if( format == HotlistModel::OperaContact || format == HotlistModel::OperaNote || format == HotlistModel::OperaGadget) { HotlistFileReader reader; if (!reader.Init(filename, HotlistFileIO::UTF8)) return OpStatus::OK; /* if (ParseHeader(reader, model, is_import)) == OpStatus::ERR) return OpStatus::ERR; */ ParseHeader(reader, model, is_import); return Parse(reader, model, is_import); } else if (format == HotlistModel::NetscapeBookmark) { if (FileIsPlacesSqlite(filename)) return ImportNetscapeSqlite(filename, !import_into_root_folder); return ImportNetscapeHTML(filename, !import_into_root_folder); } else if (format == HotlistModel::ExplorerBookmark) { return ImportExplorerFavorites(filename, !import_into_root_folder); } else if (format == HotlistModel::KDE1Bookmark) { return ImportKDE1Bookmarks(filename); } else if (format == HotlistModel::KonquerorBookmark) { return ImportKonquerorBookmarks(filename); } return OpStatus::ERR_NOT_SUPPORTED; } void HotlistParser::AddItem(HotlistModelItem *item, HotlistModel &_model, BOOL is_import) { OP_ASSERT(_model.GetModelType() != HotlistModel::BookmarkRoot); if (_model.GetModelType() == HotlistModel::BookmarkRoot) return; HotlistGenericModel &model = static_cast<HotlistGenericModel&>(_model); if (item && !item->IsInModel()) { // in two cases, the hotlist model might contain invalid entries (ie referencing an invalid gadget) // * the gadget ID stored is wrong // * the path to the widget, stored in profile/widgets/widgets.dat is wrong or in an unsupported format // these entries are of no use, so we don't want to add those if (item->IsUniteService()) { if (static_cast<GadgetModelItem*>(item)->GetOpGadget() == NULL) { OP_ASSERT(!"Invalid gadget entry!"); OP_DELETE(item); item = NULL; } } if (item) { // Don't allow duplicate items on import HotlistModelItem* added_item = model.AddItem(item, /* allow_dups = */!is_import, /*parsed_item=*/TRUE); if (!added_item) OP_DELETE(item); } } } HotlistModelItem *HotlistParser::AddAndCreateNew(HotlistModelItem *item, HotlistModel &model, BOOL is_import, OpTypedObject::Type new_type, OP_STATUS &type_status) { OP_ASSERT(model.GetModelType() != HotlistModel::BookmarkRoot); AddItem(item, static_cast<HotlistGenericModel&>(model), is_import); item = static_cast<HotlistGenericModel&>(model).CreateItem(new_type, type_status, TRUE); SetCurrentNode(item); return item; } OP_STATUS HotlistParser::Parse(HotlistFileReader &reader, HotlistModel &model, BOOL is_import) { int line_length, offset; BOOL isFolder = FALSE; BOOL isContact = FALSE; BOOL onLinkBar = FALSE; // TRUE when parent is a link folder (pre7 support) #if defined(MEASURE_LOADTIME) struct timeb start; ftime(&start); #endif m_current_item_valid = TRUE; HotlistModelItem* item = GetCurrentNode(); if (item && item->GetType() == OpTypedObject::FOLDER_TYPE) isFolder = TRUE; // OpString current_line; OP_STATUS type_status; while (1) { uni_char *line = reader.Readline(line_length); if (!line) { break; } // Skip blank lines if (!line[0]) { continue; } // If the current item does not have a supported type // skip the rest of the item, continue until new item reached if (!m_current_item_valid) { if (!IsKey(line, line_length, "#", 1)) { // go to next line continue; } else { m_current_item_valid = TRUE; } } /** SECTIONS **/ offset = IsKey(line, line_length, KEYWORD_URLSECTION, ARRAY_SIZE(KEYWORD_URLSECTION)-1); if (offset != -1) { OP_ASSERT(FALSE); continue; } offset = IsKey(line, line_length, KEYWORD_NOTESECTION, ARRAY_SIZE(KEYWORD_NOTESECTION)-1); if (offset != -1) { item = AddAndCreateNew(item, model, is_import, OpTypedObject::NOTE_TYPE, type_status); if (!item) { if (type_status == OpStatus::ERR_NOT_SUPPORTED) { m_current_item_valid = FALSE; continue; } else return type_status; } if (onLinkBar) item->SetOnPersonalbar(TRUE); isContact = FALSE; isFolder = FALSE; continue; } offset = IsKey(line, line_length, KEYWORD_SEPERATORSECTION, ARRAY_SIZE(KEYWORD_SEPERATORSECTION)-1); if (offset != -1) { item = AddAndCreateNew(item, model, is_import, OpTypedObject::SEPARATOR_TYPE, type_status); if (!item) { if (type_status == OpStatus::ERR_NOT_SUPPORTED) { m_current_item_valid = FALSE; continue; } else return type_status; } isContact = FALSE; isFolder = FALSE; continue; } #ifdef WEBSERVER_SUPPORT offset = IsKey(line, line_length, KEYWORD_UNITESECTION, ARRAY_SIZE(KEYWORD_UNITESECTION)-1); if (offset != -1) { item = AddAndCreateNew(item, model, is_import, OpTypedObject::UNITE_SERVICE_TYPE, type_status); if (!item) { if (type_status == OpStatus::ERR_NOT_SUPPORTED) { m_current_item_valid = FALSE; continue; } else return type_status; } if (onLinkBar) item->SetOnPersonalbar(TRUE); isContact = FALSE; isFolder = FALSE; continue; } #endif // WEBSERVER_SUPPORT offset = IsKey(line, line_length, KEYWORD_CONTACTSECTION, ARRAY_SIZE(KEYWORD_CONTACTSECTION)-1); if (offset != -1) { item = AddAndCreateNew(item, model, is_import, OpTypedObject::CONTACT_TYPE, type_status); if (!item) { if (type_status == OpStatus::ERR_NOT_SUPPORTED) { m_current_item_valid = FALSE; continue; } else return type_status; } if (onLinkBar) item->SetOnPersonalbar(TRUE); isContact = TRUE; isFolder = FALSE; continue; } offset = IsKey(line, line_length, KEYWORD_GROUPSECTION, ARRAY_SIZE(KEYWORD_GROUPSECTION)-1); if (offset != -1) { OP_STATUS rc; item = AddAndCreateNew(item, model, is_import, OpTypedObject::GROUP_TYPE, rc); if (!item) return OpStatus::ERR; if (onLinkBar) item->SetOnPersonalbar(TRUE); isContact = FALSE; isFolder = FALSE; continue; } offset = IsKey(line, line_length, KEYWORD_FOLDERSECTION, ARRAY_SIZE(KEYWORD_FOLDERSECTION)-1); if (offset != -1) { OP_STATUS rc; item = AddAndCreateNew(item, model, is_import, OpTypedObject::FOLDER_TYPE, rc); if (!item) return OpStatus::ERR; INT32 parentIndex = model.GetParentIndex(); if (onLinkBar) item->SetOnPersonalbar(TRUE); RETURN_IF_ERROR(Parse(reader, model, is_import)); model.SetParentIndex(parentIndex); item = 0; isContact = TRUE; isFolder = TRUE; continue; } offset = IsKey(line, line_length, KEYWORD_ENDOFFOLDER, ARRAY_SIZE(KEYWORD_ENDOFFOLDER)-1); if (offset != -1) { AddItem(item, model, is_import); return OpStatus::OK; } /** KEY - VALUES **/ offset = IsKey(line, line_length, KEYWORD_NAME, ARRAY_SIZE(KEYWORD_NAME)-1); if (offset != -1) { if (item) { if (item->IsNote() || item->IsFolder() && model.GetModelType() == HotlistModel::NoteRoot) { OpString tmp; ConvertToNewline(tmp, &line[5]); item->SetName(tmp.CStr()); } else { item->SetName(&line[5]); } } continue; } offset = IsKey(line, line_length, KEYWORD_ID, ARRAY_SIZE(KEYWORD_ID)-1); if (offset != -1) { if (item && !is_import) { //item->SetID(uni_atoi(&line[3])); } continue; } // if (!is_import) // { offset = IsKey(line, line_length, KEYWORD_UNIQUEID, ARRAY_SIZE(KEYWORD_UNIQUEID)-1); if (offset != -1) { if (item) { // Make upper for (UINT32 i = 0; i < uni_strlen(&line[9]); i++) { line[9+i] = uni_toupper(line[9+i]); } item->SetUniqueGUID(&line[9], model.GetModelType()); } continue; } // } offset = IsKey(line, line_length, KEYWORD_CREATED, ARRAY_SIZE(KEYWORD_CREATED)-1); if (offset != -1) { if (item) item->SetCreated(uni_atoi(&line[8])); continue; } offset = IsKey(line, line_length, KEYWORD_VISITED, ARRAY_SIZE(KEYWORD_VISITED)-1); if (offset != -1) { if (item) item->SetVisited(uni_atoi(&line[8])); continue; } offset = IsKey(line, line_length, KEYWORD_URL, ARRAY_SIZE(KEYWORD_URL)-1); if (offset != -1) { if (item) item->SetUrl(&line[4]); continue; } offset = IsKey(line, line_length, KEYWORD_DESCRIPTION, ARRAY_SIZE(KEYWORD_DESCRIPTION)-1); if (offset != -1) { if (item) { OpString tmp; ConvertToNewline(tmp, &line[12]); item->SetDescription(tmp.CStr()); } continue; } offset = IsKey(line, line_length, KEYWORD_SHORTNAME, ARRAY_SIZE(KEYWORD_SHORTNAME)-1); if (offset != -1) { if (item) { OpStringC s(&line[11]); if (!is_import || !g_hotlist_manager->HasNickname(s,item)) item->SetShortName(&line[11]); } continue; } offset = IsKey(line, line_length, KEYWORD_PERSONALBAR_POS, ARRAY_SIZE(KEYWORD_PERSONALBAR_POS)-1); if (offset != -1) { if (item && !is_import) item->SetPersonalbarPos(uni_atoi(&line[16])); continue; } offset = IsKey(line, line_length, KEYWORD_PANEL_POS, ARRAY_SIZE(KEYWORD_PANEL_POS)-1); if (offset != -1) { if (item && !is_import) { item->SetPanelPos(uni_atoi(&line[10])); } continue; } offset = IsKey(line, line_length, KEYWORD_ON_PERSONALBAR, ARRAY_SIZE(KEYWORD_ON_PERSONALBAR)-1); if (offset != -1) { if (item && !is_import) item->SetOnPersonalbar(IsYes(&line[15])); continue; } offset = IsKey(line, line_length, KEYWORD_IN_PANEL, ARRAY_SIZE(KEYWORD_IN_PANEL)-1); if (offset != -1) { if (item && !is_import) { if (item->GetPanelPos() == -1 && IsYes(&line[9])) { item->SetPanelPos(0); //item->SetInPanel(IsYes(&line[9])); } } continue; } offset = IsKey(line, line_length, KEYWORD_SMALL_SCREEN, ARRAY_SIZE(KEYWORD_SMALL_SCREEN)-1); if (offset != -1) { if (item) item->SetSmallScreen(IsYes(&line[13])); continue; } offset = IsKey(line, line_length, KEYWORD_ACTIVE, ARRAY_SIZE(KEYWORD_ACTIVE)-1); if (offset != -1) { if (item && IsYes(&line[7]) && !is_import) { model.SetActiveItemId(item->GetID(), FALSE); } continue; } offset = IsKey(line, line_length, KEYWORD_MEMBER, ARRAY_SIZE(KEYWORD_MEMBER)-1); if (offset != -1) { if (item) { item->SetGroupList(&line[8]); // TODO JOHAN: if (is_import) { correct_group_ids(); } } continue; } #ifdef WEBSERVER_SUPPORT offset = IsKey(line, line_length, KEYWORD_ROOT, ARRAY_SIZE(KEYWORD_ROOT)-1); if (offset != -1) { if (item && item->IsUniteService() && IsYes(&line[offset]) && !((HotlistGenericModel&)model).GetRootService()) { static_cast<UniteServiceModelItem*>(item)->SetIsRootService(); //model.SetRootService( static_cast<UniteServiceModelItem*>(item)); } continue; } offset = IsKey(line, line_length, KEYWORD_NEEDSCONFIG, ARRAY_SIZE(KEYWORD_NEEDSCONFIG)-1); if (offset != -1) { if (item && item->IsUniteService() && IsYes(&line[offset])) static_cast<UniteServiceModelItem*>(item)->SetNeedsConfiguration(TRUE); continue; } offset = IsKey(line, line_length, KEYWORD_RUNNING, ARRAY_SIZE(KEYWORD_RUNNING)-1); if (offset != -1) { if (item && item->IsUniteService()) { UniteServiceModelItem * unite_item = static_cast<UniteServiceModelItem*>(item); if (!unite_item->NeedsConfiguration() && IsYes(&line[offset])) { unite_item->SetAddToAutoStart(TRUE); } } continue; } #endif //gadget properties reading offset = IsKey(line, line_length, KEYWORD_IDENTIFIER, ARRAY_SIZE(KEYWORD_IDENTIFIER)-1); if (offset != -1) { if (item && !is_import) { #ifdef GADGET_SUPPORT item->SetGadgetIdentifier(&line[offset]); #endif // GADGET_SUPPORT } continue; } //gadget type of installation offset = IsKey(line, line_length, KEYWORD_CLEAN_UNINSTALL, ARRAY_SIZE(KEYWORD_CLEAN_UNINSTALL)-1); if (offset != -1) { if (item && !is_import) { #ifdef GADGET_SUPPORT item->SetGadgetCleanUninstall(IsYes(&line[offset])); #endif // GADGET_SUPPORT } continue; } //folder property reading if (isFolder) { offset = IsKey(line, line_length, KEYWORD_EXPANDED, ARRAY_SIZE(KEYWORD_EXPANDED)-1); if (offset != -1) { if (item) item->SetIsExpandedFolder(IsYes(&line[9])); continue; } if (model.GetModelType() == HotlistModel::BookmarkRoot) { offset = IsKey(line, line_length, KEYWORD_TARGET, ARRAY_SIZE(KEYWORD_TARGET)-1); if (offset != -1) { if (item) item->SetTarget(&line[7]); continue; } offset = IsKey(line, line_length, KEYWORD_MOVE_IS_COPY, ARRAY_SIZE(KEYWORD_MOVE_IS_COPY)-1); if (offset != -1) { if (item) item->SetHasMoveIsCopy(IsYes(&line[13])); continue; } offset = IsKey(line, line_length, KEYWORD_DELETABLE, ARRAY_SIZE(KEYWORD_DELETABLE)-1); if (offset != -1) { if (item) item->SetIsDeletable(!IsNo(&line[10])); continue; } offset = IsKey(line, line_length, KEYWORD_SUBFOLDER_ALLOWED, ARRAY_SIZE(KEYWORD_SUBFOLDER_ALLOWED)-1); if (offset != -1) { if (item) item->SetSubfoldersAllowed(!IsNo(&line[18])); continue; } offset = IsKey(line, line_length, KEYWORD_SEPARATOR_ALLOWED, ARRAY_SIZE(KEYWORD_SEPARATOR_ALLOWED)-1); if (offset != -1) { if (item) item->SetSeparatorsAllowed(!IsNo(&line[18])); continue; } offset = IsKey(line, line_length, KEYWORD_MAX_ITEMS, ARRAY_SIZE(KEYWORD_MAX_ITEMS)-1); if (offset != -1) { if (item) item->SetMaxItems((uni_atoi(&line[10]))); continue; } } offset = IsKey(line, line_length, KEYWORD_TRASH_FOLDER, ARRAY_SIZE(KEYWORD_TRASH_FOLDER)-1); if (offset != -1) { /* If import; add all items inside trash folder to real trash folder */ if (item) { if (is_import) { HotlistModelItem* trash_folder = model.GetTrashFolder(); if (trash_folder) { OP_ASSERT(item->IsFolder()); model.SetParentIndex(trash_folder->GetIndex()); // reset m_parent_index OP_ASSERT(item == model.GetCurrentNode()); // GetTrashFolder will create trash folder if it's not already there. ResetCurrentNode(); OP_DELETE(item); item = NULL; } } else { BOOL is_trash = IsYes(&line[13]); item->SetIsTrashFolder(is_trash); if (is_trash) { model.SetTrashfolderId(item->GetID()); } } } continue; } #if defined(SUPPORT_IMPORT_LINKBAR_TAG) offset = IsKey(line, line_length, KEYWORD_LINKBAR_FOLDER, ARRAY_SIZE(KEYWORD_LINKBAR_FOLDER)-1); if (offset != -1) { if (item && !is_import) { item->SetIsLinkBarFolder(IsYes(&line[15])); onLinkBar = TRUE; } continue; } offset = IsKey(line, line_length, KEYWORD_LINKBAR_STOP, ARRAY_SIZE(KEYWORD_LINKBAR_STOP)-1); if (offset != -1) { if (item && !is_import) { onLinkBar = FALSE; } continue; } #endif } if (isContact) { offset = IsKey(line, line_length, KEYWORD_MAIL, ARRAY_SIZE(KEYWORD_MAIL)-1); if (offset != -1) { if (item) { // Pre 7 versions used 0x020x02 as a separator in the file OpString tmp; ConvertToComma(tmp, &line[5]); item->SetMail(tmp.CStr()); } continue; } offset = IsKey(line, line_length, KEYWORD_PHONE, ARRAY_SIZE(KEYWORD_PHONE)-1); if (offset != -1) { if (item) item->SetPhone(&line[6]); continue; } offset = IsKey(line, line_length, KEYWORD_FAX, ARRAY_SIZE(KEYWORD_FAX)-1); if (offset != -1) { if (item) item->SetFax(&line[4]); continue; } offset = IsKey(line, line_length, KEYWORD_POSTALADDRESS, ARRAY_SIZE(KEYWORD_POSTALADDRESS)-1); if (offset != -1) { if (item) { OpString tmp; ConvertToNewline(tmp, &line[14]); item->SetPostalAddress(tmp.CStr()); } continue; } offset = IsKey(line, line_length, KEYWORD_PICTUREURL, ARRAY_SIZE(KEYWORD_PICTUREURL)-1); if (offset != -1) { if (item) item->SetPictureUrl(&line[11]); continue; } offset = IsKey(line, line_length, KEYWORD_CONAX, ARRAY_SIZE(KEYWORD_CONAX)-1); if (offset != -1) { if (item) item->SetConaxNumber(&line[22]); continue; } offset = IsKey(line, line_length, KEYWORD_ICON, ARRAY_SIZE(KEYWORD_ICON)-1); if (offset != -1) { if (item) { OpString8 icon_name; icon_name.Set(&line[5]); item->SetIconName(icon_name.CStr()); } continue; } if (line[0] == 'I' && line[1] == 'M') { offset = IsKey(line, line_length, KEYWORD_IMADDRESS, ARRAY_SIZE(KEYWORD_IMADDRESS)-1); if (offset != -1) { if (item) item->SetImAddress(&line[10]); continue; } offset = IsKey(line, line_length, KEYWORD_IMPROTOCOL, ARRAY_SIZE(KEYWORD_IMPROTOCOL)-1); if (offset != -1) { if (item) item->SetImProtocol(&line[11]); continue; } offset = IsKey(line, line_length, KEYWORD_IMSTATUS, ARRAY_SIZE(KEYWORD_IMSTATUS)-1); if (offset != -1) { if (item) item->SetImStatus(&line[9]); continue; } offset = IsKey(line, line_length, KEYWORD_IMVISIBILITY, ARRAY_SIZE(KEYWORD_IMVISIBILITY)-1); if (offset != -1) { if (item) item->SetImVisibility(&line[13]); continue; } offset = IsKey(line, line_length, KEYWORD_IMXPOSITION, ARRAY_SIZE(KEYWORD_IMXPOSITION)-1); if (offset != -1) { if (item) item->SetImXPosition(&line[12]); continue; } offset = IsKey(line, line_length, KEYWORD_IMYPOSITION, ARRAY_SIZE(KEYWORD_IMYPOSITION)-1); if (offset != -1) { if (item) item->SetImYPosition(&line[12]); continue; } offset = IsKey(line, line_length, KEYWORD_IMWIDTH, ARRAY_SIZE(KEYWORD_IMWIDTH)-1); if (offset != -1) { if (item) item->SetImWidth(&line[8]); continue; } offset = IsKey(line, line_length, KEYWORD_IMHEIGHT, ARRAY_SIZE(KEYWORD_IMHEIGHT)-1); if (offset != -1) { if (item) item->SetImHeight(&line[9]); continue; } offset = IsKey(line, line_length, KEYWORD_IMMAXIMIZED, ARRAY_SIZE(KEYWORD_IMMAXIMIZED)-1); if (offset != -1) { if (item) item->SetImMaximized(&line[12]); continue; } } offset = IsKey(line, line_length, KEYWORD_M2INDEX, ARRAY_SIZE(KEYWORD_M2INDEX)-1); if (offset != -1) { if (item && !is_import) item->SetM2IndexId(uni_atoi(&line[10])); continue; } } #if defined(SUPPORT_UNKNOWN_TAGS) // If line did not contain any key, we end up here. if (item && uni_strlen(line) > 0) { OpString formattedTag; formattedTag.Set("\t"); formattedTag.Append(line); formattedTag.Append("\n"); item->SetUnknownTag(formattedTag.CStr()); } #endif } // end while #if defined(MEASURE_LOADTIME) struct timeb stop; ftime(&stop); int s1 = start.time * 1000 + start.millitm; int s2 = stop.time * 1000 + stop.millitm; printf("bookmark parsing: duration=%d [ms], nodes=%d\n", s2 - s1, model.GetItemCount()); #endif AddItem(item, model, is_import); return OpStatus::OK; } #if 0 OP_STATUS HotlistParser::MergeFromFile(const OpStringC &filename, HotlistModel &existing_model) { HotlistModel work_model(1, TRUE); HotlistParser parser; UINT32 dirty_count = 0; if (OpStatus::IsSuccess(parser.Parse(filename, work_model, -1, HotlistModel::OperaBookmark, TRUE, dirty_count))) { //we now have the merge file in tmp CheckLevelForDuplicates(NULL, NULL, work_model, existing_model); } existing_model.PasteItem(work_model, NULL, INSERT_INTO, 0); existing_model.SetDirty(TRUE); return OpStatus::OK; } #endif // this function needs to be reimplemented if needed due to the refactoring of bookmarks. --shuais //OP_STATUS HotlistParser::CheckLevelForDuplicates(HotlistModelItem *item, HotlistModelItem *parent_item, HotlistModel &_work_model, HotlistModel &_existing_model) //{ // OP_ASSERT(_work_model.GetModelType() != HotlistModel::BookmarkRoot && _existing_model.GetModelType() != HotlistModel::BookmarkRoot); // if(_work_model.GetModelType() == HotlistModel::BookmarkRoot) // return OpStatus::ERR; // // HotlistGenericModel& work_model = static_cast<HotlistGenericModel&>(_work_model); // HotlistGenericModel& existing_model = static_cast<HotlistGenericModel&>(_existing_model); // // // if(item && parent_item) //this is a folder, find the "correpsonding folder" in the models and merge the contents // { // HotlistModelItem* new_child; // HotlistModelItem* existing_child; // // OpINT32Vector newfolder_list; // OpINT32Vector permanentfolder_list; // // INT32 idx = work_model.GetIndexByItem(item); // // work_model.GetIndexList(idx, newfolder_list, FALSE, 1, OpTypedObject::BOOKMARK_TYPE); // existing_model.GetIndexList(existing_model.GetIndexByItem(parent_item), permanentfolder_list, FALSE, 1, OpTypedObject::BOOKMARK_TYPE); // // BOOL found = FALSE; // // UINT32 k; // for (k=0; k<newfolder_list.GetCount(); k++) // { // new_child = work_model.GetItemByIndex(newfolder_list.Get(k)); // // UINT32 n; // for (n=0; n<permanentfolder_list.GetCount(); n++) // { // existing_child = existing_model.GetItemByIndex(permanentfolder_list.Get(n)); // // if(new_child->GetName().Compare(existing_child->GetName()) == 0) // { // found = TRUE; // break; // } // } // // if(!found) // { // // add the item to the existing model at the position of the parent_item and break // BookmarkModel paste_model(TRUE); // INT32 gotidx; // // HotlistModelItem* added = new_child->GetDuplicate(); // if (added) // { // paste_model.AddLastBeforeTrash(-1, added, &gotidx); // // existing_model.PasteItem(paste_model, parent_item, INSERT_INTO, 0); // } // } // found = FALSE; // } // // work_model.DeleteItem(item, FALSE); // item=NULL; // return OpStatus::OK; // } // // for (int i = 0; i<work_model.GetItemCount();) // { // HotlistModelItem *hmi = work_model.GetItemByIndex(i++); // // for (int j = 0; j<existing_model.GetItemCount();) // { // HotlistModelItem *permanent_hmi = existing_model.GetItemByIndex(j++); // { // if(permanent_hmi && hmi && hmi->GetName().Compare(permanent_hmi->GetName()) == 0) //they have the same name // { // if(hmi->IsFolder() && !permanent_hmi->GetIsTrashFolder()) // { // return CheckLevelForDuplicates(hmi, permanent_hmi, work_model, existing_model); // } // work_model.DeleteItem(hmi, FALSE); // i=0; // break; // } // } // } // } // // return OpStatus::OK; //} #if SQLITE_VERSION_NUMBER >= 3007000 #define SQLITE_VERSION_VFS 2 #define SQLITE_VERSION_IO 2 #else #define SQLITE_VERSION_VFS 1 #define SQLITE_VERSION_IO 1 #endif //This entire class has been created for it's fileLock method. //Otherwise, it's bunch of pass-throughs struct SQLite3VFS { sqlite3_vfs copy; sqlite3_vfs* os; sqlite3_io_methods methods; char name[200]; struct SQLite3File: sqlite3_file { sqlite3_file* orig; }; SQLite3VFS() { unsigned long secs, millisecs; g_op_time_info->GetWallClock(secs, millisecs); op_snprintf(name, 200, "op_vfs_%lu_%lu", secs, millisecs); memset(&copy, 0, sizeof(copy)); os = sqlite3_vfs_find(NULL); if (!os) return; memcpy(&copy, os, sizeof(copy)); copy.iVersion = SQLITE_VERSION_VFS; copy.szOsFile = sizeof(SQLite3File); copy.zName = name; copy.pAppData = this; copy.xOpen = vfsOpen; copy.xDelete = vfsDelete; copy.xAccess = vfsAccess; copy.xFullPathname = vfsFullPathname; copy.xDlOpen = vfsDlOpen; copy.xDlError = vfsDlError; copy.xDlSym = vfsDlSym; copy.xDlClose = vfsDlClose; copy.xRandomness = vfsRandomness; copy.xSleep = vfsSleep; copy.xCurrentTime = vfsCurrentTime; copy.xGetLastError = vfsGetLastError; #if SQLITE_VERSION_NUMBER >= 3007000 copy.xCurrentTimeInt64 = vfsCurrentTimeInt64; #endif sqlite3_vfs_register(&copy, 0); methods.iVersion = SQLITE_VERSION_IO; methods.xClose = fileClose; methods.xRead = fileRead; methods.xWrite = fileWrite; methods.xTruncate = fileTruncate; methods.xSync = fileSync; methods.xFileSize = fileFileSize; methods.xLock = fileLock; methods.xUnlock = fileUnlock; methods.xCheckReservedLock = fileCheckReservedLock; methods.xFileControl = fileFileControl; methods.xSectorSize = fileSectorSize; methods.xDeviceCharacteristics = fileDeviceCharacteristics; #if SQLITE_VERSION_NUMBER >= 3007000 methods.xShmMap = fileShmMap; methods.xShmLock = fileShmLock; methods.xShmBarrier = fileShmBarrier; methods.xShmUnmap = fileShmUnmap; #endif } ~SQLite3VFS() { sqlite3_vfs_unregister(&copy); } const char* Name() const { return copy.zName; } private: #define OS (((SQLite3VFS*)_this->pAppData)->os) static int vfsOpen(sqlite3_vfs* _this, const char *zName, sqlite3_file* f, int flags, int *pOutFlags) { void * ptr = op_malloc(OS->szOsFile); if (!ptr) return SQLITE_NOMEM; memset(ptr, OS->szOsFile, 0); SQLite3File* file = (SQLite3File*)f; file->pMethods = NULL; file->orig = (sqlite3_file*)ptr; int ret = OS->xOpen(OS, zName, file->orig, flags, pOutFlags); if (ret != SQLITE_OK || file->orig->pMethods == NULL) { op_free(ptr); file->orig = NULL; if (ret == SQLITE_OK) ret = SQLITE_ERROR; return ret; } file->pMethods = &((SQLite3VFS*)_this->pAppData)->methods; return ret; } static int vfsDelete(sqlite3_vfs* _this, const char *zName, int syncDir) { return OS->xDelete(OS, zName, syncDir); } static int vfsAccess(sqlite3_vfs* _this, const char *zName, int flags, int *pResOut) { return OS->xAccess(OS, zName, flags, pResOut); } static int vfsFullPathname(sqlite3_vfs* _this, const char *zName, int nOut, char *zOut) { return OS->xFullPathname(OS, zName, nOut, zOut); } static void *vfsDlOpen(sqlite3_vfs* _this, const char *zFilename) { return OS->xDlOpen(OS, zFilename); } static void vfsDlError(sqlite3_vfs* _this, int nByte, char *zErrMsg) { return OS->xDlError(OS, nByte, zErrMsg); } static void (*vfsDlSym(sqlite3_vfs* _this, void* ptr, const char *zSymbol))(void) { return OS->xDlSym(OS, ptr, zSymbol); } static void vfsDlClose(sqlite3_vfs* _this, void* ptr) { return OS->xDlClose(OS, ptr); } static int vfsRandomness(sqlite3_vfs* _this, int nByte, char *zOut) { return OS->xRandomness(OS, nByte, zOut); } static int vfsSleep(sqlite3_vfs* _this, int microseconds) { return OS->xSleep(OS, microseconds); } static int vfsCurrentTime(sqlite3_vfs* _this, double* out) { return OS->xCurrentTime(OS, out); } static int vfsGetLastError(sqlite3_vfs* _this, int i, char * ptr) { return OS->xGetLastError(OS, i, ptr); } #if SQLITE_VERSION_NUMBER >= 3007000 static int vfsCurrentTimeInt64(sqlite3_vfs* _this, sqlite3_int64* ptr) { return OS->xCurrentTimeInt64(OS, ptr); } #endif #undef OS #define ORIG (((SQLite3File*)file)->orig) #define METHODS (ORIG->pMethods) static int fileClose(sqlite3_file* file) { int ret = METHODS->xClose(ORIG); op_free(ORIG); return ret; } static int fileRead(sqlite3_file* file, void* p, int iAmt, sqlite3_int64 iOfst) { return METHODS->xRead(ORIG, p, iAmt, iOfst); } static int fileWrite(sqlite3_file* file, const void* p, int iAmt, sqlite3_int64 iOfst) { return METHODS->xWrite(ORIG, p, iAmt, iOfst); } static int fileTruncate(sqlite3_file* file, sqlite3_int64 size) { return METHODS->xTruncate(ORIG, size); } static int fileSync(sqlite3_file* file, int flags) { return METHODS->xSync(ORIG, flags); } static int fileFileSize(sqlite3_file* file, sqlite3_int64 *pSize) { return METHODS->xFileSize(ORIG, pSize); } static int fileLock(sqlite3_file* file, int i) { int ret = METHODS->xLock(ORIG, i); if (ret == SQLITE_BUSY) ret = SQLITE_OK; return ret; } static int fileUnlock(sqlite3_file* file, int i) { return METHODS->xUnlock(ORIG, i); } static int fileCheckReservedLock(sqlite3_file* file, int *pResOut) { return METHODS->xCheckReservedLock(ORIG, pResOut); } static int fileFileControl(sqlite3_file* file, int op, void *pArg) { return METHODS->xFileControl(ORIG, op, pArg); } static int fileSectorSize(sqlite3_file* file) { return METHODS->xSectorSize(ORIG); } static int fileDeviceCharacteristics(sqlite3_file* file) { return METHODS->xDeviceCharacteristics(ORIG); } #if SQLITE_VERSION_NUMBER >= 3007000 static int fileShmMap(sqlite3_file* file, int iPg, int pgsz, int i, void volatile** shm) { return METHODS->xShmMap(ORIG, iPg, pgsz, i, shm); } static int fileShmLock(sqlite3_file* file, int offset, int n, int flags) { return METHODS->xShmLock(ORIG, offset, n, flags); } static void fileShmBarrier(sqlite3_file* file) { return METHODS->xShmBarrier(ORIG); } static int fileShmUnmap(sqlite3_file* file, int deleteFlag) { return METHODS->xShmUnmap(ORIG, deleteFlag); } #endif #undef METHODS #undef ORIG }; #define SQLITE3_RETURN_IF_ERROR(expr) \ do { \ int RETURN_IF_ERROR_TMP = expr; \ if (RETURN_IF_ERROR_TMP != SQLITE_OK) \ return RETURN_IF_ERROR_TMP == SQLITE_NOMEM ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR; \ } while (0) class SQLite3Cursor; class SQLite3DB { friend class SQLite3Cursor; sqlite3* db; public: SQLite3DB(): db(NULL) {} ~SQLite3DB() { Close(); } void Close() { if (db) sqlite3_close(db); db = NULL; } OP_STATUS Open(const char* filename_u8, const char* vfsname) { OP_ASSERT(!db); SQLITE3_RETURN_IF_ERROR(sqlite3_open_v2(filename_u8, &db, SQLITE_OPEN_READONLY, vfsname)); return OpStatus::OK; } }; class SQLite3Cursor { sqlite3_stmt* stmt; OP_STATUS last_step_result; public: SQLite3Cursor(): stmt(NULL), last_step_result(0) {} void Close() { if (stmt) sqlite3_finalize(stmt); stmt = NULL; } OP_STATUS Open(const SQLite3DB& db, const char* sql) { OP_ASSERT(!stmt); OP_ASSERT(db.db); SQLITE3_RETURN_IF_ERROR(sqlite3_prepare_v2(db.db, sql, -1, &stmt, NULL)); return OpStatus::OK; } BOOL Step() { OP_ASSERT(stmt); int ret = sqlite3_step(stmt); last_step_result = ret == SQLITE_ROW || ret == SQLITE_OK || ret == SQLITE_DONE ? OpStatus::OK : ret == SQLITE_NOMEM ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR; return ret == SQLITE_ROW; } OP_STATUS StepStatus() const { return last_step_result; } int TupleSize() const { return sqlite3_column_count(stmt); } int Type(int column) const { return sqlite3_column_type(stmt, column); } int GetInt(int column) const { return sqlite3_column_int(stmt, column); } const uni_char* GetRawText(int column) const { return (const uni_char*)sqlite3_column_text16(stmt, column); } int GetRawTextLen(int column) const { return sqlite3_column_bytes16(stmt, column); } const char* GetRawText8(int column) const { return (const char*)sqlite3_column_text(stmt, column); } int GetRawTextLen8(int column) const { return sqlite3_column_bytes(stmt, column); } OP_STATUS GetText(int column, OpString& string) const { const uni_char* text = GetRawText(column); return string.Set(text, GetRawTextLen(column)); } }; /* SQLite seems to be overzealous in opening databases even when * they are opened with SQLITE_OPEN_READONLY. To check that this * seems to be places.sqlite, we'll do little duck typing: * does the database contain needed tables? (If it's not the * SQLite DB, then there will be no schema...) */ BOOL HotlistParser::FileIsPlacesSqlite(const OpStringC& filename) { struct _ { static OP_STATUS isPlacesSqlite(const OpStringC& filename) { SQLite3VFS overwrite; SQLite3DB db; SQLite3Cursor cursor; const int MOZ_TABLES_COUNT = 5; const char* MOZ_TABLES_SQL = "select count() from sqlite_master where type='table' and (" "name = 'moz_bookmarks' or " "name = 'moz_places' or " "name = 'moz_annos' or " "name = 'moz_items_annos' or " "name = 'moz_bookmarks_roots')"; OpString8 path; RETURN_IF_ERROR(path.SetUTF8FromUTF16(filename)); RETURN_IF_ERROR(db.Open(path.CStr(), overwrite.Name())); RETURN_IF_ERROR(cursor.Open(db, MOZ_TABLES_SQL)); RETURN_IF_ERROR(cursor.Step() ? OpStatus::OK : cursor.StepStatus()); if (cursor.TupleSize() != 1 || cursor.Type(0) != SQLITE_INTEGER) return OpStatus::ERR; return cursor.GetInt(0) == MOZ_TABLES_COUNT ? OpStatus::OK : OpStatus::ERR; } }; return OpStatus::IsSuccess(_::isPlacesSqlite(filename)); } /* SELECT moz_bookmarks.id, moz_bookmarks.type, moz_bookmarks.parent, moz_bookmarks.position, moz_bookmarks.title, moz_bookmarks.dateAdded, moz_bookmarks.lastModified, moz_places.last_visit_date, moz_places.url, annotation_1.content as feed, annotation_2.content as site, annotation_3.content as description, ifnull(moz_places.hidden, 0) as hidden FROM moz_bookmarks LEFT JOIN moz_places ON moz_bookmarks.fk = moz_places.id LEFT JOIN (SELECT item_id, content FROM moz_items_annos LEFT JOIN moz_anno_attributes ON moz_items_annos.anno_attribute_id = moz_anno_attributes.id WHERE name = 'livemark/feedURI') AS annotation_1 ON annotation_1.item_id = moz_bookmarks.id LEFT JOIN (SELECT item_id, content FROM moz_items_annos LEFT JOIN moz_anno_attributes ON moz_items_annos.anno_attribute_id = moz_anno_attributes.id WHERE name = 'livemark/siteURI') AS annotation_2 ON annotation_2.item_id = moz_bookmarks.id LEFT JOIN (SELECT item_id, content FROM moz_items_annos LEFT JOIN moz_anno_attributes ON moz_items_annos.anno_attribute_id = moz_anno_attributes.id WHERE name = 'bookmarkProperties/description') AS annotation_3 ON annotation_3.item_id = moz_bookmarks.id ORDER BY parent, position */ #define MOZ_PLACES_ATTRS "moz_bookmarks.id, " \ "moz_bookmarks.type, " \ "moz_bookmarks.parent, " \ "moz_bookmarks.position, " \ "moz_bookmarks.title, " \ "moz_bookmarks.dateAdded, " \ "moz_bookmarks.lastModified, " \ "moz_places.last_visit_date, " \ "moz_places.url, " \ "annotation_1.content as feed, " \ "annotation_2.content as site, " \ "annotation_3.content as description, " \ "ifnull(moz_places.hidden, 0) as hidden" #define MOZ_PLACES_ANNOTATION_VIEW(anno) "select item_id, content from moz_items_annos left join moz_anno_attributes on moz_items_annos.anno_attribute_id = moz_anno_attributes.id where name = '" anno "'" #define MOZ_PLACES_JOIN_PLACES "left join moz_places on moz_bookmarks.fk = moz_places.id" #define MOZ_PLACES_JOIN_ANNOTATION(id, anno) "left join (" MOZ_PLACES_ANNOTATION_VIEW(anno) ") as annotation_" id " on annotation_" id ".item_id = moz_bookmarks.id" #define MOZ_PLACES_SQL "select " MOZ_PLACES_ATTRS \ " from moz_bookmarks " MOZ_PLACES_JOIN_PLACES \ " " MOZ_PLACES_JOIN_ANNOTATION("1", "livemark/feedURI") \ " " MOZ_PLACES_JOIN_ANNOTATION("2", "livemark/siteURI") \ " " MOZ_PLACES_JOIN_ANNOTATION("3", "bookmarkProperties/description") \ " order by parent, position" enum { MOZ_ID, MOZ_TYPE, MOZ_PARENT, MOZ_POSITION, MOZ_TITLE, MOZ_CTIME, MOZ_MTIME, MOZ_ATIME, MOZ_URL, MOZ_FEED, MOZ_SITE, MOZ_DESCRIPTION, MOZ_HIDDEN, MOZ_COLUMN_COUNT }; struct MozPlacesBookmark: ListElement<MozPlacesBookmark> { INT32 m_id; INT32 m_type; INT32 m_parent; INT32 m_position; OpString m_title; OpString m_url; OpString m_feed; OpString m_site; OpString m_description; INT32 m_ctime; INT32 m_mtime; INT32 m_atime; OpVector<MozPlacesBookmark> m_children; enum { MOZ_PLACES_TYPE_LINK = 1, MOZ_PLACES_TYPE_FOLDER = 2, MOZ_PLACES_TYPE_SEPARATOR = 3 }; MozPlacesBookmark() : m_id(0) , m_type(0) , m_parent(0) , m_position(0) , m_ctime(0) , m_mtime(0) , m_atime(0) { } BOOL HasChildren() const { return m_children.GetCount() > 0; } OP_STATUS ReadTuple(const SQLite3Cursor& bookmarks, unsigned long &feed_count) { m_id = bookmarks.GetInt(MOZ_ID); m_type = bookmarks.GetInt(MOZ_TYPE); m_parent = bookmarks.GetInt(MOZ_PARENT); m_position = bookmarks.GetInt(MOZ_POSITION); m_ctime = bookmarks.GetInt(MOZ_CTIME); m_mtime = bookmarks.GetInt(MOZ_MTIME); m_atime = bookmarks.GetInt(MOZ_ATIME); RETURN_IF_ERROR(bookmarks.GetText(MOZ_TITLE, m_title)); RETURN_IF_ERROR(bookmarks.GetText(MOZ_URL, m_url)); RETURN_IF_ERROR(bookmarks.GetText(MOZ_FEED, m_feed)); RETURN_IF_ERROR(bookmarks.GetText(MOZ_SITE, m_site)); RETURN_IF_ERROR(bookmarks.GetText(MOZ_DESCRIPTION, m_description)); if (m_feed.HasContent()) feed_count++; return OpStatus::OK; } OP_STATUS AppendChild(MozPlacesBookmark* child) { return m_children.Add(child); } BookmarkItem* LookForFeeds(BookmarkItem* parent, BookmarkItem* after) { INT32 count = m_children.GetCount(); for (INT32 i = 0; i < count; ++i) after = m_children.Get(i)->LookForFeed(parent, after); return after; } BookmarkItem* LookForFeed(BookmarkItem* parent, BookmarkItem* after) { if (m_type == MOZ_PLACES_TYPE_FOLDER) { if (m_feed.HasContent()) //Livemark folder... return ImportLink(parent, after, m_title, m_feed, m_description, m_ctime, m_mtime, m_atime); return LookForFeeds(parent, after); } return after; } BookmarkItem* ImportChildren(BookmarkItem* parent, BookmarkItem* after) { INT32 count = m_children.GetCount(); for (INT32 i = 0; i < count; ++i) after = m_children.Get(i)->Import(parent, after); return after; } BookmarkItem* Import(BookmarkItem* parent, BookmarkItem* after) { if (m_type == MOZ_PLACES_TYPE_FOLDER) { //LivemarkImportStrategy removed on 2010-09-22 BookmarkItem* local = NULL; if (m_feed.HasContent()) //Livemark folder... { BookmarkItem* child = after; local = parent; if (HasChildren()) { child = NULL; local = ImportFolder(parent, after, m_title, m_description, m_ctime, m_mtime, m_atime); child = ImportChildren(local, child); if (child) child = ImportSeparator(local, child); } child = ImportLink(local, child, m_title, m_site, m_description, m_ctime, m_mtime, m_atime); if (!HasChildren()) { //in case there was no sub-menu, we must properly move the current last to the most recent "child" added... local = child; } } else //normal folders { local = ImportFolder(parent, after, m_title, m_description, m_ctime, m_mtime, m_atime); ImportChildren(local, NULL); } return local; } if (m_type == MOZ_PLACES_TYPE_LINK) return ImportLink(parent, after, m_title, m_url, m_description, m_ctime, m_mtime, m_atime); if (m_type == MOZ_PLACES_TYPE_SEPARATOR) return ImportSeparator(parent, after); return NULL; } static BookmarkItem* ImportFolder(BookmarkItem* parent, BookmarkItem* after, const OpString& title, const OpString& description, INT32 ctime, INT32 mtime, INT32 atime) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); if (!item) return NULL; item->SetFolderType(FOLDER_NORMAL_FOLDER); BOOL succeeded = TRUE; if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_TITLE, title.CStr())); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_DESCRIPTION, description.CStr())); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_CREATED, ctime)); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_VISITED, atime)); if (succeeded) succeeded = OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, after, parent)); if (!succeeded) { OP_DELETE(item); return NULL; } return item; } static BookmarkItem* ImportLink(BookmarkItem* parent, BookmarkItem* after, const OpString& title, const OpString& url, const OpString& description, INT32 ctime, INT32 mtime, INT32 atime) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); if (!item) return after; item->SetFolderType(FOLDER_NO_FOLDER); BOOL succeeded = TRUE; if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_TITLE, title.CStr())); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_URL, url.CStr())); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_DESCRIPTION, description.CStr())); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_CREATED, ctime)); if (succeeded) succeeded = OpStatus::IsSuccess(SetAttribute(item, BOOKMARK_VISITED, atime)); if (succeeded) succeeded = OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, after, parent)); if (!succeeded) { OP_DELETE(item); return after; } return item; } static BookmarkItem* ImportSeparator(BookmarkItem* parent, BookmarkItem* after) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); if (!item) return after; item->SetFolderType(FOLDER_SEPARATOR_FOLDER); if(!OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, after, parent))) { OP_DELETE(item); return after; } return item; } }; OP_STATUS HotlistParser::ImportNetscapeSqlite(const OpStringC& filename, BOOL into_sub_folder) { SQLite3VFS overwrite; SQLite3DB db; SQLite3Cursor roots; SQLite3Cursor bookmarks; AutoDeleteList<MozPlacesBookmark> list; OpString8 path; RETURN_IF_ERROR(path.SetUTF8FromUTF16(filename)); RETURN_IF_ERROR(db.Open(path.CStr(), overwrite.Name())); struct FolderDef { const char* name; int options; int bookmarks_id; MozPlacesBookmark* ref; enum { IMPORT_NONEMPTY = 1, IMPORT_CONTENT = 2 }; } folders[] = { { "toolbar" }, { "unfiled", FolderDef::IMPORT_NONEMPTY }, { "menu", FolderDef::IMPORT_CONTENT }, }; size_t folder_count = sizeof(folders) / sizeof(folders[0]); //************************************************* // // READ ROOT FOLDER DEFINITIONS // RETURN_IF_ERROR(roots.Open(db, "SELECT root_name, folder_id FROM moz_bookmarks_roots")); RETURN_IF_ERROR(roots.TupleSize() != 2 ? OpStatus::ERR : OpStatus::OK); while (roots.Step()) { int folder_id = roots.GetInt(1); const char* root_name = roots.GetRawText8(0); int root_name_len = roots.GetRawTextLen8(0); for (size_t i = 0; i < folder_count; ++i) { if (!strncmp(folders[i].name, root_name, root_name_len)) { folders[i].bookmarks_id = folder_id; break; } } }; roots.Close(); //************************************************* // // READ BOOKMARKS DEFINITIONS // RETURN_IF_ERROR(bookmarks.Open(db, MOZ_PLACES_SQL)); RETURN_IF_ERROR(bookmarks.TupleSize() != MOZ_COLUMN_COUNT ? OpStatus::ERR : OpStatus::OK); unsigned long feed_count = 0; while (bookmarks.Step()) { int hidden = bookmarks.GetInt(MOZ_HIDDEN); if (hidden) continue; MozPlacesBookmark* bm = OP_NEW(MozPlacesBookmark, ()); RETURN_IF_ERROR(bm ? OpStatus::OK : OpStatus::ERR_NO_MEMORY); bm->Into(&list); RETURN_IF_ERROR(bm->ReadTuple(bookmarks, feed_count)); } RETURN_IF_ERROR(bookmarks.StepStatus()); bookmarks.Close(); db.Close(); //************************************************* // // CROSS REFERENCE ROOT FOLDERS WITH BOOKMARKS // for (size_t i = 0; i < folder_count; ++i) { folders[i].ref = list.First(); while (folders[i].ref && folders[i].ref->m_id != folders[i].bookmarks_id) folders[i].ref = folders[i].ref->Suc(); } //************************************************* // // BUILD BOOKMARKS TREE // MozPlacesBookmark* node = list.First(); while (node) { MozPlacesBookmark* parent = list.First(); while (parent && parent->m_id != node->m_parent) parent = parent->Suc(); if (parent) RETURN_IF_ERROR(parent->AppendChild(node)); node = node->Suc(); } //************************************************* // // ACTUALLY IMPORT INTO CORE // BookmarkItem* root = NULL; BookmarkItem* after = NULL; if (into_sub_folder) { OpString name; RETURN_IF_ERROR(g_languageManager->GetString(Str::S_IMPORTED_FIREFOX_BOOKMARKS,name)); OpString empty; root = MozPlacesBookmark::ImportFolder(NULL, NULL, name, empty, 0, 0, 0); } if (feed_count > 0) { OpString name; RETURN_IF_ERROR(g_languageManager->GetString(Str::S_IMPORTED_FIREFOX_FEEDS,name)); OpString empty; BookmarkItem* feeds = MozPlacesBookmark::ImportFolder(root, NULL, name, empty, 0, 0, 0); for (size_t i = 0; i < folder_count; ++i) { if (!folders[i].ref) continue; after = folders[i].ref->LookForFeed(feeds, after); } after = feeds; } for (size_t i = 0; i < folder_count; ++i) { if (!folders[i].ref) continue; if (folders[i].options & FolderDef::IMPORT_NONEMPTY && !folders[i].ref->HasChildren()) continue; if (folders[i].options & FolderDef::IMPORT_CONTENT) after = folders[i].ref->ImportChildren(root, after); else after = folders[i].ref->Import(root, after); } return OpStatus::OK; } #undef MOZ_PLACES_JOIN_LIVEMARK #undef MOZ_PLACES_JOIN_PLACES #undef MOZ_PLACES_ATTRS #undef MOZ_PLACES_SQL OP_STATUS HotlistParser::ImportNetscapeHTML(const OpStringC& filename, BOOL into_sub_folder) { HotlistFileReader reader; OpString8 charset; BOOL charset_found = HotlistFileIO::ProbeCharset(filename, charset); if (charset_found) { reader.SetCharset(charset); } reader.Init(filename, HotlistFileIO::Ascii); if (into_sub_folder) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_NORMAL_FOLDER); if (item) { OpString name; const uni_char* match = filename.CStr() ? uni_stristr(filename.CStr(), UNI_L("firefox")) : 0; if (match) { g_languageManager->GetString(Str::S_IMPORTED_FIREFOX_BOOKMARKS,name); } else { g_languageManager->GetString(Str::S_IMPORTED_NETSCAPE_BOOKMARKS,name); } SetAttribute(item, BOOKMARK_TITLE, name.CStr()); if (OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { m_stack.Push(item); } else { OP_DELETE(item); } } } return ImportNetscapeHTML(reader, into_sub_folder); } OP_STATUS HotlistParser::ImportNetscapeHTML(HotlistFileReader &reader, BOOL into_sub_folder) { int line_length; BOOL multiline_description = FALSE; while (1) { uni_char *line = reader.Readline(line_length); if (!line) { break; } if (!line[0]) { continue; } if (multiline_description) { OpString tmp; multiline_description = GetNetscapeDescription(line,tmp); continue; } const uni_char* p1 = uni_stristr(line, UNI_L("<DT>")); if (p1) { const uni_char* p2; p2 = uni_stristr(p1, UNI_L("<A HREF=")); if (p2) { const uni_char* p2_end = p2; if (uni_stristr(p2, UNI_L("<A HREF=\"")) == p2) { // Typically a bookmarklet. Locate end of content. for (p2_end=&p2[9]; *p2_end && *p2_end != '\"'; p2_end++) {}; } const uni_char *p4 = uni_stristr(p2_end, UNI_L("</A>")); if (p4) { const uni_char* p3 = p4; for (; *p3 != '>' && p3 > p2_end; p3--) {}; if (p3 > p2_end) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_NO_FOLDER); if (item) { OpString tmp; tmp.Set(p3+1, p4-p3-1); ReplaceEscapes(tmp.CStr(), TRUE, FALSE, TRUE); // Convert '&amp;' and friends SetAttribute(item, BOOKMARK_TITLE, tmp.CStr()); if (GetNetscapeTagValue(p2, UNI_L("A HREF"), tmp)) { SetAttribute(item, BOOKMARK_URL, tmp.CStr()); } if (GetNetscapeTagValue(p2_end, UNI_L("ADD_DATE"), tmp)) { SetAttribute(item, BOOKMARK_CREATED, uni_atoi(tmp.CStr())); } if (GetNetscapeTagValue(p2_end, UNI_L("LAST_VISIT"), tmp)) { SetAttribute(item, BOOKMARK_VISITED, uni_atoi(tmp.CStr())); } if (GetNetscapeTagValue(p2_end, UNI_L("SHORTCUTURL"), tmp)) { SetAttribute(item, BOOKMARK_SHORTNAME, tmp.CStr()); } // TODO: Previous if(OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/0, m_stack.Peek() ? m_stack.Peek() : 0))) { if (item->GetFolderType() == FOLDER_NORMAL_FOLDER || item->GetFolderType() == FOLDER_TRASH_FOLDER) m_stack.Push(item); } else { OP_DELETE(item); } } } } continue; } p2 = uni_stristr(p1, UNI_L("<H")); if (p2) { const uni_char *p3 = uni_strstr(p2+1, UNI_L(">")); if (p3) { #if defined(OMNIWEB_BOOKMARKS_SUPPORT) const uni_char *p5 = uni_stristr(p2+1, UNI_L("<a bookmarkid=")); if(p5) { const uni_char *p6 = uni_strstr(p5+1, UNI_L(">")); if(p6) { p3 = p6; } } #endif const uni_char *p4 = uni_strstr(p3+1, UNI_L("<")); if (p4) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_NORMAL_FOLDER); if (item) { OpString tmp; tmp.Set(p3+1, p4-p3-1); ReplaceEscapes(tmp.CStr(), TRUE, FALSE, TRUE); // Convert '&amp;' and friends SetAttribute(item, BOOKMARK_TITLE, tmp.CStr()); if (GetNetscapeTagValue(p2, UNI_L("ADD_DATE"), tmp)) { SetAttribute(item, BOOKMARK_CREATED, uni_atoi(tmp.CStr())); } if(OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/0, m_stack.Peek() ? m_stack.Peek() : 0))) { if (item->GetFolderType() == FOLDER_NORMAL_FOLDER || item->GetFolderType() == FOLDER_TRASH_FOLDER) m_stack.Push(item); } else { OP_DELETE(item); } } RETURN_IF_ERROR(ImportNetscapeHTML(reader, FALSE)); m_stack.Pop(); } } continue; } } p1 = uni_stristr(line, UNI_L("</DL>")); if (p1) { // End of folder return OpStatus::OK; } p1 = uni_stristr(line, UNI_L("<DD>")); if (p1) { // Description (multiline if line ends with a <BR>) OpString tmp; multiline_description = GetNetscapeDescription(p1+4, tmp); continue; } p1 = uni_stristr(line, UNI_L("<H1>")); if (p1) { const uni_char *p2 = uni_stristr(p1+4, UNI_L("</H1>")); if (p2) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_NORMAL_FOLDER); if (item) { OpString tmp; tmp.Set(p1+4, p2-p1-4); SetAttribute(item, BOOKMARK_TITLE, tmp.CStr()); if (OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { if (item->GetFolderType() == FOLDER_NORMAL_FOLDER || item->GetFolderType() == FOLDER_TRASH_FOLDER) m_stack.Push(item); } else { OP_DELETE(item); } } RETURN_IF_ERROR(ImportNetscapeHTML(reader,FALSE)); continue; } } p1 = uni_strstr(line, UNI_L("<HR>")); if (p1) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_SEPARATOR_FOLDER); if (item) { if (OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { if (item->GetFolderType() == FOLDER_NORMAL_FOLDER || item->GetFolderType() == FOLDER_TRASH_FOLDER) m_stack.Push(item); } else { OP_DELETE(item); } } } } return OpStatus::OK; } OP_STATUS HotlistParser::ImportExplorerFavorites(const OpStringC& path, BOOL into_sub_folder) { #ifdef _MACINTOSH_ // Mac IE uses the same format as Netscape, but allows various text encodings too HotlistFileReader reader; OpString8 charset; BOOL charset_found = HotlistFileIO::ProbeCharset(path, charset); if (charset_found) { reader.SetCharset(charset); } reader.Init(path, HotlistFileIO::Ascii); // this is really a filename BookmarkItem* item = OP_NEW(BookmarkItem, ()); item->SetFolderType(FOLDER_NORMAL_FOLDER); if (item) { OpString name; g_languageManager->GetString(Str::S_IMPORTED_EXPLORER_BOOKMARKS,name); BookmarkAttribute attribute; attribute.SetTextValue(name); item->SetAttribute(BOOKMARK_TITLE, &attribute); if (!DesktopBookmarkManager::AddCoreItem(item)) { OP_DELETE(item); item = 0; } } return ImportNetscapeHTML(reader, FALSE); #else // _MACINTOCH_ OpString extensions; extensions.Set("*"); OpString top_folder_name; if (into_sub_folder) { g_languageManager->GetString(Str::S_IMPORTED_EXPLORER_BOOKMARKS, top_folder_name); } return ImportDirectory(path, extensions, top_folder_name); #endif } OP_STATUS HotlistParser::ImportKDE1Bookmarks(const OpStringC& path) { OpString extensions; //extensions.Set(".desktop,.kdelnk"); extensions.Set("*.desktop"); OpString name; g_languageManager->GetString(Str::S_IMPORTED_KDE1_BOOKMARKS,name); return ImportDirectory(path, extensions, name); } #if defined(_MACINTOSH_) && defined(SAFARI_BOOKMARKS_SUPPORT) #include "platforms/mac/util/MachOCompatibility.h" #define kChildrenKeyString "Children" #define kVersionKeyString "WebBookmarkFileVersion" #define kBookmarkTypeKeyString "WebBookmarkType" #define kBookmarkFolderTitleKeyString "Title" // Case sensitive #define kBookmarkTitleKeyString "title" // Case sensitive #define kBookmarkURLKeyString "URLString" #define kBookmarkURIDictionaryKeyString "URIDictionary" #define kBookmarkListValue "WebBookmarkTypeList" #define kBookmarkLeafValue "WebBookmarkTypeLeaf" OP_STATUS HotlistParser::ImportKonquerorBookmarks(const OpStringC& filename) { OpString name; g_languageManager->GetString(Str::S_IMPORTED_KONQUEROR_BOOKMARKS,name); CFPropertyListRef propertyList; CFStringRef errorString; CFDataRef resourceData; Boolean status; SInt32 errorCode; CFURLRef theBookmarksURL; CFStringRef theBookmarksCFString; OP_STATUS result = OpStatus::OK; theBookmarksCFString = CFStringCreateWithCharacters(kCFAllocatorDefault, (UniChar*)filename.CStr(), filename.Length()); if(theBookmarksCFString) { theBookmarksURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, theBookmarksCFString, kCFURLPOSIXPathStyle, false); if(theBookmarksURL) { // Read the XML file. status = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault, theBookmarksURL, &resourceData, // place to put file data NULL, NULL, &errorCode); if(resourceData && (status == true)) { // Reconstitute the dictionary using the XML data. propertyList = CFB_CALL(CFPropertyListCreateFromXMLData)(kCFAllocatorDefault, resourceData, kCFPropertyListImmutable, &errorString); if(propertyList) { // Make sure we really got a CFDictionary if(CFGetTypeID(propertyList) == CFDictionaryGetTypeID()) { CFDictionaryRef dict = (CFDictionaryRef)propertyList; SInt32 value = 0; CFNumberRef safariBookmarksVersion; if(CFDictionaryGetValueIfPresent(dict, CFSTR(kVersionKeyString), (const void **)&safariBookmarksVersion)) { if (CFNumberGetValue(safariBookmarksVersion, kCFNumberSInt32Type, &value)) { if(value == 1) { // Version 1.0, ok CFStringRef cfBookmarkType; if(CFDictionaryGetValueIfPresent(dict, CFSTR(kBookmarkTypeKeyString), (const void **)&cfBookmarkType)) { if(cfBookmarkType && CFStringCompare(cfBookmarkType, CFSTR(kBookmarkListValue), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { CFArrayRef children; if(CFDictionaryGetValueIfPresent(dict, CFSTR(kChildrenKeyString), (const void **)&children)) { result = ImportSafariBookmarks(children, name); } } } } } } } CFRelease(propertyList); } CFRelease(resourceData); } CFRelease(theBookmarksURL); } CFRelease(theBookmarksCFString); } return result; } uni_char * Copy_CFStringRefToUnichar(const CFStringRef cfstr) { uni_char *result = 0; if(cfstr) { CFIndex len = CFStringGetLength(cfstr); const uni_char* cfchars = (uni_char*)CFStringGetCharactersPtr(cfstr); if(cfchars) { UniSetStrN(result, cfchars, len); } else { result = OP_NEWA(uni_char, len+1); if(result) { CFStringGetCharacters(cfstr, CFRangeMake(0, len), (UniChar*)result); result[len] = 0; } } } return result; } OP_STATUS HotlistParser::ImportSafariBookmarks(CFArrayRef array, const OpStringC& top_folder_name) { OP_STATUS result = OpStatus::OK; if (!top_folder_name.IsEmpty()) { AddNewBookmarkFolder(top_folder_name.CStr()); } CFStringRef cfTemp = 0; uni_char *uni_temp = 0; CFIndex array_count, array_index; CFIndex dict_count, dict_index; CFDictionaryRef dict; if(!array) return OpStatus::OK; array_count = CFArrayGetCount(array); for (array_index = 0;array_index < array_count;array_index++) { dict = (CFDictionaryRef)CFArrayGetValueAtIndex(array, array_index); dict_count = CFDictionaryGetCount(dict); CFTypeRef *theKeys = (CFTypeRef*) malloc(sizeof(CFTypeRef*) * dict_count); // ??? op_malloc ??? CFTypeRef *theValues = (CFTypeRef*) malloc(sizeof(CFTypeRef*) * dict_count); // ??? op_malloc ??? /* Where do the CF... functions come from ? Might they realloc these ? * Otherwise, why don't we use op_malloc (and op_free, below) ? * FIXME: please document if you know ! */ if ((NULL != theKeys) && (NULL != theValues)) { CFDictionaryGetKeysAndValues(dict,theKeys, theValues); for (dict_index = 0;dict_index < dict_count;dict_index++) { if(CFStringCompare((CFStringRef)theKeys[dict_index], CFSTR(kBookmarkTypeKeyString), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { if(CFStringCompare((CFStringRef)theValues[dict_index], CFSTR(kBookmarkListValue), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { cfTemp = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(kBookmarkFolderTitleKeyString)); uni_temp = Copy_CFStringRefToUnichar(cfTemp); AddNewBookmarkFolder(uni_temp); CFArrayRef children = (CFArrayRef) CFDictionaryGetValue(dict, CFSTR(kChildrenKeyString)); OpStringC top_folder_name; result = ImportSafariBookmarks(children, top_folder_name); m_stack.Pop(); OP_DELETEA(uni_temp); } else if(CFStringCompare((CFStringRef)theValues[dict_index], CFSTR(kBookmarkLeafValue), kCFCompareCaseInsensitive) == kCFCompareEqualTo) { const uni_char* uni_temp2 = NULL; CFDictionaryRef uriDict = (CFDictionaryRef) CFDictionaryGetValue(dict, CFSTR(kBookmarkURIDictionaryKeyString)); cfTemp = (CFStringRef) CFDictionaryGetValue(uriDict, CFSTR(kBookmarkTitleKeyString)); uni_temp = Copy_CFStringRefToUnichar(cfTemp); cfTemp = (CFStringRef) CFDictionaryGetValue(dict, CFSTR(kBookmarkURLKeyString)); uni_temp2 = Copy_CFStringRefToUnichar(cfTemp); AddNewBookmark(uni_temp,uni_temp2); OP_DELETEA(uni_temp); OP_DELETEA(uni_temp2); } } } } free(theKeys); // ??? op_free ??? free(theValues); // ??? op_free ??? } return result; } #else // SAFARI_BOOKMARKS_SUPPORT && _MACINTOSH_ OP_STATUS HotlistParser::ImportKonquerorBookmarks(const OpStringC& filename) { HotlistXBELReader reader; reader.SetFilename(filename); reader.Parse(); OpString name; g_languageManager->GetString(Str::S_IMPORTED_KONQUEROR_BOOKMARKS,name); INT32 index = 0; INT32 folder_count = -1; return ImportXBEL(reader, index, folder_count, name); } OP_STATUS HotlistParser::ImportXBEL(HotlistXBELReader& reader, INT32& index, INT32 folder_count, const OpStringC& top_folder_name) { if (!top_folder_name.IsEmpty()) { AddNewBookmarkFolder(top_folder_name.CStr()); } for (; index < reader.GetCount();) { if (folder_count == 0) { break; } XBELReaderModelItem* node = reader.GetItem(index); if (node) { if (reader.IsFolder(node)) { INT32 child_count = reader.GetChildCount(index); index++; BookmarkItem* item = OP_NEW(BookmarkItem, ()); if(item) { item->SetFolderType(FOLDER_NORMAL_FOLDER); SetAttribute(item, BOOKMARK_TITLE, reader.GetName(node).CStr()); SetAttribute(item, BOOKMARK_CREATED, reader.GetCreated(node)); SetAttribute(item, BOOKMARK_VISITED, reader.GetVisited(node)); if (OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { m_stack.Push(item); } else { OP_DELETE(item); item = 0; } RETURN_IF_ERROR(ImportXBEL(reader, index, child_count, OpString())); } } else { index++; BookmarkItem* item = OP_NEW(BookmarkItem, ()); if(item) { item->SetFolderType(FOLDER_NO_FOLDER); SetAttribute(item, BOOKMARK_TITLE, reader.GetName(node).CStr()); SetAttribute(item, BOOKMARK_URL, reader.GetUrl(node).CStr()); SetAttribute(item, BOOKMARK_CREATED, reader.GetCreated(node)); SetAttribute(item, BOOKMARK_VISITED, reader.GetVisited(node)); if (!OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { OP_DELETE(item); item = 0; } } } } folder_count --; } return OpStatus::OK; } #endif // SAFARI_BOOKMARKS_SUPPORT && _MACINTOSH_ OP_STATUS HotlistParser::ImportDirectory(const OpStringC& path, const OpStringC& extensions, const OpStringC& top_folder_name) { HotlistDirectoryReader reader; reader.Construct(path, extensions); if (!top_folder_name.IsEmpty()) { AddNewBookmarkFolder(top_folder_name.CStr()); } HotlistDirectoryReader::Node *node = reader.GetFirstEntry(); while (node) { if (reader.IsDirectory(node)) { if(AddNewBookmarkFolder(reader.GetName(node).CStr(), reader.GetCreated(node), reader.GetVisited(node))) { OpStringC top_folder_name; RETURN_IF_ERROR(ImportDirectory(reader.GetPath(node), extensions, top_folder_name)); m_stack.Pop(); } } else if (reader.IsFile(node)) { AddNewBookmark(reader.GetName(node).CStr(), reader.GetUrl(node).CStr(), reader.GetCreated(node), reader.GetVisited(node)); } node = reader.GetNextEntry(); } return OpStatus::OK; } OP_STATUS HotlistParser::Write(const OpString &filename, HotlistModel &model, BOOL all, BOOL safe) { HotlistFileWriter writer; RETURN_IF_ERROR(writer.Open(filename, safe)); RETURN_IF_ERROR(writer.WriteHeader(model.GetModelIsSynced())); RETURN_IF_ERROR(Write(writer, model, all)); RETURN_IF_ERROR(writer.Close()); return OpStatus::OK; } OP_STATUS HotlistParser::Write(HotlistFileWriter &writer, HotlistModel &model, BOOL all) { for (int i=0; i<model.GetItemCount();) { RETURN_IF_ERROR(Write(writer, model, i, TRUE, all, i)); } return OpStatus::OK; } OP_STATUS HotlistParser::Write(HotlistFileWriter& writer, HotlistModel& model, INT32 index, BOOL recursive, BOOL all, INT32& next_index) { next_index = -1; HotlistModelItem* item = model.GetItemByIndex(index); if (item) { if (item->IsBookmark()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteBookmarkNode(writer, *item)); } } else if (item->IsNote()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteNoteNode(writer, *item)); } } else if (item->IsSeparator()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteSeparatorNode(writer, *item)); } } #ifdef WEBSERVER_SUPPORT else if (item->IsUniteService()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteUniteServiceNode(writer, *item)); } } #endif // WEBSERVER_SUPPORT else if (item->IsContact()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteContactNode(writer, *item)); } } else if (item->IsGroup()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteGroupNode(writer, *item)); } } else if (item->IsFolder()) { if (all || item->GetIsMarked()) { RETURN_IF_ERROR(WriteFolderNode(writer, *item, model)); } if (recursive) { INT32 parent_index = index; index ++; while (index<model.GetItemCount()) { int p = model.GetItemParent(index); if (p != parent_index) { break; } // The commented out test disables a real save-only-what-is-selected RETURN_IF_ERROR(Write(writer, model, index, TRUE, all || (item->GetIsMarked() /*&& !item->GetIsExpandedFolder()*/), index)); } if (all || item->GetIsMarked()) { RETURN_IF_ERROR(writer.WriteAscii("-\n\n")); } next_index = index; return OpStatus::OK; } } } next_index = index + 1; return OpStatus::OK; } OP_STATUS HotlistParser::WriteHTML(const OpString &filename, BookmarkModel &model, BOOL all, BOOL safe) { HotlistFileWriter writer; RETURN_IF_ERROR(writer.Open(filename, safe)); RETURN_IF_ERROR(WriteHTML(writer, model, all)); RETURN_IF_ERROR(writer.Close()); return OpStatus::OK; } OP_STATUS HotlistParser::WriteHTML(HotlistFileWriter& writer, BookmarkModel& model, BOOL all) { OpString bookmarks; g_languageManager->GetString(Str::SI_IDSTR_HL_BOOKMARKS_ROOT_FOLDER_NAME, bookmarks); #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) RETURN_IF_ERROR(writer.WriteAscii("<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\n<!--This is an automatically generated file.\nIt will be read and overwritten.\nDo Not Edit! -->\n<TITLE>")); RETURN_IF_ERROR(writer.WriteUni(bookmarks.CStr())); RETURN_IF_ERROR(writer.WriteAscii("</TITLE>\n<H1>")); RETURN_IF_ERROR(writer.WriteUni(bookmarks.CStr())); RETURN_IF_ERROR(writer.WriteAscii("</H1>\n<DL><P>\n")); #else RETURN_IF_ERROR(writer.WriteAscii("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>\n")); RETURN_IF_ERROR(writer.WriteUni(bookmarks.CStr())); RETURN_IF_ERROR(writer.WriteAscii("\n</title><style type=\"text/css\">\ndl { margin-left: 2em; margin-top: 1em}\ndt { margin-left: 0; font-weight: bold}\ndd { margin-left: 0; }\ndl.first {margin-left: 0 }\n</style>\n</head>\n\n<body>\n<dl class=first>\n")); #endif BOOL first = TRUE; for (int i=0; i<model.GetItemCount();) { RETURN_IF_ERROR(WriteHTML(writer, model, i, first, all, i, 4)); } #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) RETURN_IF_ERROR(writer.WriteAscii("</DL><P>\n")); #else RETURN_IF_ERROR(writer.WriteAscii("</dl>\n\n</body>\n</html>\n")); #endif return OpStatus::OK; } OP_STATUS HotlistParser::WriteHTML(HotlistFileWriter& writer, BookmarkModel& model, INT32 index, BOOL& first, BOOL all, INT32& next_index, INT32 indent) { OP_STATUS ret = OpStatus::OK; next_index = -1; HotlistModelItem* item = model.GetItemByIndex(index); if (item) { uni_char* html_string; if (item->IsBookmark()) { if (all || item->GetIsMarked()) { const OpStringC &url = item->GetResolvedUrl(); html_string = HTMLify_string(url.CStr()); #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) ret = writer.WriteFormat("%*s<DT><A HREF=\"%s\" ADD_DATE=\"%d\" LAST_VISITED=\"%d\"", indent, UNI_L(""), html_string ? html_string : UNI_L(""), item->GetCreated(), item->GetVisited()); OP_DELETEA(html_string); if (ret != OpStatus::OK) return ret; html_string = HTMLify_string(item->GetShortName().CStr()); if (html_string && *html_string) { ret = writer.WriteFormat(" SHORTCUTURL=\"%s\"", html_string); if (ret != OpStatus::OK) { OP_DELETEA(html_string); return ret; } } OP_DELETEA(html_string); RETURN_IF_ERROR(writer.WriteAscii(">")); html_string = HTMLify_string(item->GetName().CStr()); ret = writer.WriteFormat("%s</A>\n", html_string ? html_string : UNI_L("")); OP_DELETEA(html_string); RETURN_IF_ERROR(ret); html_string = HTMLify_string(item->GetDescription().CStr()); if (html_string && uni_strlen(html_string) > 0) { OpString tmp; ConvertFromNewline(tmp, html_string, UNI_L("<BR>\n")); ret = writer.WriteFormat("%*s%<DD>%s</DD>\n", indent, UNI_L(""), tmp.CStr() ? tmp.CStr() : UNI_L("")); } OP_DELETEA(html_string); RETURN_IF_ERROR(ret); #else // (SUPPORT_WRITE_NETSCAPE_BOOKMARKS) ret = writer.WriteFormat("<dd><a href=\"%s\">", html_string ? html_string : UNI_L("")); OP_DELETEA(html_string); RETURN_IF_ERROR(ret); html_string = HTMLify_string(item->GetName()); ret = writer.WriteFormat("%s", html_string ? html_string : UNI_L("")); OP_DELETEA(html_string); RETURN_IF_ERROR(ret); RETURN_IF_ERROR(writer.WriteAscii("</a></dd>\n")); #endif // (SUPPORT_WRITE_NETSCAPE_BOOKMARKS) } next_index = index + 1; return OpStatus::OK; } else if (item->IsSeparator()) { #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) RETURN_IF_ERROR(writer.WriteFormat("%*s%<HR>\n", indent, UNI_L(""))); #endif } else if (item->IsFolder() && !item->GetIsTrashFolder()) { BOOL was_first = first; if ((all && !item->GetIsTrashFolder()) || item->GetIsMarked()) { #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) html_string = HTMLify_string(item->GetName().CStr()); ret = writer.WriteFormat("%*s<DT><H3 ADD_DATE=\"%d\">%s</H3>\n", indent, UNI_L(""), item->GetCreated(), html_string ? html_string : UNI_L("")); OP_DELETEA(html_string); RETURN_IF_ERROR(ret); RETURN_IF_ERROR(writer.WriteFormat("%*s<DL><P>\n", indent, UNI_L(""))); #else // SUPPORT_WRITE_NETSCAPE_BOOKMARKS if (was_first) { RETURN_IF_ERROR(writer.WriteAscii("<dt>")); } else { RETURN_IF_ERROR(writer.WriteAscii("<dd>\n<dl>\n<dt>")); } first = FALSE; html_string = HTMLify_string(item->GetName()); if (html_string) { ret = writer.WriteUni(html_string); OP_DELETEA(html_string); } RETURN_IF_ERROR(ret); RETURN_IF_ERROR(writer.WriteAscii("</dt>\n")); #endif // SUPPORT_WRITE_NETSCAPE_BOOKAMRKS } INT32 parent_index = index; index ++; while (index<model.GetItemCount()) { int p = model.GetItemParent(index); if (p != parent_index) { break; } // The commented out test disables a real save-only-what-is-selected RETURN_IF_ERROR(WriteHTML(writer, model, index, first, all || (item->GetIsMarked() /*&& !item->GetIsExpandedFolder()*/), index, indent+4)); } if (all || item->GetIsMarked()) { #if defined(SUPPORT_WRITE_NETSCAPE_BOOKMARKS) RETURN_IF_ERROR(writer.WriteFormat("%*s</DL><P>\n", indent, UNI_L(""))); #else if (!was_first) { RETURN_IF_ERROR(writer.WriteAscii("</dl>\n</dd>\n")); } #endif } first = was_first; next_index = index; return OpStatus::OK; } } next_index = index + 1; return OpStatus::OK; } OP_STATUS HotlistParser::WriteDeletedDefaultBookmark(HotlistFileWriter& writer) { // If this hits BookmarkAdrStorage wasn't closed completely when g_desktop_bookmark_manager destructs. OP_ASSERT(g_desktop_bookmark_manager); if (!g_desktop_bookmark_manager) return OpStatus::ERR; const OpAutoVector<OpString>& bookmarks = g_desktop_bookmark_manager->DeletedDefaultBookmarks(); if (bookmarks.GetCount()) { RETURN_IF_ERROR(writer.WriteAscii("#DELETED\n")); for (UINT32 i=0; i<bookmarks.GetCount(); i++) { RETURN_IF_ERROR(writer.WriteFormat("\tPARTNERID=%s\n", bookmarks.Get(i)->CStr())); } } return OpStatus::OK; } OP_STATUS HotlistParser::WriteBookmarkNode(HotlistFileWriter& writer, HotlistModelItem& item) { RETURN_IF_ERROR(writer.WriteAscii("#URL\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); if (item.GetName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", item.GetName().CStr())); if (item.GetUrl().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tURL=%s\n", item.GetUrl().CStr())); if (item.GetDisplayUrl().CStr() && item.GetDisplayUrl().Compare(item.GetUrl()) != 0) RETURN_IF_ERROR(writer.WriteFormat("\tDISPLAY URL=%s\n", item.GetDisplayUrl().CStr())); if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited()) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetDescription().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetDescription().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tDESCRIPTION=%s\n", tmp.CStr())); } if (item.GetShortName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tSHORT NAME=%s\n", item.GetShortName().CStr())); if (item.GetModel()->GetActiveItemId() == item.GetID()) RETURN_IF_ERROR(writer.WriteAscii("\tACTIVE=YES\n")); if (item.GetOnPersonalbar()) { RETURN_IF_ERROR(writer.WriteAscii("\tON PERSONALBAR=YES\n")); RETURN_IF_ERROR(writer.WriteFormat("\tPERSONALBAR_POS=%d\n", item.GetPersonalbarPos())); } if (item.GetInPanel()) { RETURN_IF_ERROR(writer.WriteAscii("\tIN PANEL=YES\n")); RETURN_IF_ERROR(writer.WriteFormat("\tPANEL_POS=%d\n", item.GetPanelPos())); } if (item.GetSmallScreen()) { RETURN_IF_ERROR(writer.WriteAscii("\tSMALL SCREEN=YES\n")); } if (item.GetUniqueGUID().CStr()) { RETURN_IF_ERROR(writer.WriteFormat("\tUNIQUEID=%s\n", item.GetUniqueGUID().CStr())); } if (item.GetPartnerID().CStr()) { RETURN_IF_ERROR(writer.WriteFormat("\tPARTNERID=%s\n", item.GetPartnerID().CStr())); } #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } OP_STATUS HotlistParser::WriteNoteNode(HotlistFileWriter& writer, HotlistModelItem& item) { RETURN_IF_ERROR(writer.WriteAscii("#NOTE\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); #ifdef SUPPORT_SYNC_NOTES if (item.GetUniqueGUID().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tUNIQUEID=%s\n", item.GetUniqueGUID().CStr())); #endif if (item.GetName().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetName().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", tmp.CStr())); } if (item.GetUrl().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tURL=%s\n", item.GetUrl().CStr())); if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited()) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetDescription().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetDescription().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tDESCRIPTION=%s\n", tmp.CStr())); } if (item.GetModel()->GetActiveItemId() == item.GetID()) RETURN_IF_ERROR(writer.WriteAscii("\tACTIVE=YES\n")); #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } #ifdef GADGET_SUPPORT OP_STATUS HotlistParser::WriteGadgetNode(HotlistFileWriter& writer, HotlistModelItem& item) { if (item.GetName().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetName().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", tmp.CStr())); } //gadget specific if (item.GetGadgetIdentifier().CStr()) { RETURN_IF_ERROR(writer.WriteFormat("\tIDENTIFIER=%s\n", item.GetGadgetIdentifier().CStr())); } if(item.GetGadgetCleanUninstall()) RETURN_IF_ERROR(writer.WriteAscii("\tCLEAN UNINSTALL=YES\n")); //generic if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited()) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetModel()->GetActiveItemId() == item.GetID()) RETURN_IF_ERROR(writer.WriteAscii("\tACTIVE=YES\n")); #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } #ifdef WEBSERVER_SUPPORT OP_STATUS HotlistParser::WriteUniteServiceNode(HotlistFileWriter& writer, HotlistModelItem& item) { if (item.IsUniteService()) { RETURN_IF_ERROR(writer.WriteAscii("#UNITESERVICE\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); UniteServiceModelItem & unite_item = static_cast<UniteServiceModelItem &>(item); if (unite_item.IsRootService()) RETURN_IF_ERROR(writer.WriteAscii("\tROOT=YES\n")); if (unite_item.NeedsConfiguration()) RETURN_IF_ERROR(writer.WriteAscii("\tNEEDS_CONFIGURATION=YES\n")); if (unite_item.NeedsToAutoStart()) RETURN_IF_ERROR(writer.WriteAscii("\tRUNNING=YES\n")); return WriteGadgetNode(writer, item); } else return OpStatus::ERR; } #endif // WEBSERVER_SUPPORT #endif // GADGET_SUPPORT OP_STATUS HotlistParser::WriteSeparatorNode(HotlistFileWriter& writer, HotlistModelItem& item) { if (item.GetSeparatorType() != SeparatorModelItem::NORMAL_SEPARATOR) { return OpStatus::OK; } RETURN_IF_ERROR(writer.WriteAscii("#SEPERATOR\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); if (item.GetUniqueGUID().CStr()) { RETURN_IF_ERROR(writer.WriteFormat("\tUNIQUEID=%s\n", item.GetUniqueGUID().CStr())); } RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } OP_STATUS HotlistParser::WriteContactNode(HotlistFileWriter& writer, HotlistModelItem& item) { RETURN_IF_ERROR(writer.WriteAscii("#CONTACT\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); if (item.GetName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", item.GetName().CStr())); if (item.GetUrl().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tURL=%s\n", item.GetUrl().CStr())); if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetDescription().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetDescription().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tDESCRIPTION=%s\n", tmp.CStr())); } if (item.GetShortName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tSHORT NAME=%s\n", item.GetShortName().CStr())); if (item.GetModel()->GetActiveItemId() == item.GetID()) RETURN_IF_ERROR(writer.WriteAscii("\tACTIVE=YES\n")); if (item.GetOnPersonalbar()) { RETURN_IF_ERROR(writer.WriteAscii("\tON PERSONALBAR=YES\n")); RETURN_IF_ERROR(writer.WriteFormat("\tPERSONALBAR_POS=%d\n", item.GetPersonalbarPos())); } if (item.GetMail().HasContent()) { // Pre 7 versions used 0x020x02 as a separator in the file OpString tmp; ConvertFromComma(tmp, item.GetMail().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tMAIL=%s\n", tmp.CStr())); } if (item.GetPhone().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tPHONE=%s\n", item.GetPhone().CStr())); if (item.GetFax().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tFAX=%s\n", item.GetFax().CStr())); if (item.GetPostalAddress().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetPostalAddress().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tPOSTALADDRESS=%s\n", tmp.CStr())); //writer.WriteFormat("\tPOSTALADDRESS=%s\n", item.GetPostalAddress().CStr()); } if (item.GetPictureUrl().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tPICTUREURL=%s\n", item.GetPictureUrl().CStr())); if (item.IsContact() && item.GetImage()) { OpString icon; icon.Set(item.GetImage()); RETURN_IF_ERROR(writer.WriteFormat("\tICON=%s\n", icon.CStr())); } if (item.GetConaxNumber().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\t00: CONAX CARD NUMBER=%s\n", item.GetConaxNumber().CStr())); if (item.GetImAddress().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMADDRESS=%s\n", item.GetImAddress().CStr())); if (item.GetImProtocol().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMPROTOCOL=%s\n", item.GetImProtocol().CStr())); if (item.GetImStatus().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMSTATUS=%s\n", item.GetImStatus().CStr())); if (item.GetImXPosition().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMXPOSITION=%s\n", item.GetImXPosition().CStr())); if (item.GetImYPosition().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMYPOSITION=%s\n", item.GetImYPosition().CStr())); if (item.GetImWidth().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMWIDTH=%s\n", item.GetImWidth().CStr())); if (item.GetImHeight().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMHEIGHT=%s\n", item. GetImHeight().CStr())); if (item.GetImVisibility().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMVISIBILITY=%s\n", item.GetImVisibility().CStr())); if (item.GetImMaximized().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tIMMAXIMIZED=%s\n", item.GetImMaximized().CStr())); if (item.GetM2IndexId(FALSE) != 0) RETURN_IF_ERROR(writer.WriteFormat("\tM2INDEXID=%d\n", item.GetM2IndexId(FALSE))); #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } OP_STATUS HotlistParser::WriteFolderNode(HotlistFileWriter& writer, HotlistModelItem& item, HotlistModel& model) { RETURN_IF_ERROR(writer.WriteAscii("#FOLDER\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); if (model.GetModelType() == HotlistModel::NoteRoot && item.GetName().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetName().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", tmp.CStr())); } else if (item.GetName().CStr()) { RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", item.GetName().CStr())); } if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetDescription().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetDescription().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tDESCRIPTION=%s\n", tmp.CStr())); } if (item.GetShortName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tSHORT NAME=%s\n", item.GetShortName().CStr())); if (item.GetPartnerID().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tPARTNERID=%s\n", item.GetPartnerID().CStr())); if (item.GetModel()->GetActiveItemId() == item.GetID()) RETURN_IF_ERROR(writer.WriteAscii("\tACTIVE=YES\n")); if (item.GetOnPersonalbar()) { RETURN_IF_ERROR(writer.WriteAscii("\tON PERSONALBAR=YES\n")); RETURN_IF_ERROR(writer.WriteFormat("\tPERSONALBAR_POS=%d\n", item.GetPersonalbarPos())); } if (item.GetIsTrashFolder()) RETURN_IF_ERROR(writer.WriteAscii("\tTRASH FOLDER=YES\n")); if (item.GetTarget().HasContent()) RETURN_IF_ERROR(writer.WriteFormat("\tTARGET=%s\n", item.GetTarget().CStr())); if (item.GetHasMoveIsCopy()) RETURN_IF_ERROR(writer.WriteAscii("\tMOVE_IS_COPY=YES\n")); if (!item.GetIsDeletable()) RETURN_IF_ERROR(writer.WriteAscii("\tDELETABLE=NO\n")); if (!item.GetSubfoldersAllowed()) RETURN_IF_ERROR(writer.WriteAscii("\tSUBFOLDER_ALLOWED=NO\n")); if (!item.GetSeparatorsAllowed()) RETURN_IF_ERROR(writer.WriteAscii("\tSEPARATOR_ALLOWED=NO\n")); if (item.GetMaxItems() != -1) RETURN_IF_ERROR(writer.WriteFormat("\tMAX_ITEMS=%d\n", item.GetMaxItems())); if (item.GetIsExpandedFolder() && !item.GetIsTrashFolder()) RETURN_IF_ERROR(writer.WriteAscii("\tEXPANDED=YES\n")); #if defined(SUPPORT_IMPORT_LINKBAR_TAG) if (item.GetIsLinkBarFolder()) { RETURN_IF_ERROR(writer.WriteAscii("\tLINKBAR FOLDER=YES\n")); RETURN_IF_ERROR(writer.WriteAscii("\tLINKBAR STOP=YES\n")); } #endif if (item.GetUniqueGUID().CStr()) { OpString guid; guid.Set(item.GetUniqueGUID()); RETURN_IF_ERROR(writer.WriteFormat("\tUNIQUEID=%s\n", guid.CStr())); } #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } OP_STATUS HotlistParser::WriteTrashFolderNode(HotlistFileWriter& writer, BookmarkItem *bookmark) { RETURN_IF_ERROR(writer.WriteAscii("#FOLDER\n")); RETURN_IF_ERROR(writer.WriteAscii("\tNAME=Trash\n")); // Name doesn't matter for trash RETURN_IF_ERROR(writer.WriteFormat("\tUNIQUEID=%s\n", bookmark->GetUniqueId())); RETURN_IF_ERROR(writer.WriteAscii("\tTRASH FOLDER=YES\n")); RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } OP_STATUS HotlistParser::WriteGroupNode(HotlistFileWriter& writer, HotlistModelItem& item) { RETURN_IF_ERROR(writer.WriteAscii("#GROUP\n")); RETURN_IF_ERROR(writer.WriteFormat("\tID=%d\n", item.GetID())); if (item.GetName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tNAME=%s\n", item.GetName().CStr())); if (item.GetCreated() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tCREATED=%d\n", item.GetCreated())); if (item.GetVisited() > 0) RETURN_IF_ERROR(writer.WriteFormat("\tVISITED=%d\n", item.GetVisited())); if (item.GetDescription().CStr()) { OpString tmp; ConvertFromNewline(tmp, item.GetDescription().CStr(), newline_comma_replacement); RETURN_IF_ERROR(writer.WriteFormat("\tDESCRIPTION=%s\n", tmp.CStr())); } if (item.GetShortName().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tSHORT NAME=%s\n", item.GetShortName().CStr())); if (item.GetGroupList().CStr()) RETURN_IF_ERROR(writer.WriteFormat("\tMEMBERS=%s\n", item.GetGroupList().CStr())); #if defined(SUPPORT_UNKNOWN_TAGS) if (item.GetUnknownTags().CStr()) { RETURN_IF_ERROR(writer.WriteUni(item.GetUnknownTags().CStr())); } #endif RETURN_IF_ERROR(writer.WriteAscii("\n")); return OpStatus::OK; } int HotlistParser::IsKey(const uni_char* candidate, int candidateLen, const char* key, int keyLen) { if (candidateLen >= keyLen) { for (int i=0; i<keyLen; i++) { if (candidate[i] != (uni_char)key[i]) return -1; } return keyLen; } return -1; } BOOL HotlistParser::IsYes(const uni_char* candidate) { // faster and less complex than uni_stricmp return candidate && (candidate[0] & 0xdf) == 'Y' && (candidate[1] & 0xdf) == 'E' && (candidate[2] & 0xdf) == 'S'; } BOOL HotlistParser::IsNo(const uni_char* candidate) { // faster and less complex than uni_stricmp return candidate && (candidate[0] & 0xdf) == 'N' && (candidate[1] & 0xdf) == 'O'; } void HotlistParser::ConvertFromNewline(OpString &dest, const uni_char* src, const uni_char* replacement) { int subLen = 0; int subStart = 0; int len = src ? uni_strlen(src) : 0; //Fix for bug [184935] The length of a note is unlimited, notes can be very large // Necessary to reserve buffer to avoid unneccesary Grows in // OpString. dest.Reserve(len); for (int i=0; i<len; i++) { if (src[i] == '\r') { if (src[i+1] == '\n') { // "\r\n" Windows i++; } } else if (src[i] == '\n') { if (src[i+1] == '\r') { // "\n\r" Mac ? i++; } } else { if (subLen == 0) { subStart = i; } subLen ++; continue; } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } dest.Append(replacement); } if (subLen > 0) { dest.Append(&src[subStart], subLen); } } void HotlistParser::ConvertToNewline(OpString &dest, const uni_char* src) { int subLen = 0; int subStart = 0; int len = src ? uni_strlen(src) : 0; //Fix for bug [184935] The length of a note is unlimited, notes can be very large // Necessary to reserve buffer to avoid unneccesary Grow's in // OpString. dest.Reserve(len); for (int i=0; i<len; i++) { if (src[i] == 2) { if (src[i+1] == 2) { i++; } } else { if (subLen == 0) { subStart = i; } subLen ++; continue; } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } dest.Append(NEWLINE); } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } } void HotlistParser::ConvertFromComma(OpString &dest, const uni_char* src, const uni_char* replacement) { int subLen = 0; int subStart = 0; int len = src ? uni_strlen(src) : 0; for (int i=0; i<len; i++) { if (src[i] != ',') { if (subLen == 0) { subStart = i; } subLen ++; continue; } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } dest.Append(replacement); } if (subLen > 0) { dest.Append(&src[subStart], subLen); } } void HotlistParser::ConvertToComma(OpString &dest, const uni_char* src) { int subLen = 0; int subStart = 0; int len = src ? uni_strlen(src) : 0; for (int i=0; i<len; i++) { if (src[i] == 2) { if (src[i+1] == 2) { i++; } } else { if (subLen == 0) { subStart = i; } subLen ++; continue; } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } dest.Append(UNI_L(",")); } if (subLen > 0) { dest.Append(&src[subStart], subLen); subLen = 0; } } BOOL HotlistParser::GetNetscapeTagValue(const uni_char* haystack, const uni_char* tag, OpString &value) { if (haystack && tag) { int tag_len = uni_strlen(tag); const uni_char *p = uni_stristr(haystack, tag); if (p && p[tag_len] == '=') { int i=0; int num_ranges = 0; int range[2]={-1,-1}; for (i=tag_len; p[i]; i++) { if (p[i] == '"') { range[num_ranges++] = i; if (num_ranges == 2) { break; } } } if (num_ranges == 2) { int length = range[1]-range[0]-1; if (length > 0) { value.Set(&p[range[0]+1], length); } return TRUE; } } } return FALSE; } BOOL HotlistParser::GetNetscapeDescription(const uni_char* haystack, OpString &value) { if (haystack) { const uni_char* p1 = uni_stristr(haystack, UNI_L("<BR>")); if (p1) { int length = uni_strlen(haystack)-(p1-haystack); if (length > 0) { value.Set(haystack, length); } return TRUE; } else { value.Set(haystack); return FALSE; } } return FALSE; } BookmarkItem* HotlistParser::AddNewBookmarkFolder(const uni_char* name,INT32 created,INT32 visited) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); if(item) { item->SetFolderType(FOLDER_NORMAL_FOLDER); if(name) SetAttribute(item, BOOKMARK_TITLE, name); if(created) SetAttribute(item, BOOKMARK_CREATED, created); if(visited) SetAttribute(item, BOOKMARK_VISITED, visited); if (OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { m_stack.Push(item); } else { OP_DELETE(item); item = 0; } } return item; } BookmarkItem* HotlistParser::AddNewBookmark(const uni_char* name, const uni_char* url , INT32 created , INT32 visited ) { BookmarkItem* item = OP_NEW(BookmarkItem, ()); if(item) { item->SetFolderType(FOLDER_NO_FOLDER); if(name) SetAttribute(item, BOOKMARK_TITLE, name); if(url) SetAttribute(item, BOOKMARK_URL, url); if(created) SetAttribute(item, BOOKMARK_CREATED, created); if(visited) SetAttribute(item, BOOKMARK_VISITED, visited); if (!OpStatus::IsSuccess(DesktopBookmarkManager::AddCoreItem(item, /*previous?*/ 0, m_stack.Peek() ? m_stack.Peek() : 0))) { OP_DELETE(item); item = 0; } } return item; }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/testapp.h> #include <vespa/vespalib/stllike/string.h> #include <vespa/document/base/documentid.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/searchcore/proton/server/executor_thread_service.h> #include <vespa/searchlib/common/lambdatask.h> #include <vespa/searchcore/proton/reference/i_gid_to_lid_change_listener.h> #include <vespa/searchcore/proton/reference/gid_to_lid_change_handler.h> #include <map> #include <vespa/log/log.h> LOG_SETUP("gid_to_lid_change_handler_test"); using document::GlobalId; using document::DocumentId; using search::makeLambdaTask; namespace proton { namespace { GlobalId toGid(vespalib::stringref docId) { return DocumentId(docId).getGlobalId(); } vespalib::string doc1("id:test:music::1"); } class ListenerStats { using lock_guard = std::lock_guard<std::mutex>; std::mutex _lock; uint32_t _changes; uint32_t _createdListeners; uint32_t _registeredListeners; uint32_t _destroyedListeners; public: ListenerStats() : _lock(), _changes(0u), _createdListeners(0u), _registeredListeners(0u), _destroyedListeners(0u) { } ~ListenerStats() { EXPECT_EQUAL(_createdListeners, _destroyedListeners); } void notifyGidToLidChange() { lock_guard guard(_lock); ++_changes; } void markCreatedListener() { lock_guard guard(_lock); ++_createdListeners; } void markRegisteredListener() { lock_guard guard(_lock); ++_registeredListeners; } void markDestroyedListener() { lock_guard guard(_lock); ++_destroyedListeners; } uint32_t getCreatedListeners() const { return _createdListeners; } uint32_t getRegisteredListeners() const { return _registeredListeners; } uint32_t getDestroyedListeners() const { return _destroyedListeners; } void assertCounts(uint32_t expCreatedListeners, uint32_t expRegisteredListeners, uint32_t expDestroyedListeners, uint32_t expChanges) { EXPECT_EQUAL(expCreatedListeners, getCreatedListeners()); EXPECT_EQUAL(expRegisteredListeners, getRegisteredListeners()); EXPECT_EQUAL(expDestroyedListeners, getDestroyedListeners()); EXPECT_EQUAL(expChanges, _changes); } }; class MyListener : public IGidToLidChangeListener { ListenerStats &_stats; vespalib::string _name; vespalib::string _docTypeName; public: MyListener(ListenerStats &stats, const vespalib::string &name, const vespalib::string &docTypeName) : IGidToLidChangeListener(), _stats(stats), _name(name), _docTypeName(docTypeName) { _stats.markCreatedListener(); } virtual ~MyListener() { _stats.markDestroyedListener(); } virtual void notifyGidToLidChange(GlobalId, uint32_t) override { _stats.notifyGidToLidChange(); } virtual void notifyRegistered() override { _stats.markRegisteredListener(); } virtual const vespalib::string &getName() const override { return _name; } virtual const vespalib::string &getDocTypeName() const override { return _docTypeName; } }; struct Fixture { vespalib::ThreadStackExecutor _masterExecutor; ExecutorThreadService _master; std::vector<std::shared_ptr<ListenerStats>> _statss; std::shared_ptr<GidToLidChangeHandler> _handler; Fixture() : _masterExecutor(1, 128 * 1024), _master(_masterExecutor), _statss(), _handler(std::make_shared<GidToLidChangeHandler>(&_master)) { } ~Fixture() { close(); } void close() { _master.execute(makeLambdaTask([this]() { _handler->close(); })); _master.sync(); } ListenerStats &addStats() { _statss.push_back(std::make_shared<ListenerStats>()); return *_statss.back(); } void addListener(std::unique_ptr<IGidToLidChangeListener> listener) { _handler->addListener(std::move(listener)); _master.sync(); } void notifyGidToLidChange(GlobalId gid, uint32_t lid) { _master.execute(makeLambdaTask([this, gid, lid]() { _handler->notifyGidToLidChange(gid, lid); })); _master.sync(); } void removeListeners(const vespalib::string &docTypeName, const std::set<vespalib::string> &keepNames) { _handler->removeListeners(docTypeName, keepNames); _master.sync(); } }; TEST_F("Test that we can register a listener", Fixture) { auto &stats = f.addStats(); auto listener = std::make_unique<MyListener>(stats, "test", "testdoc"); TEST_DO(stats.assertCounts(1, 0, 0, 0)); f.addListener(std::move(listener)); TEST_DO(stats.assertCounts(1, 1, 0, 0)); f.notifyGidToLidChange(toGid(doc1), 10); TEST_DO(stats.assertCounts(1, 1, 0, 1)); f.removeListeners("testdoc", {}); TEST_DO(stats.assertCounts(1, 1, 1, 1)); } TEST_F("Test that we can register multiple listeners", Fixture) { auto &stats1 = f.addStats(); auto &stats2 = f.addStats(); auto &stats3 = f.addStats(); auto listener1 = std::make_unique<MyListener>(stats1, "test1", "testdoc"); auto listener2 = std::make_unique<MyListener>(stats2, "test2", "testdoc"); auto listener3 = std::make_unique<MyListener>(stats3, "test3", "testdoc2"); TEST_DO(stats1.assertCounts(1, 0, 0, 0)); TEST_DO(stats2.assertCounts(1, 0, 0, 0)); TEST_DO(stats3.assertCounts(1, 0, 0, 0)); f.addListener(std::move(listener1)); f.addListener(std::move(listener2)); f.addListener(std::move(listener3)); TEST_DO(stats1.assertCounts(1, 1, 0, 0)); TEST_DO(stats2.assertCounts(1, 1, 0, 0)); TEST_DO(stats3.assertCounts(1, 1, 0, 0)); f.notifyGidToLidChange(toGid(doc1), 10); TEST_DO(stats1.assertCounts(1, 1, 0, 1)); TEST_DO(stats2.assertCounts(1, 1, 0, 1)); TEST_DO(stats3.assertCounts(1, 1, 0, 1)); f.removeListeners("testdoc", {"test1"}); TEST_DO(stats1.assertCounts(1, 1, 0, 1)); TEST_DO(stats2.assertCounts(1, 1, 1, 1)); TEST_DO(stats3.assertCounts(1, 1, 0, 1)); f.removeListeners("testdoc", {}); TEST_DO(stats1.assertCounts(1, 1, 1, 1)); TEST_DO(stats2.assertCounts(1, 1, 1, 1)); TEST_DO(stats3.assertCounts(1, 1, 0, 1)); f.removeListeners("testdoc2", {"test3"}); TEST_DO(stats1.assertCounts(1, 1, 1, 1)); TEST_DO(stats2.assertCounts(1, 1, 1, 1)); TEST_DO(stats3.assertCounts(1, 1, 0, 1)); f.removeListeners("testdoc2", {"foo"}); TEST_DO(stats1.assertCounts(1, 1, 1, 1)); TEST_DO(stats2.assertCounts(1, 1, 1, 1)); TEST_DO(stats3.assertCounts(1, 1, 1, 1)); } TEST_F("Test that we keep old listener when registering duplicate", Fixture) { auto &stats = f.addStats(); auto listener = std::make_unique<MyListener>(stats, "test1", "testdoc"); TEST_DO(stats.assertCounts(1, 0, 0, 0)); f.addListener(std::move(listener)); TEST_DO(stats.assertCounts(1, 1, 0, 0)); listener = std::make_unique<MyListener>(stats, "test1", "testdoc"); TEST_DO(stats.assertCounts(2, 1, 0, 0)); f.addListener(std::move(listener)); TEST_DO(stats.assertCounts(2, 1, 1, 0)); } } TEST_MAIN() { TEST_RUN_ALL(); }
#include <stdio.h> #include <math.h> int IsTheNumber ( const int N ); int main() { int n1, n2, i, cnt; scanf("%d %d", &n1, &n2); cnt = 0; for ( i=n1; i<=n2; i++ ) { if ( IsTheNumber(i) ) cnt++; } printf("cnt = %d\n", cnt); return 0; } int IsTheNumber ( const int N ){ int flag1 = 0; // 完全平方数 int flag2 = 0; // 至少两位数相同 int i = (int)sqrt(N); if ( i*i == N) flag1 = 1; int n = N > 0 ? N : -N; int cnter[10] = {0}; while(n > 0){ cnter[n % 10]++; if( cnter[n % 10] > 1 ){ flag2 = 1; break; } n /= 10; } return (flag1 && flag2) ? 1 : 0; }
#include "ManagerUtils/PlotUtils/interface/Common.hpp" #include "TriggerEfficiency/EfficiencyPlot/interface/EfficiencyPlot.h" using namespace std; extern void DrawUncEta() { TCanvas* c = mgr::NewCanvas(); TPad* top = mgr::NewTopPad(); top->Draw(); top->cd(); TH1F* h1 = gPad->DrawFrame( -3, 0.85, 3, 1 ); SetHistTitle( h1, "", "Scale Factor" ); mgr::SetTopPlotAxis( h1 ); TLegend* leg = mgr::NewLegend( 0.4, 0.18, 0.5, 0.35 ); leg->SetLineColor( kWhite ); TGraphAsymmErrors* base = HistTGraph( "base_eta", "sf_eta" ); TGraphAsymmErrors* comp = HistTGraph( "compare_eta", "sf_eta" ); base->Draw("EP"); comp->Draw("EP"); SetHist(base, kGray+1, 33); SetHist(comp, kAzure-3, 8); string era = PlotMgr().GetOption<string>( "era" ); leg->AddEntry( base, era.c_str(), "lp" ); leg->AddEntry( comp, (era+"*").c_str(), "lp" ); leg->Draw(); TPaveText* pt = mgr::NewTextBox( .45, .76, .93, .84 ); pt->AddText( PlotMgr().GetSingleData<string>( "desc" ).c_str() ); pt->Draw(); c->cd(); /**************************************************************************/ TPad* bot = mgr::NewBottomPad(); bot->Draw(); bot->cd(); TH1F* h2 = gPad->DrawFrame( -3, -0.052, 3, 0.052 ); SetHistTitle( h2, "SuperCluster #eta", "Systematic Unc" ); mgr::SetBottomPlotAxis( h2 ); h2->GetYaxis()->SetLabelSize(14); TGraphAsymmErrors* scale = DividedUncGraph( comp, base); scale->Draw("EP"); SetBottomHist(scale); TLine* line = new TLine( -3, 0, 3, 0 ); line->SetLineColor( kRed ); line->SetLineStyle( 8 ); line->Draw(); c->cd(); mgr::DrawCMSLabelOuter( PRELIMINARY ); mgr::DrawLuminosity( PlotMgr().GetOption<double>( "lumi" ) ); mgr::SaveToPDF( c, PlotMgr().GetResultsName( "pdf", "SF_eta" ) ); delete c; delete line; delete leg; delete pt; } extern void DrawUncPt() { TCanvas* c = mgr::NewCanvas(); TPad* top = mgr::NewTopPad(); top->Draw(); top->cd(); TH1F* h1 = gPad->DrawFrame( 0, 0.7, 500, 1.5 ); SetHistTitle( h1, "", "Scale Factor" ); mgr::SetTopPlotAxis( h1 ); TLegend* leg = mgr::NewLegend( 0.60, 0.45, 0.80, 0.65 ); leg->SetLineColor( kWhite ); TGraphAsymmErrors* base = HistTGraph( "base_pt", "sf_pt" ); TGraphAsymmErrors* comp = HistTGraph( "compare_pt", "sf_pt" ); base->Draw("EP"); comp->Draw("EP"); SetHist(base, kGray+1, 33); SetHist(comp, kAzure-3, 8); string era = PlotMgr().GetOption<string>( "era" ); leg->AddEntry( base, era.c_str(), "lp" ); leg->AddEntry( comp, (era+"*").c_str(), "lp" ); leg->Draw(); TPaveText* pt = mgr::NewTextBox( .45, .76, .93, .84 ); pt->AddText( PlotMgr().GetSingleData<string>( "desc" ).c_str() ); pt->Draw(); c->cd(); /**************************************************************************/ TPad* bot = mgr::NewBottomPad(); bot->Draw(); bot->cd(); TH1F* h2 = gPad->DrawFrame( 0, -0.052, 500, 0.052 ); SetHistTitle( h2, "P_{T}", "Systematic Unc" ); mgr::SetBottomPlotAxis( h2 ); h2->GetYaxis()->SetLabelSize(14); TGraphAsymmErrors* scale = DividedUncGraph( comp, base); scale->Draw("EP"); SetBottomHist(scale); TLine* line = new TLine( 0, 0, 500, 0 ); line->SetLineColor( kRed ); line->SetLineStyle( 8 ); line->Draw(); c->cd(); mgr::DrawCMSLabelOuter( PRELIMINARY ); mgr::DrawLuminosity( PlotMgr().GetOption<double>( "lumi" ) ); mgr::SaveToPDF( c, PlotMgr().GetResultsName( "pdf", "SF_pt" ) ); delete c; delete line; delete leg; delete pt; } extern TGraphAsymmErrors* DividedUncGraph( TGraphAsymmErrors* num, TGraphAsymmErrors* den ) { TGraphAsymmErrors* ans = new TGraphAsymmErrors( num->GetN() ); for( int i = 0; i < num->GetN(); ++i ){ const double numy = num->GetY()[i]; const double numyerrlo = num->GetErrorYlow( i ); const double numyerrhi = num->GetErrorYhigh( i ); const double deny = den->GetY()[i]; const double denyerrlo = den->GetErrorYlow( i ); const double denyerrhi = den->GetErrorYhigh( i ); const double numx = num->GetX()[i]; const double xerrlo = num->GetErrorXlow( i ); const double xerrhi = num->GetErrorXhigh( i ); ans->SetPoint( i, numx, (numy-deny) / deny ); ans->SetPointError( i, xerrlo, xerrhi, ErrorProp( numy, numyerrlo, deny, denyerrlo ), ErrorProp( numy, numyerrhi, deny, denyerrhi ) ); } ans->SetTitle( "" ); return ans; }
// This is the CPP file you will edit and turn in. // Also remove these comments here and add your own. // TODO: remove this comment header #include <fstream> #include <iostream> #include <string> #include "simpio.h" #include "console.h" #include "random.h" #include "strlib.h" #include "vector.h" #include "map.h" using namespace std; //Function Prototype void fileScanner(ifstream &infile,int order); void fileWriter(int order); string findSeed(void); //Named Constant const int REQUIRED_WORDS =2000; //Global Variable Map<string, Vector<char> > writterDatabase; int main() { ifstream infile; while(true){ string fileName = getLine("Please enter filename containing source text: "); infile.open(fileName.c_str()); //in order to obtain the correct file name if (!infile.fail()) break; infile.clear(); cout<<"Unable to open the file. Please try again! "<<endl; } int order = getInteger("What order of analysis (1 to 10)"); fileScanner(infile,order); fileWriter(order); return 0; } /* Function Name: fileScanner Usage: void fileWriter(ifstream in,int order) this method is firstly achieving read all txt file into a char stream. Then, according to the order entered, the keyword of map will be listed. the following char of each keyword will be added to the vector. */ void fileScanner(ifstream &infile,int order){ Vector<string> key; Vector<char> keyStream; //eof: end of file while(!infile.eof()){ keyStream.add(infile.get()); } for (int i =0; i<keyStream.size()-order; i++) { string singleKey = ""; for(int j=0;j<order;j++){ singleKey+=string(1,keyStream.get(i+j)); } if(!writterDatabase.containsKey(singleKey)){ Vector<char> possibleChoices; possibleChoices.add(keyStream.get(i+order)); writterDatabase.put(singleKey,possibleChoices); }else{ Vector<char> possibleChoices; possibleChoices= writterDatabase.get(singleKey); possibleChoices.add(keyStream.get(i+order)); writterDatabase.put(singleKey,possibleChoices); } } } /* Function Name: fileWriter Usage: void fileWriter(int) the mostly appeared keyword will be treated as seed and the next char will be selected from the vector related to keyword. then this char will combined with the previous seed except the first char to form a new seed. Until reach 2000 char, it won't finish. */ void fileWriter(int order){ cout<<"Analyzing, please wait."<<endl; string seed = findSeed(); string article = ""; article+=seed; for(int i=0;i<REQUIRED_WORDS-order;i++){ Vector<char> follower = writterDatabase.get(seed); //randomly choose one from all the followers int randomIndex =randomInteger(0, follower.size()-1); char nextChar = follower[randomIndex]; seed=seed.substr(1)+string(1,nextChar); article+=string(1,nextChar); } cout<<article<<endl; } /* Fuction Name: findSeed usage: string str = findSeed this is simply a normal find maximum problem. the only useful poing is using foreach method to iterate within a map. */ string findSeed(){ int maxFollower = 0; string seed = ""; //awesome foreach method foreach(string key in writterDatabase){ if(writterDatabase.get(key).size()>maxFollower){ maxFollower=writterDatabase.get(key).size(); seed = key; } } return seed; }
// File: HLRAppli_ReflectLines.cdl // Created: 05.12.12 15:53:35 // Created by: Julia GERASIMOVA // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRAppli_ReflectLines_HeaderFile #define _HLRAppli_ReflectLines_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <HLRAlgo_Projector.hxx> #include <HLRBRep_Algo.hxx> #include <HLRBRep_TypeOfResultingEdge.hxx> #include <TopoDS_Shape.hxx> #include <Standard_Real.hxx> //! This class builds reflect lines on a shape //! according to the axes of view defined by user. //! Reflect lines are represented by edges in 3d. class HLRAppli_ReflectLines { public: DEFINE_STANDARD_ALLOC //! Constructor Standard_EXPORT HLRAppli_ReflectLines(const TopoDS_Shape& aShape); //! Sets the normal to the plane of visualisation, //! the coordinates of the view point and //! the coordinates of the vertical direction vector. Standard_EXPORT void SetAxes (const Standard_Real Nx, const Standard_Real Ny, const Standard_Real Nz, const Standard_Real XAt, const Standard_Real YAt, const Standard_Real ZAt, const Standard_Real XUp, const Standard_Real YUp, const Standard_Real ZUp); Standard_EXPORT void Perform(); //! returns resulting compound of reflect lines //! represented by edges in 3d Standard_EXPORT TopoDS_Shape GetResult() const; //! returns resulting compound of lines //! of specified type and visibility //! represented by edges in 3d or 2d Standard_EXPORT TopoDS_Shape GetCompoundOf3dEdges(const HLRBRep_TypeOfResultingEdge type, const Standard_Boolean visible, const Standard_Boolean In3d) const; protected: private: HLRAlgo_Projector myProjector; Handle(HLRBRep_Algo) myHLRAlgo; TopoDS_Shape myShape; //TopoDS_Shape myCompound; }; #endif // _HLRAppli_ReflectLines_HeaderFile
// // Created by chris on 11/08/2017. // #include <iostream> #include "Model.h" Model::Model() { glGenVertexArrays(1, &h_vao); glGenBuffers(1, &h_vbo); glGenBuffers(1, &h_indexBuffer); } void Model::draw() { draw(GL_TRIANGLES); } void Model::draw(GLenum mode) { if(this->indexCount == 0) { glBindVertexArray(h_vao); glBindBuffer(GL_ARRAY_BUFFER, h_vbo); glDrawArrays(mode, 0, vertexCount); glBindVertexArray(0); } else { glBindVertexArray(h_vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, h_indexBuffer); glDrawElements(mode, this->indexCount, GL_UNSIGNED_INT, nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); } } void Model::setVertices(Vertex *vertices, GLuint count) { this->vertexCount = count; glBindVertexArray(h_vao); glBindBuffer(GL_ARRAY_BUFFER, h_vbo); glBufferData(GL_ARRAY_BUFFER, count * sizeof(Vertex), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *) (offsetof(Vertex, position))); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *) (offsetof(Vertex, texCoord))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *) (offsetof(Vertex, normal))); glBindVertexArray(0); } void Model::setIndices(GLuint *indices, GLuint count) { this->indexCount = count; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, h_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(GLuint), indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } Model::~Model() { glDeleteBuffers(1, &h_indexBuffer); glDeleteBuffers(1, &h_vbo); glDeleteVertexArrays(1, &h_vao); }
// Author : Gabriel Duarte // Date : 01/30/2018 // Lab # : 02 exercise 1 // Description : We are making a check board. // Include the library #include "EasyBMP.h" using namespace std; int main() { // Create an image BMP AnImage; // Set the image size AnImage.SetSize(256,256); // Set the bit depth AnImage.SetBitDepth(8); // The for loop for the rows for (int i = 0; i < 256; ++i) { // The for loop for the cols for (int j = 0; j < 256; ++j) { // Make it a red square if ((i/32)%2 == 0 && (j/32)%2 == 0) { AnImage (i,j)->Red = 255; AnImage (i,j)->Green = 0; AnImage (i,j)->Blue = 0; } else if ((j/32)%2 == 1 && (i/32)%2 == 1) { AnImage (i,j)->Red = 255; AnImage (i,j)->Green = 0; AnImage (i,j)->Blue = 0; } // Make it a black square else { AnImage (i,j)->Red = 0; AnImage (i,j)->Green = 0; AnImage (i,j)->Blue = 0; } } } // Output the image to a "file" AnImage.WriteToFile("board.bmp"); return 0; }
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; /* 0(Lgn + k) algorithm Input: K = 4, X = 35 arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56} Output: 30 39 42 45 */ int getMinPosition(int arr[], int i, int j, int k, int n) { if (i < 0) return j; if (j > n) return i; int iabs = abs(arr[i]- k); int jabs = abs(arr[j]- k); return (iabs < jabs) ? i : j; } // minimum elements that bigger or equal k int findNearestNeighbor(int arr[], int start, int end, int k, int n) { int middle = start + (end - start) / 2; if (arr[middle] == k) return middle; if (end < start) return -1; if ( (end == start) || (end == start + 1)) { return getMinPosition(arr,start, end, k,n); } if (arr[end] < k) return end; if (arr[start] > k) return start; int childK = -1; if (arr[middle] < k) { childK = findNearestNeighbor(arr, middle+ 1, end, k,n); } else if (arr[middle] > k) { childK = findNearestNeighbor(arr, start, middle-1, k,n); } if (childK != -1) { childK = getMinPosition(arr, childK, middle,k,n); } return (childK == -1) ? middle:childK; } void printKNearest(int arr[], int start, int end, int X, int k ,int n) { int kPosition = findNearestNeighbor(arr, start, end, X,n); int numElemetns = 0; if (kPosition == start) { while (numElemetns < k) { if (arr[kPosition + numElemetns] != X) cout << arr[kPosition + numElemetns] << " "; else { k++; } numElemetns++; } return; } if (kPosition == end) { while (numElemetns < k) { if (arr[kPosition - numElemetns] != X) cout << arr[kPosition - numElemetns] << " "; else { k++; } numElemetns++; } return; } int goOnLeft = 1; int goOnRight = 1; int printElement = kPosition; while (numElemetns < k) { if (arr[printElement] != X) { cout << arr[printElement] << " "; } else k++; printElement = getMinPosition(arr,kPosition-goOnLeft,kPosition + goOnRight,X,n); if(printElement == kPosition - goOnLeft) goOnLeft++; else goOnRight++; numElemetns++; } cout << "\n"; } void main() { int arr[] = {12,16,22,30,35,39,42,45,48,50,53,55,56}; int size = sizeof(arr)/ sizeof(int); int n = size - 1; int start= 0; int end = n; //int X = 15; //int X = 12; //int X = 13; //int X = 11; //int X = 35; int X = 57; printKNearest(arr,start,end,X,4,n); //cout << kPosition << "\n"; }
#include "pch.h" #include "game.h" #include <vector> game::game() { Console = new console(); gui = new GUI(*Console); Player = new player(Console, gui); ai = new AI(); } void game::startGame() { Console->cls(); gui->drawGameInterface(Player->getMyField(), Player->getEnemyField()); ai->placeShips(2); Player->placeShips(2); int delta_comentator = 0; int head_coment_x = 55; int head_coment_y = 4; bool gameOver = false; int turn = 1; while (!gameOver) { Console->cls(); gui->drawGameInterface(Player->getMyField(), Player->getEnemyField()); //gui->drawGameInterface(ai->getMyField(), ai->getEnemyField(), 60, 0); if (turn == 1) { Player->makeShot(ai); } else if (turn == 2) { std::vector<int> tmp = ai->makeShot(); int hit = Player->takeHit(tmp[0], tmp[1]); ai->analise(tmp[0], tmp[1], hit); Console->print("Computer shot at " + (char)((int)'0' + tmp[0]) + (char)((int)'A' + tmp[1]), head_coment_x, head_coment_y + delta_comentator); delta_comentator = (delta_comentator + 1) % 10; } turn = (turn % 2) + 1; gameOver = ((Player->getHP() == 0) || (ai->getHP() == 0)); } Console->cls(); if (Player->getHP() == 0) { cout << "You loose"; } else if (ai->getHP() == 0) { cout << "You win"; } cout << endl; system("pause"); menu(); } void game::menu() { Console->cls(); gui->drawMenu(); Console->change_console_view(15, 16); int choice; bool repeat = true; while (repeat) { Console->change_console_view(15, 16); cout << "Enter your choice: "; cin >> choice; switch (choice) { case 1: startGame(); repeat = false; break; case 2: settings(); repeat = false; break; case 3: system("exit"); repeat = false; break; default: break; } } } void game::settings() { } game::~game() { Console->cls(); }
#ifndef _MSG_0X28_ENTITYMETADATA_STC_H_ #define _MSG_0X28_ENTITYMETADATA_STC_H_ #include "mcprotocol_base.h" #include "metadata.h" namespace MC { namespace Protocol { namespace Msg { class EntityMetadata : public BaseMessage { public: EntityMetadata(); EntityMetadata(int32_t _entityId, Metadata _metadata); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getEntityId() const; Metadata getMetadata() const; void setEntityId(int32_t _val); void setMetadata(Metadata _val); private: int32_t _pf_entityId; Metadata _pf_metadata; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X28_ENTITYMETADATA_STC_H_
#include <chuffed/core/propagator.h> #include <chuffed/globals/EdExplFinder.h> #include <iostream> class EditDistance : public Propagator { public: enum ExplLevel { // generate naive explanation if all seq variables are fixed only E_NAIVE, // generate explanation on any domain change, E_FULL, }; int max_char; // maximum cost of any insertion/deletion operation int max_id_cost; // minimum cost of any insertion/deletion operation int min_id_cost; vec<int> insertion_cost; vec<int> deletion_cost; vec<int> substitution_cost; int const seqSize; IntView<>* const seq1; IntView<>* const seq2; IntView<> const ed; const ExplLevel explLevel = E_FULL; Tint lastBound; // Persistent state // // Intermediate state // EditDistance(int _max_char, vec<int>& _insertion_cost, vec<int>& _deletion_cost, vec<int>& _substitution_cost, vec<IntView<> > _seq1, vec<IntView<> > _seq2, IntView<> _ed) : max_char(_max_char), insertion_cost(_insertion_cost), deletion_cost(_deletion_cost), substitution_cost(_substitution_cost), seqSize(_seq1.size()), seq1(_seq1.release()), seq2(_seq2.release()), ed(_ed), dpMatrix(vec<int>((seqSize + 1) * (seqSize + 1))), cellHasChanged(vec<int>(seqSize * 2)) { // get maximum costs over all insertions/deletions max_id_cost = 0; for (int i = 0; i < max_char; i++) { max_id_cost = std::max(max_id_cost, insertion_cost[i]); max_id_cost = std::max(max_id_cost, deletion_cost[i]); } min_id_cost = INT_MAX; for (int i = 0; i < max_char; i++) { min_id_cost = std::min(min_id_cost, insertion_cost[i]); min_id_cost = std::min(min_id_cost, deletion_cost[i]); } // set maximum possible upper bound in the beginning lastBound = seqSize * 2 * max_id_cost; cellChanges = 0; for (int i = 0; i < seqSize * 2; i++) { cellHasChanged[i] = 0; } #ifndef NDEBUG std::cout << "insertion_cost: "; for (int i = 0; i < max_char; i++) { std::cout << insertion_cost[i] << " "; } std::cout << std::endl; std::cout << "deletion_cost: "; for (int i = 0; i < max_char; i++) { std::cout << deletion_cost[i] << " "; } std::cout << std::endl; std::cout << "substitution_cost: "; for (int i = 0; i < max_char * max_char; i++) { std::cout << substitution_cost[i] << " "; } std::cout << std::endl; #endif // we set this propagator to low priority priority = 3; // attach variable views int offset = 0; for (int i = 0; i < seqSize; i++) { seq1[i].attach(this, offset + i, EVENT_C); } offset += seqSize; for (int i = 0; i < seqSize; i++) { seq2[i].attach(this, offset + i, EVENT_C); } // in the future we could also wake the propagator on changes on the edit distance offset += seqSize; ed.attach(this, offset, EVENT_L); // insert 0 values into matrices for (int i = 0; i < (seqSize + 1) * (seqSize + 1); i++) { dpMatrix[i] = 0; } } void wakeup(int i, int c) override { if (i < seqSize * 2) { if (((unsigned)c & EVENT_C) != 0U) { if (cellHasChanged[i] == 0) { cellHasChanged[i] = 1; cellChanges++; } } } pushInQueue(); } bool propagate() override { // Step 1: // Update dp matrix according to change // #ifndef NDEBUG std::cout << "lastBound = " << lastBound << std::endl; std::cout << "cellChanges = " << cellChanges << std::endl; std::cout << "cellHasChanged = ["; for (int i = 0; i < seqSize * 2; i++) { std::cout << cellHasChanged[i] << " "; } std::cout << "]" << std::endl; #endif int ub = std::min(2 * seqSize * max_id_cost, lastBound + cellChanges * 2 * max_id_cost); updateDpMatrix(ub); cellChanges = 0; for (int i = 0; i < seqSize * 2; i++) { cellHasChanged[i] = 0; } #ifndef NDEBUG printCurrentDpMatrix(); #endif // Step 2: // Propagate lower bound to edit distance, and add explanation // // calc edit distance int editDistanceLB = getEditDistanceLB(); lastBound = editDistanceLB; if (ed.getMin() < editDistanceLB) { #ifndef NDEBUG std::cout << "ED " << editDistanceLB << std::endl; #endif if (explLevel == E_NAIVE) { // in case of naive explanation, check if all variables are fixed for (int i = 0; i < seqSize; i++) { if (!seq1[i].isFixed() || !seq2[i].isFixed()) { return true; } } } if (ed.setMinNotR(editDistanceLB)) { Clause* r = nullptr; if (so.lazy) { switch (explLevel) { case E_NAIVE: r = getNaiveExplanation(); break; case E_FULL: EdExplFinder edExplFinder; // launch inequality finder for explanation r = edExplFinder.FindEdExplanation(max_char, &insertion_cost, &deletion_cost, &substitution_cost, seq1, seq2, &dpMatrix, editDistanceLB, seqSize, min_id_cost); break; } if (!ed.setMin(editDistanceLB, r)) { return false; } } } } return true; } private: // The matrix will store the values for the dynamic programming matrix vec<int> dpMatrix; int cellChanges; vec<int> cellHasChanged; int getMinimumDeletionCosts(IntView<>* const iVar) { int min_deletion_costs = INT_MAX; // find minimum deletion costs for (int it : *iVar) { if (it > 0) { min_deletion_costs = std::min(min_deletion_costs, deletion_cost[it - 1]); } else { return 0; } } assert(min_deletion_costs < INT_MAX); return min_deletion_costs; } int getMinimumInsertionCosts(IntView<>* const jVar) { int min_insertion_costs = INT_MAX; // find minimum insertion costs for (int it : *jVar) { if (it > 0) { min_insertion_costs = std::min(min_insertion_costs, insertion_cost[it - 1]); } else { return 0; } } assert(min_insertion_costs < INT_MAX); return min_insertion_costs; } int getMinimumSubstitutionCost(IntView<>* const iVar, IntView<>* const jVar) { int min_substitution_costs = INT_MAX; // find minimum substitution costs for (int i_val : *iVar) { for (int j_val : *jVar) { if (i_val == 0 && j_val == 0) { return 0; } if (i_val == 0 && j_val != 0) { min_substitution_costs = std::min(min_substitution_costs, deletion_cost[j_val - 1]); } if (i_val != 0 && j_val == 0) { min_substitution_costs = std::min(min_substitution_costs, insertion_cost[i_val - 1]); } if (i_val != 0 && j_val != 0) { min_substitution_costs = std::min(min_substitution_costs, substitution_cost[substCoord(i_val, j_val)]); } } } assert(min_substitution_costs < INT_MAX); return min_substitution_costs; } void updateDpPosition(int i, int j, int d) { IntView<>* const iVar = &seq1[i - 1]; IntView<>* const jVar = &seq2[j - 1]; if (i == 0 && j == 0) { // top left position is always 0 } else if (i == 0) { int min_insertion_costs = getMinimumInsertionCosts(jVar); dpMatrix[matrixCoord(i, j)] = dpMatrix[matrixCoord(0, j - 1)] + min_insertion_costs; } else if (j == 0) { int min_deletion_costs = getMinimumDeletionCosts(iVar); dpMatrix[matrixCoord(i, j)] = dpMatrix[matrixCoord(i - 1, 0)] + min_deletion_costs; } else { int minChange = seqSize * 2 * max_id_cost; if (j - 1 >= i - d) { int min_insertion_costs = getMinimumInsertionCosts(jVar); minChange = std::min(minChange, dpMatrix[matrixCoord(i, j - 1)] + min_insertion_costs); } if (j < i + d) { int min_deletion_costs = getMinimumDeletionCosts(iVar); minChange = std::min(minChange, dpMatrix[matrixCoord(i - 1, j)] + min_deletion_costs); } if (iVar->isFixed() && jVar->isFixed() && iVar->getVal() == jVar->getVal()) { // both values fixed and equal minChange = std::min(minChange, dpMatrix[matrixCoord(i - 1, j - 1)]); } else { int minDiagonalCost = getMinimumSubstitutionCost(iVar, jVar); int diagonalCost = dpMatrix[matrixCoord(i - 1, j - 1)] + minDiagonalCost; minChange = std::min(minChange, diagonalCost); } dpMatrix[matrixCoord(i, j)] = minChange; } } int matrixCoord(int i, int j) const { return i * (seqSize + 1) + j; } int substCoord(int c1, int c2) const { return (c1 - 1) * max_char + (c2 - 1); } void updateDpMatrix(int upperBound) { // // First update regular matrix // // count num possible 0 insertions int possible_0_inserts = 0; int possible_0_deletes = 0; for (int i = 0; i < seqSize; i++) { if (seq1[i].indomain(0)) { possible_0_inserts++; } if (seq2[i].indomain(0)) { possible_0_deletes++; } } // d = distance to diagonal that should be calculated in the matrix int d = upperBound / min_id_cost + std::max(possible_0_inserts, possible_0_deletes); #ifndef NDEBUG std::cout << "d = " << d << std::endl; #endif for (int i = 0; i < seqSize + 1; i++) { int startCol = std::max(0, i - d); int endCol = std::min(seqSize, i + d); for (int j = startCol; j < endCol + 1; j++) { updateDpPosition(i, j, d); } } } int getEditDistanceLB() { // retrieve LB from dp matrix return dpMatrix[matrixCoord(seqSize, seqSize)]; } // the naive explanation will include current bounds for all variables Clause* getNaiveExplanation() const { // count number of possible values in total int clauseSize = seqSize * 2 + 1; Clause* r = Reason_new(clauseSize); int offset = 1; // insert all clauses for each variable in sequence 1 for (int i = 0; i < seqSize; i++) { // x != val (*r)[offset + i] = seq1[i].getLit(seq1[i].getVal(), LR_NE); } offset += seqSize; // insert all clauses for each variable in sequence 2 for (int i = 0; i < seqSize; i++) { // x != val (*r)[offset + i] = seq2[i].getLit(seq2[i].getVal(), LR_NE); } return r; } void printCurrentDpMatrix() { std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << std::endl; std::cout << " Sequence1: " << std::endl; for (int i = 0; i < seqSize; i++) { std::cout << "{"; for (int it : seq1[i]) { std::cout << it << ","; } if (seq1[i].isFixed()) { std::cout << "!"; } std::cout << "};"; } std::cout << std::endl; std::cout << " Sequence2: " << std::endl; for (int i = 0; i < seqSize; i++) { std::cout << "{"; for (int it : seq2[i]) { std::cout << it << ","; } if (seq2[i].isFixed()) { std::cout << "!"; } std::cout << "};"; } std::cout << std::endl; std::cout << std::endl; std::cout << " Current dp matrix: " << std::endl; std::cout << " "; for (int i = 0; i < seqSize + 1; i++) { printf("%2d ", i); } std::cout << std::endl; for (int i = 0; i < seqSize + 2; i++) { std::cout << "---"; } std::cout << std::endl; for (int i = 0; i < seqSize + 1; i++) { for (int j = -1; j < seqSize + 1; j++) { if (j == -1) { printf("%2d|", i); } else { printf("%2d ", dpMatrix[matrixCoord(i, j)]); } } std::cout << std::endl; } } }; void edit_distance(int max_char, vec<int>& insertion_cost, vec<int>& deletion_cost, vec<int>& substitution_cost, vec<IntVar*>& seq1, vec<IntVar*>& seq2, IntVar* ed) { vec<IntView<> > s1; for (int i = 0; i < seq1.size(); i++) { seq1[i]->specialiseToEL(); s1.push(IntView<>(seq1[i])); } vec<IntView<> > s2; for (int i = 0; i < seq2.size(); i++) { seq2[i]->specialiseToEL(); s2.push(IntView<>(seq2[i])); } // insert clauses to ensure 0 values appear only at the end of each sequence for (int i = 0; i < seq1.size() - 1; i++) { // x_i >= 1 v x_i+1 <= 0 vec<Lit> cl; cl.push(seq1[i]->getLit(1, LR_GE)); cl.push(seq1[i + 1]->getLit(0, LR_LE)); sat.addClause(cl); } for (int i = 0; i < seq2.size() - 1; i++) { // x_i >= 1 v x_i+1 <= 0 vec<Lit> cl; cl.push(seq2[i]->getLit(1, LR_GE)); cl.push(seq2[i + 1]->getLit(0, LR_LE)); sat.addClause(cl); } new EditDistance(max_char, insertion_cost, deletion_cost, substitution_cost, s1, s2, IntView<>(ed)); }
#ifndef RTPCLASS_H #define RTPCLASS_H #include <QThread> #include <QUdpSocket> #include <errno.h> #include <QFile> #include <QTime> #include "rtpsession.h" #include "rtpsourcedata.h" #include "rtpudpv4transmitter.h" #include "rtcpcompoundpacket.h" #include "rtcpsrpacket.h" #include "rtpipv4address.h" #include "rtppacket.h" #include "rtpsessionparams.h" #include <stdio.h> #include <iostream> #include "cv.h" #include "highgui.h" #include "h264class.h" #include <QDebug> #include <QPixmap> #include<winsock2.h> #pragma comment(lib,"ws2_32.lib")//Õâ¾ä¹Ø¼ü; using namespace std; using namespace jrtplib; typedef struct pic_data { int index; int offset; int length; unsigned char payloadType; unsigned char *buf; }pic_data; Q_DECLARE_METATYPE(pic_data) class rtpClass : public QThread,public RTPSession { Q_OBJECT public: rtpClass(QObject *parent = 0); ~rtpClass(); void startThread(); void stopThread(); void checkerror(int rtperr,char *error); void delay(unsigned long time); void initInstance(); IplImage* QImageToIplImage(const QImage * qImage); protected: bool stopped; signals: public slots: }; #endif // RTPCLASS_H
// Fill out your copyright notice in the Description page of Project Settings. #include "FightWithBlock.h" #include "MyGameState.h" #include "BlockBase.h" #include "MyStructs.h" AMyGameState::AMyGameState() { static ConstructorHelpers::FObjectFinder<UDataTable> GroundTable(TEXT("DataTable'/Game/myBlueprint/DataTables/D_Ground.D_Ground'")); static ConstructorHelpers::FObjectFinder<UDataTable> SurfaceTable(TEXT("DataTable'/Game/myBlueprint/DataTables/D_Surface.D_Surface'")); if (GroundTable.Succeeded() && SurfaceTable.Succeeded()) { GroundDataTable = GroundTable.Object; SurfaceDataTable = SurfaceTable.Object; GroundRowNames = GroundTable.Object->GetRowNames(); SurfaceRowNames = SurfaceTable.Object->GetRowNames(); } } void AMyGameState::BeginPlay() { /*GenerateGround(); if(Role == ROLE_Authority) GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("ROLE_Authority!!!!!!!!!!")); if(Role == ROLE_AutonomousProxy) GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("ROLE_AutonomousProxy!!!!!!!!!!")); if(Role == ROLE_SimulatedProxy) GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("ROLE_SimulatedProxy!!!!!!!!!!"));*/ } void AMyGameState::GenerateGround_() { if (MapSize > 100) { GEngine->AddOnScreenDebugMessage(-1, 5, FColor::Red, TEXT("MapSize is too Big!!!!!!!!!!")); return; } else { FBlock* GroundRow = NULL; int32 x = 1, y = 1, z = 1; while (z <= MaxZ) { GroundRowNames[(float)FMath::FRandRange(0.f, (float)(GroundRowNames.Num() - 1))]; GroundRow = GroundDataTable->FindRow<FBlock>(GroundRowNames[(float)FMath::FRandRange(0.f, (float)(GroundRowNames.Num() - 1))], TEXT("")); GroundRow->Position.X = x; GroundRow->Position.Y = y; GroundRow->Position.Z = z; AllBlockInfo.Add(SpawnBlock(GroundRow, BlockSize)); x += 1; if (x > MapSize) { x = 1; y += 1; if (y > MapSize) { y = 1; z += 1; } } } return; } } void AMyGameState::GenerateGround() { if (Role < ROLE_Authority) { //GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Green, TEXT("Client!!!!!!!!!!!!!!!!")); } else { //GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("Server!!!!!!!!!!!!!!!!")); ServerGenerateGround(); } } void AMyGameState::ServerGenerateGround_Implementation() { GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("Spawn!!!!!!!!!!!!!!!!")); GenerateGround_(); } bool AMyGameState::ServerGenerateGround_Validate() { return true; } ABlockBase* AMyGameState::SpawnBlock(const FBlock* Block, float Size) { //GEngine->AddOnScreenDebugMessage(-1, 50, FColor::Black, TEXT("Spawn!!!!!!!!!!!!!!!!")); FVector location = FVector(Block->Position.X * Size, Block->Position.Y * Size, Block->Position.Z * Size); UWorld* World = GetWorld(); ABlockBase* tempBlock = NULL; if (World) { tempBlock = World->SpawnActor<ABlockBase>(location, FRotator(0, 0, 0)); tempBlock->SetInitProperty(*Block); return tempBlock; } else { return tempBlock; } }
//--------------------------------------------------------- // // Project: dada // Module: core // File: common.h // Author: Viacheslav Pryshchepa // // Description: // //--------------------------------------------------------- #ifndef DADA_CORE_COMMON_H #define DADA_CORE_COMMON_H #ifndef NULL # define NULL 0 #endif namespace dada { typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; typedef signed long long int64_t; typedef unsigned long long uint64_t; typedef unsigned int size_t; } // dada #endif // DADA_CORE_COMMON_H
#include <iostream> #include <cstring> using namespace std; class Solution { public: int lengthOfLastWord(const char *s) { int result = 0; while(*s){ if(*s++ != ' ')/* increment happends here*/{ ++result; }else if(*s && *s != ' '){ result = 0; } } return result; } }; int main(){ string s1 = "hello world "; const char *s = &s1[0]; Solution *sol = new Solution(); int result = sol->lengthOfLastWord(s); cout<< result <<endl; }
#include<iostream> #include<string> using std::cin; using std::cout; using std::endl; using std::string; void swap(int &a,int &b){ a=a^b; b=a^b; a=a^b; } void swap(string &a,string &b){ string temp; temp=a; a=b; b=temp; } int main(){ int a,b; cout<<"Enter a"<<endl; cin>>a; cout<<"Enter b"<<endl; cin>>b; cout<<"Before swap a = "<<a<<" b = "<<b<<endl; swap(a,b); cout<<"After swap a = "<<a<<" b = "<<b<<endl; string c,d; cout<<"Enter First name"<<endl; cin>>c; cout<<"Enter Last name"<<endl; cin>>d; cout<<"Before swap FirstName = "<<c<<" LastName = "<<d<<endl; swap(c,d); cout<<"After swap FirstName = "<<c<<" LastName = "<<d<<endl; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "DRAnimInstance.h" #include "Dragon.h" UDRAnimInstance::UDRAnimInstance() { CurrentDragonSpeed = 0.0f; static ConstructorHelpers::FObjectFinder<UAnimMontage> ATTACK_MONTAGE(TEXT("/Game/AI/SK_DesertDragon_Skeleton_Montage.SK_DesertDragon_Skeleton_Montage")); if (ATTACK_MONTAGE.Succeeded()) { AttackMontage = ATTACK_MONTAGE.Object; } } void UDRAnimInstance::NativeUpdateAnimation(float DeltaSeconds) { Super::NativeUpdateAnimation(DeltaSeconds); auto Dragon = Cast<ADragon>(TryGetPawnOwner()); if (::IsValid(Dragon)) { CurrentDragonSpeed = Dragon->GetVelocity().Size(); //IsAlert = Dragon->GetAlert(); } } void UDRAnimInstance::PlayAttacckMontage(int32 NewSection) { if (!Montage_IsPlaying(AttackMontage)) { Montage_Play(AttackMontage, 1.0f); Montage_JumpToSection(GetAttackMontageSectionName(NewSection),AttackMontage); } } void UDRAnimInstance::AnimNotify_AttackHitCheck() { ABLOG_S(Warning); OnAttackHitCheck.Broadcast(); } void UDRAnimInstance::AnimNotify_Dash() { OnDash.Broadcast(); } void UDRAnimInstance::AnimNotify_FireBall() { OnFireBall.Broadcast(); } FName UDRAnimInstance::GetAttackMontageSectionName(int32 Section) { return FName(*FString::Printf(TEXT("Attack%d"), Section)); }
#include <iostream> #include "vector.h" using namespace std; int main() { vector vec = {1, 2, 3, 4}; vector not_a_vec = vec; vec.set(3, 1); cout << not_a_vec.get(3) << endl; return 0; }
/***************************************************************** Name :insertion_sort Author :srhuang Email :lukyandy3162@gmail.com History : 20191123 Initial Version *****************************************************************/ #include <iostream> #define DEBUG (0) #define SCALE (10000) using namespace std; using namespace std::chrono; /*==============================================================*/ //Global area /*==============================================================*/ //Function area int *random_case(int number) { int *result = new int[number]; //generate index ordered arrary for(int i=0; i<number; i++){ result[i]=i+1; } //swap each position srand(time(NULL)); for(int i=0; i<number-1; i++){ int j = i + rand() / (RAND_MAX / (number-i)); //swap int t=result[i]; result[i] = result[j]; result[j]=t; } return result; } int *worst_case(int number) { int *result = new int[number]; //generate index ordered arrary for(int i=0; i<number; i++){ result[i]=number-i; } return result; } int *best_case(int number) { int *result = new int[number]; //generate index ordered arrary for(int i=0; i<number; i++){ result[i]=i+1; } return result; } void insertion_sort(int *input, int n) { cout << endl; int count = 0; //one by one insert each element for(int i=1; i<n; i++){ int temp = input[i]; //find the position and shift the last element int j=i; while((j>0) && (temp < input[j-1])){ count++; input[j] = input[j-1]; j--; }//for j input[j] = temp; }//for i cout << "shift count :" << count << endl; } /*==============================================================*/ int main(int argc, char const *argv[]){ int n=SCALE; //generate data int *best_data = best_case(n); int *worst_data = worst_case(n); int *random_data = random_case(n); #if DEBUG cout << "Before sorting :"; for(int i=0; i<n; i++){ cout << random_data[i] << " "; } cout << endl; #endif //sort auto start = high_resolution_clock::now(); insertion_sort(random_data, n); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "Time taken by random_data: " << duration.count() << " microseconds" << endl; start = high_resolution_clock::now(); insertion_sort(best_data, n); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout << "Time taken by best_data: " << duration.count() << " microseconds" << endl; start = high_resolution_clock::now(); insertion_sort(worst_data, n); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout << "Time taken by worst_data: " << duration.count() << " microseconds" << endl; #if DEBUG cout << "\nAfter sorting :"; for(int i=0; i<n; i++){ cout << random_data[i] << " "; } cout << endl; #endif return 0; } /*==============================================================*/
#include "field.hh" #include <vector> struct subfield { pos a,b,c,d,e,f; stone A,B,C,D,E,F; subfield(){ a = not_a_position; b = not_a_position; c = not_a_position; d = not_a_position; e = not_a_position; f = not_a_position; A = EMPTY; B = EMPTY; C = EMPTY; D = EMPTY; E = EMPTY; F = EMPTY; } }; struct listmove { std::vector<pos> list; int dir; }; listmove convert2list(move m) { listmove Listmove; if (!is_equal(m.c,not_a_position) ) Listmove.list.push_back(m.c); if (!is_equal(m.b,not_a_position) ) Listmove.list.push_back(m.b); Listmove.list.push_back(m.a); Listmove.dir=m.dir; return Listmove; } move convert2unsorted(listmove m) { move M; if (m.list.size()>2) {M.c=m.list[2];} if (m.list.size()>1) {M.b=m.list[1];} if (m.list.size()>0) {M.a=m.list[0];} return M; } void do_move(field& f, move m) { // first try if the move is valid... (to be implemented) subfield oldfield; oldfield.a=m.a; oldfield.b=m.b; oldfield.c=m.c; pos a = m.a; pos b = m.b; pos c = m.c; int dir = m.dir; pos temp = a; pos backtemp = a; stone player = f.get_stone(a.a, a.b); // suche nach erster freien Position in dir do { temp = add_pos(temp, unitvec[dir]); } while (f.get_stone(temp.a,temp.b) != 0); // verschiebe alle Steine bis Pos a while (not (is_equal(temp,a))) { backtemp = sub_pos(temp, unitvec[dir]); f.set_stone(temp.a, temp.b, f.get_stone(backtemp.a,backtemp.b)); temp = sub_pos(temp, unitvec[dir]); }; // verschiebe die drei Steine pos next_a = add_pos(a, unitvec[dir]); pos next_b = add_pos(b, unitvec[dir]); pos next_c = add_pos(c, unitvec[dir]); // zero the old positions if(is_valid_pos(a)) f.set_stone(a.a, a.b, EMPTY); if(is_valid_pos(b)) f.set_stone(b.a, b.b, EMPTY); if(is_valid_pos(c)) f.set_stone(c.a, c.b, EMPTY); // set new positions if(is_valid_pos(a)) f.set_stone(next_a.a, next_a.b, player); if(is_valid_pos(b)) f.set_stone(next_b.a, next_b.b, player); if(is_valid_pos(c)) f.set_stone(next_c.a, next_c.b, player); }
#include <iostream> #include <gL\glew.h> #include <gl\glfw3.h> #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include "Game.h" using namespace std; #define RED 1.0f, 0.0f, 0.0f #define GREEN 0.0f, 1.0f, 0.0f #define BLUE 0.0f, 0.0f, 1.0f #define BLACK 0.0f, 0.0f, 0.0f Game *game; int keyPressed = -1; double MouseXPos = -1.0; double MouseYPos = -1.0; void SpecialKeyPressed(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS || GLFW_REPEAT) keyPressed = key; if (keyPressed == GLFW_KEY_RIGHT) game->view_matrix *= glm::translate(20.0f, 0.0f, 0.0f); if (keyPressed == GLFW_KEY_LEFT) game->view_matrix *= glm::translate(-20.0f, 0.0f, 0.0f); if (keyPressed == GLFW_KEY_UP) game->view_matrix *= glm::translate(0.0f, 20.0f, 0.0f); if (keyPressed == GLFW_KEY_DOWN) game->view_matrix *= glm::translate(0.0f, -20.0f, 0.0f); if (keyPressed == GLFW_KEY_Q) game->view_matrix *= glm::rotate(10.0f, glm::vec3(0.0f, 1.0f, 0.0f)); if (keyPressed == GLFW_KEY_E) game->view_matrix *= glm::rotate(-10.0f, glm::vec3(0.0f, 1.0f, 0.0f)); if (keyPressed == GLFW_KEY_W) game->view_matrix *= glm::translate(0.0f, 0.0f, 20.0f); if (keyPressed == GLFW_KEY_S) game->view_matrix *= glm::translate(0.0f, 0.0f, -20.0f);; } void MouseClicked(GLFWwindow* window, int button, int action, int mods) { if (action == GLFW_MOUSE_BUTTON_LEFT) glfwGetCursorPos(window, &MouseXPos, &MouseYPos); } int main() { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //OpenGL version 3. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // 3.3 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(1024, 720, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glfwSwapInterval(1); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK){ cout << "ERROR!"; return 0; } GLCall(glEnable(GL_DEPTH_TEST)); GLCall(glDepthFunc(GL_LESS)); GLCall(glEnable(GL_BLEND)); GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetKeyCallback(window, &SpecialKeyPressed); glfwSetMouseButtonCallback(window, &MouseClicked); game = new Game(); game->Initialize(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ game->Draw(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
// // main.cpp // 1256 // // Created by Pedro Neves Alvarez on 7/8/17. // Copyright © 2017 Pedro Neves Alvarez. All rights reserved. // #include <iostream> #include <vector> using namespace std; int main(int argc, const char * argv[]) { int tests,cut,tam,n; cout << "Enter the test cases"; cin >> tests; for(int i = 0; i<tests;i++){ if(i) cout << endl; cin >> cut >> tam; vector<int> hashv[cut]; vector<int>::iterator iter; for(int j=0;j<tam;j++){ cin>>n; hashv[n%cut].push_back(n); } for(int j=0;j<cut;j++){ cout<<j; for(iter=hashv[j].begin();iter!=hashv[j].end();iter++){ cout << " -> " << *iter; } cout << " -> \\" << endl; } } return 0; }
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * 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 xWorkshop Inc. 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. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #include "xnet_message.hxx" #include "xnet_message_ids.hxx" #include "xassert.hxx" #include "xnetwork.hxx" #include "xlogger.hxx" #include "xlocale.hxx" namespace xws { xnet_message_ids& xnet_message::net_message_ids() { static xnet_message_ids mids; return mids; } xnet_message_ptr xnet_message::create_message(xmid_t id) { id_to_creator_t& id_2_creator = id_to_creator(); xnet_message_creator_t creator = id_2_creator[id]; if (creator) { xnet_message_ptr message((*creator)()); if (message) { message->set_id(id); return message; } } // static xnet_message_ptr none; return none; } xnet_message_ptr xnet_message::create_message(const xstring& name) { const xnet_message_ids& mids = net_message_ids(); return create_message(mids.id_of(name)); } xnet_message::xnet_message(xversion_t version) : xversionable(version) { } xnet_message::~xnet_message() { } bool xnet_message::to_byte_array(xbyte_array& byte_array) { xdata_stream stream(&byte_array); // Move to the end just in case of byte_array is not empty stream.seek(0, seek_end); // This is the old size, will be overwritten later std::size_t size = byte_array.size(); stream << size << id() << version(); if (this->to_data_stream(stream)) { // Move back to the postition where size should be located stream.seek(size, seek_beg); // Delta size should be written size = byte_array.size() - size; // Overwrite the size field stream << size; return true; } return false; } xnet_message_set xnet_message::from_byte_array(const xbyte_array& byte_array, xsize_t* consumed_size) { xnet_message_set set; xdata_stream stream(byte_array); xsize_t recognized_size = 0; while (!stream.at_end()) { xsize_t size = 0; xsize_t begin_pos = stream.pos(); stream >> size; xdebug_info(xchar_format(xtr(_X("byte_array.size() = {1}, size read from stream = {2}."))) % byte_array.size() % size); if (size == 0 || size > byte_array.size()) { xdebug_info(_X("The size indicates in the stream is not correct.")); } else { xmid_t id = 0; xversion_t version = 0; stream >> id >> version; xnet_message_ptr message = create_message(id); if (message) { message->set_version(version); if (message->from_data_stream(stream)) { xsize_t end_pos = stream.pos(); xsize_t stream_offset = end_pos - begin_pos; // Stream goes exactly the same steps as that of a message size // Otherwise it is not a correct message if (stream_offset == size) { set.push_back(xnet_message_ptr(message)); recognized_size += size; } else { xdebug_info(xchar_format(xtr(_X("The size of message (= {1}) does not match that read out from stream (= {2})."))) % size % stream_offset); } } } else { xdebug_info(xchar_format(xtr(_X("Failed to create a message with id = {1}."))) % id); } } } if (consumed_size) { *consumed_size = recognized_size; } return set; } void xnet_message::register_creator(const xstring& klass, xnet_message_creator_t creator) { xdebug_info(xchar_format(xtr(_X("Registering creator for message \"{1}\"..."))) % klass); xnet_message_ids& mids = net_message_ids(); xmid_t id = mids.id_of(klass); xassert(id != INVALID_XMID); id_to_creator_t& id_2_creator = id_to_creator(); id_2_creator.insert(id_to_creator_t::value_type(id, creator)); } id_to_creator_t& xnet_message::id_to_creator() { static id_to_creator_t id_2_creator; return id_2_creator; } } // namespace xws
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.String.h> #include <Uno.UX.Property-1.h> namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct app18_ButtonEntryMyCoupon_Price_Property;} namespace g{struct ButtonEntryMyCoupon;} namespace g{ // internal sealed class app18_ButtonEntryMyCoupon_Price_Property :482 // { ::g::Uno::UX::Property1_type* app18_ButtonEntryMyCoupon_Price_Property_typeof(); void app18_ButtonEntryMyCoupon_Price_Property__ctor_3_fn(app18_ButtonEntryMyCoupon_Price_Property* __this, ::g::ButtonEntryMyCoupon* obj, ::g::Uno::UX::Selector* name); void app18_ButtonEntryMyCoupon_Price_Property__Get1_fn(app18_ButtonEntryMyCoupon_Price_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString** __retval); void app18_ButtonEntryMyCoupon_Price_Property__New1_fn(::g::ButtonEntryMyCoupon* obj, ::g::Uno::UX::Selector* name, app18_ButtonEntryMyCoupon_Price_Property** __retval); void app18_ButtonEntryMyCoupon_Price_Property__get_Object_fn(app18_ButtonEntryMyCoupon_Price_Property* __this, ::g::Uno::UX::PropertyObject** __retval); void app18_ButtonEntryMyCoupon_Price_Property__Set1_fn(app18_ButtonEntryMyCoupon_Price_Property* __this, ::g::Uno::UX::PropertyObject* obj, uString* v, uObject* origin); void app18_ButtonEntryMyCoupon_Price_Property__get_SupportsOriginSetter_fn(app18_ButtonEntryMyCoupon_Price_Property* __this, bool* __retval); struct app18_ButtonEntryMyCoupon_Price_Property : ::g::Uno::UX::Property1 { uWeak< ::g::ButtonEntryMyCoupon*> _obj; void ctor_3(::g::ButtonEntryMyCoupon* obj, ::g::Uno::UX::Selector name); static app18_ButtonEntryMyCoupon_Price_Property* New1(::g::ButtonEntryMyCoupon* obj, ::g::Uno::UX::Selector name); }; // } } // ::g
#include "utils.h" PVOID utility::get_kernel_module_by_name(char* moduleName) { ULONG pool_size = 0; NTSTATUS status = ZwQuerySystemInformation(0xB, nullptr, 0, &pool_size); if (status != STATUS_INFO_LENGTH_MISMATCH) return 0; PSYSTEM_MODULE_INFORMATION system_module_info = (PSYSTEM_MODULE_INFORMATION)ExAllocatePool(NonPagedPool, pool_size); if (!system_module_info) return 0; status = ZwQuerySystemInformation(0xB, system_module_info, pool_size, nullptr); if (!NT_SUCCESS(status)) ExFreePool(system_module_info); PVOID address = 0; for (unsigned int i = 0; i < system_module_info->NumberOfModules; i++) { SYSTEM_MODULE module_entry = system_module_info->Modules[i]; if (strstr((char*)module_entry.FullPathName, moduleName)) address = module_entry.ImageBase; } ExFreePool(system_module_info); return address; } // https://github.com/not-wlan/driver-hijack modified it a bit NTSTATUS utility::find_driver_object(PDRIVER_OBJECT* DriverObject, PUNICODE_STRING DriverName) { HANDLE handle{}; OBJECT_ATTRIBUTES attributes{}; UNICODE_STRING directory_name{}; PVOID directory{}; BOOLEAN success = FALSE; RtlInitUnicodeString(&directory_name, L"\\Driver"); InitializeObjectAttributes(&attributes, &directory_name, OBJ_CASE_INSENSITIVE, NULL, NULL); NTSTATUS status = ZwOpenDirectoryObject(&handle, DIRECTORY_ALL_ACCESS, &attributes); if (!NT_SUCCESS(status)) return status; status = ObReferenceObjectByHandle(handle, DIRECTORY_ALL_ACCESS, nullptr, KernelMode, &directory, nullptr); if (!NT_SUCCESS(status)) { ZwClose(handle); return status; } POBJECT_DIRECTORY directory_object = POBJECT_DIRECTORY(directory); ExAcquirePushLockExclusiveEx(&directory_object->Lock, 0); for (POBJECT_DIRECTORY_ENTRY entry : directory_object->HashBuckets) { if (!entry) continue; if (success) break; while (entry && entry->Object) { PDRIVER_OBJECT driver = PDRIVER_OBJECT(entry->Object); if (RtlCompareUnicodeString(&driver->DriverName, DriverName, FALSE) == 0) { *DriverObject = driver; success = TRUE; } entry = entry->ChainLink; } } ExReleasePushLockExclusiveEx(&directory_object->Lock, 0); ObDereferenceObject(directory); ZwClose(handle); return success == TRUE ? STATUS_SUCCESS : STATUS_NOT_FOUND; } NTSTATUS utility::memory::read_virtual_memory(PKERNEL_MEMORY_REQUEST memory_request) { PEPROCESS process; SIZE_T bytes; NTSTATUS status = PsLookupProcessByProcessId((HANDLE)memory_request->pid, &process); if (!NT_SUCCESS(status)) return status; status = MmCopyVirtualMemory(process, memory_request->source, PsGetCurrentProcess(), memory_request->buffer, memory_request->size, UserMode, &bytes); ObDereferenceObject(process); return status; } NTSTATUS utility::memory::write_virtual_memory(PKERNEL_MEMORY_REQUEST memory_request) { PEPROCESS process; SIZE_T bytes; NTSTATUS status = PsLookupProcessByProcessId((HANDLE)memory_request->pid, &process); if (!NT_SUCCESS(status)) return status; status = MmCopyVirtualMemory(PsGetCurrentProcess(), memory_request->buffer, process, memory_request->source, memory_request->size, UserMode, &bytes); ObDereferenceObject(process); return status; }
#include <stdio.h> int main(){ char strings[3][10] = {"Hello","World","Doodle"}; char *p_str[3]; for(int i=0; i<3; i++){ p_str[i] = strings[i]; } for(int i=0; i< 3; i++){ printf("%s", strings[i]); printf("%s", &strings[i][0]); printf("%s", p_str[i]); printf("\n"); } }
#include <iostream> using namespace std; int main(){ int input; cin >> input; if(input > 100000){ return 0; } for(int i = 1; i <= input; i++){ cout << i << "\n"; } return 0; }
/* * @Description: tf监听模块 * @Author: Ren Qian * @Date: 2020-02-06 16:10:31 */ #include "lidar_localization/tf_listener/tf_listener.hpp" #include <Eigen/Geometry> namespace lidar_localization { TFListener::TFListener(ros::NodeHandle& nh, std::string base_frame_id, std::string child_frame_id) :nh_(nh), base_frame_id_(base_frame_id), child_frame_id_(child_frame_id) { } bool TFListener::LookupData(Eigen::Matrix4f& transform_matrix) { try { tf::StampedTransform transform; listener_.lookupTransform(base_frame_id_, child_frame_id_, ros::Time(0), transform); TransformToMatrix(transform, transform_matrix); return true; } catch (tf::TransformException &ex) { return false; } } bool TFListener::TransformToMatrix(const tf::StampedTransform& transform, Eigen::Matrix4f& transform_matrix) { Eigen::Translation3f tl_btol(transform.getOrigin().getX(), transform.getOrigin().getY(), transform.getOrigin().getZ()); double roll, pitch, yaw; tf::Matrix3x3(transform.getRotation()).getEulerYPR(yaw, pitch, roll); Eigen::AngleAxisf rot_x_btol(roll, Eigen::Vector3f::UnitX()); Eigen::AngleAxisf rot_y_btol(pitch, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf rot_z_btol(yaw, Eigen::Vector3f::UnitZ()); // 此矩阵为 child_frame_id 到 base_frame_id 的转换矩阵 transform_matrix = (tl_btol * rot_z_btol * rot_y_btol * rot_x_btol).matrix(); return true; } }
// // nehe16.cpp // NeheGL // // Created by Andong Li on 9/15/13. // Copyright (c) 2013 Andong Li. All rights reserved. // #include "nehe16.h" const char* NEHE16::TITLE = "NEHE16"; GLfloat NEHE16::sleepTime = 0.0f; int NEHE16::frameCounter = 0; int NEHE16::currentTime = 0; int NEHE16::lastTime = 0; char NEHE16::FPSstr[15] = "Calculating..."; GLuint NEHE16::texture[3] = {0,0,0}; GLuint NEHE16::filter = 0; //use first filter as default GLfloat NEHE16::xrot = 0.0f; GLfloat NEHE16::yrot = 0.0f; GLfloat NEHE16::xspeed = 0.0f; GLfloat NEHE16::yspeed = 0.0f; GLfloat NEHE16::z = -5.0f; GLfloat NEHE16::LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f }; GLfloat NEHE16::LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat NEHE16::LightPosition[]= { 0.0f, 0.0f, 2.0f, 1.0f }; bool NEHE16::light = false; bool NEHE16::lp = false; bool NEHE16::fp = false; bool NEHE16::gp = false; bool NEHE16::keys[256] = {}; //all set to false bool NEHE16::specialKeys[256] = {}; //all set to false GLuint NEHE16::fogMode[3]= { GL_EXP, GL_EXP2, GL_LINEAR }; GLuint NEHE16::fogfilter= 0; GLfloat NEHE16::fogColor[4]= {0.5f, 0.5f, 0.5f, 1.0f}; GLvoid NEHE16::ReSizeGLScene(GLsizei width, GLsizei height){ // Prevent A Divide By Zero By if(height==0) { height=1; } // Reset The Current Viewport glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } bool NEHE16::LoadGLTextures(const char* dir){ int imageWidth, imageHeight; //load image, using SOIL unsigned char* image = SOIL_load_image(Utils::getAbsoluteDir(dir),&imageWidth,&imageHeight,0,0); if(image == NULL){ return false; } glGenTextures(3, &texture[0]); // Create Three Textures // Create Nearest Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); // Create Linear Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[1]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image); // Create MipMapped Filtered Texture glBindTexture(GL_TEXTURE_2D, texture[2]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST); gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, imageWidth, imageHeight, GL_RGB, GL_UNSIGNED_BYTE, image); //free loaded texture image SOIL_free_image_data(image); return true; } GLvoid NEHE16::InitGL(){ //give the relative directory of image under current project folder if(!LoadGLTextures("NeheGL/img/crate.png")){ cout<<"Fail to load textures"<<endl; } // Enable Texture Mapping glEnable(GL_TEXTURE_2D); // Enables Smooth Shading glShadeModel(GL_SMOOTH); // clear background as black glClearColor(0.5f,0.5f,0.5f,1.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // want the best perspective correction to be done glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light glEnable(GL_LIGHT1); // Enable Light One glFogi(GL_FOG_MODE, fogMode[fogfilter]); // Fog Mode glFogfv(GL_FOG_COLOR, fogColor); // Set Fog Color glFogf(GL_FOG_DENSITY, 0.35f); // How Dense Will The Fog Be glHint(GL_FOG_HINT, GL_DONT_CARE); // Fog Hint Value glFogf(GL_FOG_START, 1.0f); // Fog Start Depth glFogf(GL_FOG_END, 5.0f); // Fog End Depth glEnable(GL_FOG); // Enables GL_FOG } GLvoid NEHE16::DrawGLScene(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0f,0.0f,z); // Translate Into/Out Of The Screen By z glRotatef(xrot,1.0f,0.0f,0.0f); // Rotate On The X Axis By xrot glRotatef(yrot,0.0f,1.0f,0.0f); // Rotate On The Y Axis By yrot glBindTexture(GL_TEXTURE_2D, texture[filter]); // Select Our Texture glBegin(GL_QUADS); // Front Face glNormal3f( 0.0f, 0.0f, 1.0f); // Normal Pointing Towards Viewer glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 1 (Front) glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 2 (Front) glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Front) glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 4 (Front) // Back Face glNormal3f( 0.0f, 0.0f,-1.0f); // Normal Pointing Away From Viewer glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Back) glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 2 (Back) glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 3 (Back) glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 4 (Back) // Top Face glNormal3f( 0.0f, 1.0f, 0.0f); // Normal Pointing Up glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 1 (Top) glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 2 (Top) glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Top) glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 4 (Top) // Bottom Face glNormal3f( 0.0f,-1.0f, 0.0f); // Normal Pointing Down glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Bottom) glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 2 (Bottom) glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 3 (Bottom) glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 4 (Bottom) // Right face glNormal3f( 1.0f, 0.0f, 0.0f); // Normal Pointing Right glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Point 1 (Right) glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); // Point 2 (Right) glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); // Point 3 (Right) glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Point 4 (Right) // Left Face glNormal3f(-1.0f, 0.0f, 0.0f); // Normal Pointing Left glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); // Point 1 (Left) glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Point 2 (Left) glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Point 3 (Left) glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); // Point 4 (Left) glEnd(); //draw FPS text glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glLoadIdentity (); glTranslatef(0.0f,0.0f,-1.0f); glColor3f(0.8f,0.8f,0.8f);//set text color computeFPS(); Utils::drawText(-0.54f,-0.4f, GLUT_BITMAP_HELVETICA_12, FPSstr); if (light){ glEnable(GL_LIGHTING); } glEnable(GL_TEXTURE_2D); glutSwapBuffers(); xrot += xspeed; // Add xspeed To xrot yrot += yspeed; // Add yspeed To yrot // handle key actions if(keys['l'] && !lp){ lp=TRUE; light=!light; if (!light){ glDisable(GL_LIGHTING); } else{ glEnable(GL_LIGHTING); } } if(!keys['l']){ lp=FALSE; } if(keys['f'] && !fp){ fp=TRUE; filter = (filter + 1) % 3; } if(!keys['f']){ fp=FALSE; } if (keys['g'] && !gp){ gp=TRUE; fogfilter = (fogfilter + 1) % 3; glFogi (GL_FOG_MODE, fogMode[fogfilter]); } if (!keys['g']){ gp=FALSE; } if(specialKeys[GLUT_KEY_PAGE_UP]){ z-=0.02f; } if(specialKeys[GLUT_KEY_PAGE_DOWN]){ z+=0.02f; } if (specialKeys[GLUT_KEY_UP]){ xspeed-=0.01f; } if (specialKeys[GLUT_KEY_DOWN]){ xspeed+=0.01f; } if (specialKeys[GLUT_KEY_RIGHT]){ yspeed+=0.01f; } if (specialKeys[GLUT_KEY_LEFT]){ yspeed-=0.01f; } } /* This function is used to limit FPS for smooth animation */ GLvoid NEHE16::UpdateScene(int flag){ clock_t startTime = clock(); glutPostRedisplay(); clock_t endTime = clock(); //compute sleep time in millesecond float sleepTime = ((CLOCKS_PER_SEC/EXPECT_FPS)-(endTime-startTime))/1000.0; //sleepTime = floor(sleepTime+0.5); sleepTime < 0 ? sleepTime = 0 : NULL; glutTimerFunc(sleepTime, UpdateScene, flag); } GLvoid NEHE16::KeyboardFuction(unsigned char key, int x, int y){ keys[key] = true; } GLvoid NEHE16::KeyboardUpFuction(unsigned char key, int x, int y){ keys[key] = false; } GLvoid NEHE16::KeySpecialFuction(int key, int x, int y){ specialKeys[key] = true; } GLvoid NEHE16::KeySpecialUpFuction(int key, int x, int y){ specialKeys[key] = false; } void NEHE16::computeFPS(){ frameCounter++; currentTime=glutGet(GLUT_ELAPSED_TIME); if (currentTime - lastTime > FPS_UPDATE_CAP) { sprintf(FPSstr,"FPS: %4.2f",frameCounter*1000.0/(currentTime-lastTime)); lastTime = currentTime; frameCounter = 0; } }
/* IBM_PROLOG_BEGIN_TAG */ /* * Copyright 2003,2016 IBM International Business Machines Corp. * * 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. */ /* IBM_PROLOG_END_TAG */ #ifndef _Cevent_H #define _Cevent_H #ifdef __HTX_LINUX__ #include <sys/sem.h> #endif class CcreateEvent { // member data private: char eventname[32]; ARGS_T *ArgDataP; int id; key_t key; // key for this sempahpore event. // The wait must do two operations on my one event. // first it waits for sem to be 0.. Then it resets to one // for the next access of the sem_wait call. struct sembuf op_wait[2]; // the signal call to semop only has to do the one operation.. // it sets the value of the semaphore to 0.. or decrements it. struct sembuf op_signal[1]; // This struct is used by semctl to set and get sem value and // remove the semaphores... #ifndef __HTX_LINUX__ union semun { int val; struct semid_ds *buf; ushort *array; } semctl_arg; #else /* * Linux defines it in sys/sem.h */ union semun semctl_arg; #endif int init_event; // member functions public: // constructor and destructor. NOTE: passing ptr to function. // LPDWORD is defined in windef.h its ulong * 32 bits. CcreateEvent( int ManReset, // TRUE if manual, FALSE auto reset int Signaled, // TRUE for initial signaled. // signaled means the wait is // satisfied. char *name, ARGS_T *ArgDataPtr); ~CcreateEvent(); DWORD WaitEvent(DWORD timeout); void SignalEvent(); // in aix sets sem to 0. in nt signals event. int sem_create(int initval); void sem_remove(); void display_value(); void SetEvent(); // sets sem to 1. int GetEvent(); // Gets the value of the semaphore. }; #endif
/********************************************************************** * * Filename: timer.h * * Description: Header file for the Intel 8018xEB Timer class. * * Notes: * * * Copyright (c) 1998 by Michael Barr. This software is placed into * the public domain and may be used for any purpose. However, this * notice must not be changed or removed and no warranty is either * expressed or implied by its publication or distribution. **********************************************************************/ #ifndef _TIMER_H #define _TIMER_H #include "mutex.h" enum TimerState { Idle, Active, Done }; enum TimerType { OneShot, Periodic }; class Timer { public: Timer(); ~Timer(); int start(unsigned int nMilliseconds, TimerType = OneShot); int waitfor(); void cancel(); TimerState state; TimerType type; unsigned int length; unsigned int count; Timer * pNext; Mutex * pMutex; // Just planning ahead for Chapter 9. private: static void interrupt Interrupt(); }; #endif /* _TIMER_H */
class CfgPatches { class ad_interaction_sys { units[] = {"adint_logic"}; magazines[] = {}; requiredVersion = 0.1; requiredAddons[] = {"A3_Modules_F","CBA_Extended_EventHandlers","CBA_MAIN","ace_main"}; author= "[101st.AD] Jay"; authorUrl = "http://www.airborne-division.de"; version = 1.0.3; versionStr = "1.0.3"; versionAr[] = {1,0,3}; versionDesc = "ADINT"; versionAct = ""; }; }; class CfgFactionClasses { class airborne_milsim_class; class airborne_milsim: airborne_milsim_class { displayName = "Airborne Division MilSim"; priority = 10; }; }; class CfgVehicles { class Module_F; class adint_logic : Module_F { displayName = "Civilian Interaction System"; icon = "ad_interaction_sys\data\logo.paa"; picture = "ad_interaction_sys\data\logo.paa"; category = "airborne_milsim"; priority = 1; scope = 2; author = "[101st.AD] Jay"; class Eventhandlers { init = "[] execvm '\ad_interaction_sys\config.sqf';[] execvm '\ad_interaction_sys\system\fn_systemInit.sqf'"; }; }; }; #include "functions.h" #include "adintVehicles.hpp" /* class CfgVehicles { class CAManBase; class Civilian: CAManBase {}; { class ACE_Actions { class ACE_MainActions { selection = ""; distance = 5; condition = 1; class ADINT_NAME { selection = ""; displayName = "Tell of what name you have"; distance = 4; condition = "[_this select 0] call adint_fnc_systemIsAlive"; statement = "[_this select 0] call adint_fnc_interactionName"; showDisabled = 0; exceptions = {}; priority = 5; icon = ""; }; }; }; }; };
/* Name: Graham Atlee Course: csc1720 Date: 10/24/19 Location of program: ~/csc1720/Labs/lab9 This is implemenation code for methods in the unordedArrayListType. These functions override pure virtual functions from the base class. */ #include <iostream> #include "unorderedArrayListType.h" using namespace std; void unorderedArrayListType::insertAt(int location, int insertItem) { if (location < 0 || location >= maxSize) cout << "The position of the item to be inserted " << "is out of range." << endl; else if (length >= maxSize) //list is full cout << "Cannot insert in a full list" << endl; else { for (int i = length; i > location; i--) list[i] = list[i - 1]; //move the elements down list[location] = insertItem; //insert the item at //the specified position length++; //increment the length } } //end insertAt void unorderedArrayListType::insertFirst(int insertItem) { const int firstPos = 0; int temp; if(length >= maxSize) cout << "Cannot insert in a full list." << endl; else insertAt(firstPos, insertItem); } //end insertFirst void unorderedArrayListType::insertEnd(int insertItem) { if (length >= maxSize) //the list is full cout << "Cannot insert in a full list." << endl; else { list[length] = insertItem; //insert the item at the end length++; //increment the length } } //end insertEnd int unorderedArrayListType::seqSearch(int searchItem) const { int loc; bool found = false; loc = 0; while (loc < length && !found) if (list[loc] == searchItem) found = true; else loc++; if (found) return loc; else return -1; } //end seqSearch void unorderedArrayListType::remove(int removeItem) { int loc; if (length == 0) cout << "Cannot delete from an empty list." << endl; else { loc = seqSearch(removeItem); if (loc != -1) removeAt(loc); else cout << "The item to be deleted is not in the list." << endl; } } //end remove void unorderedArrayListType::removeAll(int removeItem) { int count = 0; //run through get a count of remove Item for(int i = 0; i < length; i++) if(list[i] == removeItem) count++; //run a for loop with the length being the count for(int i = 0; i < count; i++) remove(removeItem); } //end removeAll void unorderedArrayListType::removeAt(int location) { int endPos, swap; const int firstPos = 0; //first do a check to make sure we have valid value if (location < 0 || location >= length) cout << "The location of the item to be removed " << "is out of range." << endl; else if(location == 0){ //at beginning of list we can swap last element to save time endPos = listSize() - 1; //get last index retrieveAt(endPos, swap); //get the value at the last index replaceAt(firstPos, swap); //set it at first position length--; //adjust the length } else { //shift the entire array if not at the beginning for (int i = location; i < length - 1; i++) list[i] = list[i+1]; length--; } } //end removeAt void unorderedArrayListType::replaceAt(int location, int repItem) { if (location < 0 || location >= length) cout << "The location of the item to be " << "replaced is out of range." << endl; else list[location] = repItem; } //end replaceAt unorderedArrayListType::unorderedArrayListType(int size) : arrayListType(size) { } //end constructor
/***************************************************************************************************************** * File Name : minimumDistanceTwoNumbers.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page05\minimumDistanceTwoNumbers.h * Created on : Jan 8, 2014 :: 1:44:45 AM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef MINIMUMDISTANCETWONUMBERS_H_ #define MINIMUMDISTANCETWONUMBERS_H_ unsigned int minimumDistanceTwoNumbersON2(vector<int> userInput,int firstNumber,int secondNumber){ if(userInput.size() == 0){ return 0; } unsigned int minDistance = UINT_MAX; for(unsigned int outerCounter = 0;outerCounter < userInput.size();outerCounter++){ if(userInput[outerCounter] == firstNumber || userInput[firstNumber] == secondNumber){ for(unsigned int innerCounter = outerCounter+1;innerCounter < userInput.size();innerCounter++){ if(userInput[innerCounter] == (userInput[outerCounter] ^ firstNumber ^ secondNumber)){ minDistance = min(minDistance,innerCounter - outerCounter); } } } } return minDistance; } unsigned int minimumDistanceTwoNumberON(vector<int> userInput,int firstNumber,int secondNumber){ if(userInput.size() == 0){ return 0; } unsigned int minDistance = UINT_MAX; unsigned int prevIndex = -1; for(unsigned int counter = 0;counter < userInput.size();counter++){ if(userInput[counter] == firstNumber || userInput[counter] == secondNumber){ if(prevIndex == -1){ prevIndex = counter; }else{ if(userInput[prevIndex] == userInput[counter]){ prevIndex = counter; }else{ minDistance = min(minDistance,counter - prevIndex); prevIndex = counter; } } } } return minDistance; } #endif /* MINIMUMDISTANCETWONUMBERS_H_ */ /************************************************* End code *******************************************************/
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #include "FPSpaceInvaders.h" #include "FPSpaceInvaders.generated.inl" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, FPSpaceInvaders, "FPSpaceInvaders" );
#include<bits/stdc++.h> using namespace std; int main(){ int N,M; cin >> N >> M; int A[N]; double sum = 0; for(int i =0; i<N; i++){ cin >> A[i]; sum += A[i]; } sum /= 4 *M; int count = 0; for(int i =0; i<N; i++){ if(A[i] >= sum)count++; } if(count >= M)cout<< "Yes"<< endl; else cout << "No" << endl; }
#include <iberbar/Utility/Xml/RapidXml.h> #include <iberbar/Utility/String.h> #include <iostream> #include <rapidxml.hpp> #include <rapidxml_print.hpp> #include <rapidxml_utils.hpp> namespace iberbar { namespace Xml { typedef rapidxml::xml_node< TCHAR > RapidContextNode; typedef rapidxml::file< CHAR > RapidXmlFileContext; typedef rapidxml::xml_document< TCHAR > RapidXmlDocumentContext; class CRapidXmlDocument; class CRapidXmlNode; class CRapidXmlNodeList; class CRapidXmlDocument : public CDocument { public: CRapidXmlDocument(); virtual ~CRapidXmlDocument(); public: virtual CResult create( const TCHAR* rootnode ); virtual CResult loadFromFile( const TCHAR* filename ); virtual CResult loadFromString( const TCHAR* source ); virtual CResult save( const TCHAR* filename ); virtual void close(); virtual CResult getRoot( CNode** ppRootNode ); protected: #ifdef UNICODE PTR_PointerCharW m_pData; #endif RapidXmlFileContext* m_file; RapidXmlDocumentContext* m_doc; }; class CRapidXmlNode : public CNode { public: CRapidXmlNode( CRapidXmlDocument* parent, RapidContextNode* node ); virtual ~CRapidXmlNode() override; public: virtual CResult selectSimgleNode( const TCHAR* pzTagName, CNode** ppNode ) override; virtual CResult selectNodes( const TCHAR* pzTagName, CNodeList** ppNodeList ) override; virtual CResult appendChild( const TCHAR* pzTagName, CNode** ppNode ) override; virtual CResult deleteChild( CNode* pNode ) override; virtual CResult setAttribute( const TCHAR* pzAttrName, const TCHAR* pzAttrValue ) override; virtual const TCHAR* getAttribute( const TCHAR* pzAttrName ) override; virtual CResult setValueText( const TCHAR* value ) override; virtual const TCHAR* getValueText() override; virtual const TCHAR* nameText() override; private: CRapidXmlDocument* m_document; RapidContextNode* m_node_context; }; class CRapidXmlNodeList : public CNodeList { public: CRapidXmlNodeList( CRapidXmlDocument* document ); virtual ~CRapidXmlNodeList() override; public: virtual void getNodeAt( int nIndex, CNode** ppNode ) override; virtual int getNodeCount() override; void addNode( CRapidXmlNode* pNode ); private: CRapidXmlDocument * m_document; std::vector< CRapidXmlNode* > m_nodes; }; } } iberbar::Xml::CRapidXmlDocument::CRapidXmlDocument() : CDocument() , m_file( nullptr ) , m_doc( nullptr ) { } iberbar::Xml::CRapidXmlDocument::~CRapidXmlDocument() { SAFE_DELETE( this->m_file ); SAFE_DELETE( this->m_doc ); } iberbar::CResult iberbar::Xml::CRapidXmlDocument::create( const TCHAR* rootnode ) { return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlDocument::loadFromFile( const TCHAR* filepath ) { assert( m_file == nullptr ); assert( m_doc == nullptr ); assert( filepath && filepath[ 0 ] != 0 ); try { #ifdef UNICODE PTR_PointerCharA filepath_0 = UnicodeToUtf8_Pointer( filepath ); m_file = new RapidXmlFileContext( filepath_0->getPointerConst() ); m_doc = new RapidXmlDocumentContext(); m_pData = Utf8ToUnicode_Pointer( m_file->data() ); m_doc->parse<0>( m_pData->GetPointer() ); #else m_file = new RapidXmlFileContext( filepath ); m_doc = new RapidXmlDocumentContext(); m_doc->parse<0>( m_file->data() ); #endif } catch ( std::exception exc ) { CResult result; result.code = ResultCode::Bad; result.Format( "Exception of parsing: %s", exc.what() ); return result; } return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlDocument::loadFromString( const TCHAR* ) { return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlDocument::save( const TCHAR* filepath ) { return CResult(); } void iberbar::Xml::CRapidXmlDocument::close() { } iberbar::CResult iberbar::Xml::CRapidXmlDocument::getRoot( iberbar::Xml::CNode** ppNode ) { CResult result; RapidContextNode* node_context = this->m_doc->first_node(); PTR_CNode node; if ( node_context ) node.attach( new CRapidXmlNode( this, node_context ) ); else result = CResult( ResultCode::Bad, "" ); if ( ppNode ) { if ( *ppNode ) (*ppNode)->release(); (*ppNode) = node; if ( *ppNode ) (*ppNode)->addRef(); } return result; } iberbar::Xml::CRapidXmlNode::CRapidXmlNode( CRapidXmlDocument* parent, RapidContextNode* node_context ) : CNode() , m_document( parent ) , m_node_context( node_context ) { this->m_document->addRef(); } iberbar::Xml::CRapidXmlNode::~CRapidXmlNode() { UNKNOWN_SAFE_RELEASE_NULL( this->m_document ); } iberbar::CResult iberbar::Xml::CRapidXmlNode::selectSimgleNode( const TCHAR* tag, CNode** ppNode ) { assert( tag && tag[ 0 ] != 0 ); CResult result; RapidContextNode* node_context = this->m_node_context->first_node( tag ); PTR_CNode node = nullptr; if ( node_context ) node.attach( new CRapidXmlNode( this->m_document, node_context ) ); else result = CResult( ResultCode::Bad, "" ); if ( ppNode ) { if ( *ppNode ) (*ppNode)->release(); (*ppNode) = node; if ( *ppNode ) (*ppNode)->addRef(); } return result; } iberbar::CResult iberbar::Xml::CRapidXmlNode::selectNodes( const TCHAR* tag, CNodeList** ppNodeList ) { assert( tag && tag[ 0 ] != 0 ); if ( ppNodeList ) UNKNOWN_SAFE_RELEASE_NULL( *ppNodeList ); RapidContextNode* node_context = this->m_node_context->first_node( tag ); if ( node_context == nullptr ) return CResult( ResultCode::Bad, "" ); PTR_CNodeList nodelist; nodelist.attach( new CRapidXmlNodeList( this->m_document ) ); CRapidXmlNodeList* nodelist_ptr = (CRapidXmlNodeList*)((CNodeList*)nodelist); while ( node_context ) { nodelist_ptr->addNode( new CRapidXmlNode( this->m_document, node_context ) ); node_context = node_context->next_sibling( tag ); } if ( ppNodeList ) { (*ppNodeList) = nodelist; (*ppNodeList)->addRef(); } return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlNode::appendChild( const TCHAR* tag, CNode** ppNode ) { return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlNode::deleteChild( CNode* node ) { return CResult(); } iberbar::CResult iberbar::Xml::CRapidXmlNode::setAttribute( const TCHAR* attrName, const TCHAR* attrValue ) { return CResult(); } const TCHAR* iberbar::Xml::CRapidXmlNode::getAttribute( const TCHAR* attrName ) { rapidxml::xml_attribute< TCHAR >* attr_context = this->m_node_context->first_attribute( attrName ); if ( attr_context == nullptr ) return nullptr; return attr_context->value(); } iberbar::CResult iberbar::Xml::CRapidXmlNode::setValueText( const TCHAR* value ) { return CResult(); } const TCHAR* iberbar::Xml::CRapidXmlNode::getValueText() { return nullptr; } const TCHAR* iberbar::Xml::CRapidXmlNode::nameText() { return nullptr; } iberbar::Xml::CRapidXmlNodeList::CRapidXmlNodeList( CRapidXmlDocument* document ) : CNodeList() , m_document( document ) , m_nodes() { this->m_document->addRef(); } iberbar::Xml::CRapidXmlNodeList::~CRapidXmlNodeList() { std::vector< CRapidXmlNode* >::iterator lc_iter = m_nodes.begin(); std::vector< CRapidXmlNode* >::iterator lc_end = m_nodes.end(); for ( ; lc_iter != lc_end; lc_iter ++ ) UNKNOWN_SAFE_RELEASE_NULL( *lc_iter ); UNKNOWN_SAFE_RELEASE_NULL( this->m_document ); } void iberbar::Xml::CRapidXmlNodeList::getNodeAt( int index, CNode** ppNode ) { assert( index >= 0 && index < this->getNodeCount() ); (*ppNode) = m_nodes[ index ]; (*ppNode)->addRef(); } int iberbar::Xml::CRapidXmlNodeList::getNodeCount() { return (int)this->m_nodes.size(); } void iberbar::Xml::CRapidXmlNodeList::addNode( CRapidXmlNode* node ) { assert( node ); this->m_nodes.push_back( node ); } iberbar::Xml::PTR_CDocument iberbar::Xml::CreateRapidXmlDocument() { PTR_CDocument doc; doc.attach( new CRapidXmlDocument() ); return doc; }
#pragma once #include "stdafx.h" #include "dice.h" dice::dice(int val) { value = val; int vl; vl = val; model = models[vl - 1]; } void dice::change_value(double val) { value = val; int vl; vl = val; model = models[vl - 1]; } ostream& operator <<(std::ostream& out, dice& dc) { out << dc.model; return out; }
#include<bits/stdc++.h> #define rep(i, s, n) for (int i = (s); i < (int)(n); i++) #define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/ #define MOD 1000000007 using namespace std; using ll = long long; using Graph = vector<vector<int>>; using pint = pair<int,int>; const double PI = 3.14159265358979323846; const int dx[4] = {1,0,-1,0}; const int dy[4] = {0,1,0,-1}; stack<int>st; int solve (string str){ int a,b; b = st.top(); st.pop(); a = st.top(); st.pop(); if(str == "+")return a + b; else if(str == "-")return a - b; else return a * b; } int main(){ string S; while(cin >> S){ if(S == "+" || S == "-" || S == "*"){ st.push(solve(S)); } else st.push(atoi(S.c_str())); } cout << st.top() << endl; return 0; }
#pragma once #include "Common/GeomMath.h" #include <yaml-cpp/yaml.h> namespace YAML { template<> struct convert<Vector2f> { static Node encode(const Vector2f& rhs) { Node node; node.push_back(rhs[0]); node.push_back(rhs[1]); node.SetStyle(EmitterStyle::Flow); return node; } static bool decode(const Node& node, Vector2f& rhs) { if(!node.IsSequence() || node.size() != 2) { return false; } rhs[0] = node[0].as<float>(); rhs[1] = node[1].as<float>(); return true; } }; template<> struct convert<Vector3f> { static Node encode(const Vector3f& rhs) { Node node; node.push_back(rhs[0]); node.push_back(rhs[1]); node.push_back(rhs[2]); node.SetStyle(EmitterStyle::Flow); return node; } static bool decode(const Node& node, Vector3f& rhs) { if(!node.IsSequence() || node.size() != 3) { return false; } rhs[0] = node[0].as<float>(); rhs[1] = node[1].as<float>(); rhs[2] = node[2].as<float>(); return true; } }; template<> struct convert<Vector4f> { static Node encode(const Vector4f& rhs) { Node node; node.push_back(rhs[0]); node.push_back(rhs[1]); node.push_back(rhs[2]); node.push_back(rhs[3]); node.SetStyle(EmitterStyle::Flow); return node; } static bool decode(const Node& node, Vector4f& rhs) { if(!node.IsSequence() || node.size() != 4) { return false; } rhs[0] = node[0].as<float>(); rhs[1] = node[1].as<float>(); rhs[2] = node[2].as<float>(); rhs[3] = node[3].as<float>(); return true; } }; }
#pragma once /* * Lanq(Lan Quick) * Solodov A. N. (hotSAN) * 2016 * LqPtdArr (LanQ ProTecteD ARRay) - Multithread array. */ #include "LqOs.h" #include "LqAlloc.hpp" #include "LqShdPtr.hpp" #include <vector> #include <type_traits> #include <functional> #pragma pack(push) #pragma pack(LQSTRUCT_ALIGN_MEM) template<typename TypeVal> class LqPtdArr { friend class interator; static const bool IsDebug = false; struct Arr { size_t CountPointers; intptr_t Count; TypeVal Val[1]; }; static void Del(Arr* Val) { for(auto* i = Val->Val, *m = i + Val->Count; i < m; i++) i->~TypeVal(); LqMemFree(Val); } typedef LqShdPtr<Arr, Del, true, false> GlobPtr; typedef LqShdPtr<Arr, Del, false, false> LocalPtr; GlobPtr Ptr; static Arr* AllocNew() { struct _st { size_t CountPointers; intptr_t Count; }; static _st __Empty = {5, 0}; return (Arr*)&__Empty; } static Arr* AllocNew(size_t Count) { Arr* Res; if(Res = (Arr*)LqMemAlloc(Count * sizeof(TypeVal) + (sizeof(Arr) - sizeof(TypeVal)))) { Res->Count = Count; Res->CountPointers = 0; } return Res; } template<typename _SetVal> bool _AddByArr(const _SetVal* Val, intptr_t Count) { auto Cur = Ptr.NewStart(); intptr_t NewCount = Cur->Count + Count; auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return false; } intptr_t i = 0; for(auto m = Cur->Count; i < m; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); for(size_t j = 0; i < NewCount; i++, j++) new(NewArr->Val + i) TypeVal(Val[j]); Ptr.NewFin(NewArr); return true; } template<typename _SetVal> bool _SetByArr(const _SetVal* Val, intptr_t Count) { auto Cur = Ptr.NewStart(); auto NewCount = Count; auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return false; } for(size_t i = 0; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Val[i]); Ptr.NewFin(NewArr); return true; } size_t _RmCount(intptr_t MinCount, intptr_t Count, LqPtdArr& Dest) { size_t Res = 0; auto Cur = Ptr.NewStart(); intptr_t NewCount = Cur->Count - Count; if(NewCount < MinCount) { NewCount = MinCount; if(NewCount == Cur->Count) { Ptr.NewFin(Cur); return 0; } } if(NewCount <= ((intptr_t)0)) { Dest.append(Cur->Val, Cur->Count); Res = Cur->Count; Ptr.NewFin(AllocNew()); return Res; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return 0; } intptr_t i = 0; for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); Dest.append(Cur->Val + i, Cur->Count - i); Res = Cur->Count - NewCount; Ptr.NewFin(NewArr); return Res; } size_t _RmCount(intptr_t MinCount, intptr_t Count) { size_t Res = 0; auto Cur = Ptr.NewStart(); intptr_t NewCount = Cur->Count - Count; if(NewCount < MinCount) { NewCount = MinCount; if(NewCount == Cur->Count) { Ptr.NewFin(Cur); return 0; } } if(NewCount <= 0) { Res = Cur->Count; Ptr.NewFin(AllocNew()); return Res; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return 0; } for(intptr_t i = 0; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); Res = Cur->Count - NewCount; Ptr.NewFin(NewArr); return Res; } size_t _RmCount(intptr_t MinCount, intptr_t Count, std::function<void(TypeVal* Rest, size_t RestCount, TypeVal* Removed, size_t RemovedCount)> LockedFunc) { size_t Res = 0; auto Cur = Ptr.NewStart(); intptr_t NewCount = Cur->Count - Count; if(NewCount < MinCount) { NewCount = MinCount; if(NewCount == Cur->Count) { Ptr.NewFin(Cur); return 0; } } if(NewCount <= 0) { Res = Cur->Count; Ptr.NewFin(AllocNew()); return Res; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return 0; } intptr_t i = 0; for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); LockedFunc(Cur->Val, NewCount, Cur->Val + i, Cur->Count - i); Res = Cur->Count - NewCount; Ptr.NewFin(NewArr); return Res; } public: class interator { friend LqPtdArr; LocalPtr Ptr; size_t Index; template<typename PtrType> inline interator(const PtrType& NewPtr, size_t NewIndex = 0): Ptr(NewPtr), Index(NewIndex) {} public: inline interator(): Ptr(AllocNew()), Index(size_t(-1)) {} inline interator(const interator& NewPtr) : Ptr(NewPtr.Ptr), Index(NewPtr.Index) {} inline interator& operator=(const interator& NewPtr) { Ptr.Set(NewPtr.Ptr); Index = NewPtr.Index; return *this; } //Preincrement inline interator& operator++() { ++Index; return (*this); } inline interator operator++(int) { ++Index; return *this; } inline interator& operator--() { --Index; return (*this); } inline interator operator--(int) { --Index; return *this; } inline TypeVal& operator*() const { return Ptr->Val[Index]; } inline TypeVal& operator[](size_t Index) const { return Ptr->Val[this->Index + Index]; } inline TypeVal* operator->() const { return &Ptr->Val[Index]; } inline interator operator+(int Add) const { return interator(Ptr, Index + Add); } inline interator operator-(int Sub) const { return interator(Ptr, Index - Sub); } inline interator& operator+=(size_t Add) { Index += Add; return (*this); } inline interator& operator-=(size_t Sub) { Index -= Sub; return (*this); } inline bool operator!=(const interator& Another) const { if(Another.Index == size_t(-1)) return Index != Ptr->Count; return (Ptr != Another.Ptr) || (Index != Another.Index); } inline bool operator==(const interator& Another) const { if(Another.Index == size_t(-1)) return Index == Ptr->Count; return (Ptr == Another.Ptr) && (Index == Another.Index); } inline size_t size() const { return Ptr->Count; } inline bool is_end() const { return Index >= Ptr->Count; } inline void set_end() { Index = TypeIndex(-1); } }; inline LqPtdArr(): Ptr(AllocNew()) {} inline LqPtdArr(const LqPtdArr& Val) : Ptr(Val.Ptr) {} template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline LqPtdArr(const std::initializer_list<InType> _Ax) : Ptr(AllocNew()) { _SetByArr(_Ax.begin(), _Ax.size()); } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline LqPtdArr(const std::vector<InType>& _Ax) : Ptr(AllocNew()) { _SetByArr(_Ax.data(), _Ax.size()); } inline LqPtdArr(TypeVal&& _Ax) : Ptr(AllocNew()) { push_back(_Ax); } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline LqPtdArr& operator=(const std::initializer_list<InType> Val) { _SetByArr(Val.begin(), Val.size()); return *this; } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline LqPtdArr& operator=(const std::vector<InType>& Val) { _SetByArr(Val.data(), Val.size()); return *this; } inline LqPtdArr& operator=(const LqPtdArr& Val) { Ptr.Set(Val.Ptr); return *this; } inline interator begin() const { return Ptr; } inline interator end() const { return interator(); } inline interator back() const { interator i = Ptr; return i + (i.size() - 1); } template<typename InType, typename = decltype(std::declval<TypeVal>() == std::declval<InType>())> interator search(InType&& SrchVal) const { interator LocPtr(Ptr, size_t(-1)); auto* Val = LocPtr.Ptr->Val; for(size_t i = 0, m = LocPtr.Ptr->Count; i < m; i++) { if(Val[i] == SrchVal) { LocPtr.Index = i; return LocPtr; } } return interator(); } interator search_next(interator Prev) const { interator LocPtr(Prev.Ptr); auto* Val = LocPtr.Ptr->Val; auto& v = Val[Prev.Index]; for(size_t i = Prev.Index + 1, m = LocPtr.Ptr->Count; i < m; i++) { if(Val[i] == v) { LocPtr.Index = i; return LocPtr; } } return interator(); } size_t append(interator& Start, interator& End) { if(IsDebug) { if(Start.Ptr != End.Ptr) throw "LqPtdArr::append(interator, interator): Interatrs points to different arrays. (Check threads race cond)\n"; } if(_AddByArr(&*Start, End.Index - Start.Index)) return End.Index - Start.Index; return 0; } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> size_t append(const std::initializer_list<InType> Start) { return _AddByArr(Start.begin(), Start.size()) ? Start.size() : 0; } size_t append(interator& Start) { if(_AddByArr(&*Start, Start.Ptr->Count - Start.Index)) return Start.Ptr->Count - Start.Index; return 0; } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline size_t append(const std::vector<InType>& Val) { return _AddByArr(Val.data(), Val.size()) ? Val.size() : 0; } inline size_t append(const LqPtdArr& Val) { return append(Val.begin()); } template<typename InType, typename = decltype(TypeVal(std::declval<InType>()))> inline size_t append(const InType* Val, size_t Count) { return _AddByArr(Val, Count) ? Count : 0; } inline size_t unappend(size_t Count, size_t MinCount = 0) { return _RmCount(MinCount, Count); } inline size_t unappend(size_t Count, size_t MinCount, LqPtdArr& Dest) { return _RmCount(MinCount, Count, Dest); } inline size_t unappend(size_t Count, size_t MinCount, std::function<void(TypeVal* Rest, size_t RestCount, TypeVal* Removed, size_t RemovedCount)> LockedFunc) { return _RmCount(MinCount, Count, LockedFunc); } inline void swap(LqPtdArr& AnotherVal) { Ptr.Swap(AnotherVal.Ptr); } template< typename InType, typename = decltype(TypeVal(std::declval<InType>())) > inline bool push_back(InType&& NewVal) { return _AddByArr(&NewVal, 1); } template< typename InType, typename = decltype(std::declval<TypeVal>() == std::declval<InType>()), typename = decltype(TypeVal(std::declval<InType>())) > int push_back_uniq(InType&& NewVal) { auto Cur = Ptr.NewStart(); for(size_t m = Cur->Count, i = 0; i < m; i++) if(Cur->Val[i] == NewVal) { Ptr.NewFin(Cur); return 0; } intptr_t NewCount = Cur->Count + 1; auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return -1; } intptr_t i = 0; for(auto m = Cur->Count; i < m; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); new(NewArr->Val + i) TypeVal(NewVal); Ptr.NewFin(NewArr); return 1; } template< typename InType, typename InType2, typename = decltype(std::declval<TypeVal>() == std::declval<InType>()), typename = decltype(TypeVal(std::declval<InType2>())) > int replace(InType&& PrevVal, InType2&& NewVal) { auto Cur = Ptr.NewStart(); intptr_t RmIndex = -1; for(intptr_t i = 0, m = Cur->Count; i < m; i++) { if(Cur->Val[i] == PrevVal) { RmIndex = i; break; } } if(RmIndex == -1) { Ptr.NewFin(Cur); return 0; } intptr_t NewCount = Cur->Count; auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return -1; } intptr_t i = 0; for(; i < RmIndex; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); new(NewArr->Val + i++) TypeVal(NewVal); for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); Ptr.NewFin(NewArr); return 1; } inline bool pop_back() { return _RmCount(1) == 1; } template< typename InType, typename = decltype(std::declval<TypeVal>() == std::declval<InType>()) > inline bool remove_by_val(InType&& RmVal) { return remove_by_val<TypeVal>(RmVal, nullptr); } template< typename TypeGetVal, typename InType, typename = decltype(std::declval<TypeVal>() == std::declval<InType>()), typename = decltype(TypeGetVal(std::declval<TypeVal>())) > bool remove_by_val(InType&& RmVal, TypeGetVal* RemovedVal) { auto Cur = Ptr.NewStart(); intptr_t RmIndex = -1; for(intptr_t i = 0, m = Cur->Count; i < m; i++) { if(Cur->Val[i] == RmVal) { RmIndex = i; break; } } if(RmIndex == -1) { Ptr.NewFin(Cur); return false; } intptr_t NewCount = Cur->Count - 1; if(NewCount <= 0) { Ptr.NewFin(AllocNew()); return true; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return false; } intptr_t i = 0; for(; i < RmIndex; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); if(RemovedVal != nullptr) *RemovedVal = Cur->Val[i]; for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i + 1]); Ptr.NewFin(NewArr); return true; } template< typename InType, typename = decltype(std::declval<TypeVal>() == std::declval<InType>()) > intptr_t remove_mult_by_val(InType&& RmVal) { auto Cur = Ptr.NewStart(); intptr_t RmCount = 0; for(intptr_t i = 0, m = Cur->Count; i < m; i++) { if(Cur->Val[i] == RmVal) RmCount++; } if(RmCount == 0) { Ptr.NewFin(Cur); return 0; } intptr_t NewCount = Cur->Count - RmCount; if(NewCount <= 0) { Ptr.NewFin(AllocNew()); return RmCount; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return 0; } intptr_t i = 0; for(intptr_t j = 0; j < Cur->Count; j++) if(!(Cur->Val[j] == RmVal)) new(NewArr->Val + i++) TypeVal(Cur->Val[j]); NewArr->Count = i; Ptr.NewFin(NewArr); return RmCount; } inline bool remove_by_compare_fn(std::function<bool(TypeVal&)> CompareFn) { return remove_by_compare_fn<TypeVal>(CompareFn, nullptr); } template< typename TypeGetVal, typename = decltype(TypeGetVal(std::declval<TypeVal>())) > bool remove_by_compare_fn(std::function<bool(TypeVal&)> CompareFn, TypeGetVal* RemovedVal) { auto Cur = Ptr.NewStart(); intptr_t RmIndex = -((intptr_t)1); for(intptr_t i = 0, m = Cur->Count; i < m; i++) { if(CompareFn(Cur->Val[i])) { RmIndex = i; break; } } if(RmIndex == -((intptr_t)1)) { Ptr.NewFin(Cur); return false; } intptr_t NewCount = Cur->Count - ((intptr_t)1); if(NewCount <= 0) { Ptr.NewFin(AllocNew()); return true; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { Ptr.NewFin(Cur); return false; } intptr_t i = 0; for(; i < RmIndex; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); if(RemovedVal != nullptr) *RemovedVal = Cur->Val[i]; for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i + 1]); Ptr.NewFin(NewArr); return true; } size_t remove_mult_by_compare_fn(std::function<bool(TypeVal&)> CompareFn) { auto Cur = Ptr.NewStart(); auto NewArr = AllocNew(Cur->Count); if(NewArr == nullptr) { Ptr.NewFin(Cur); return 0; } intptr_t i = 0, j = 0; for(; j < Cur->Count; j++) { if(!CompareFn(Cur->Val[j])) new(NewArr->Val + i++) TypeVal(Cur->Val[j]); } NewArr->Count = i; Ptr.NewFin(NewArr); return j - i; } void begin_locket_enum(const TypeVal ** Arr, intptr_t* Count) const { auto Cur = ((LqPtdArr*)this)->Ptr.NewStart(); *Count = Cur->Count; *Arr = Cur->Val; } void end_locket_enum(intptr_t RmIndex) const { auto Cur = Ptr.Get(); if(RmIndex == -((intptr_t)1)) { ((LqPtdArr*)this)->Ptr.NewFin(Cur); return; } intptr_t NewCount = Cur->Count - 1; if(NewCount <= 0) { ((LqPtdArr*)this)->Ptr.NewFin(AllocNew()); return; } auto NewArr = AllocNew(NewCount); if(NewArr == nullptr) { ((LqPtdArr*)this)->Ptr.NewFin(Cur); return; } intptr_t i = 0; for(; i < RmIndex; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i]); for(; i < NewCount; i++) new(NewArr->Val + i) TypeVal(Cur->Val[i + 1]); ((LqPtdArr*)this)->Ptr.NewFin(NewArr); } int clear() { auto Res = Ptr.NewStart()->Count; Ptr.NewFin(AllocNew()); return Res; } size_t size() const { const LocalPtr p = Ptr; return p->Count; } }; #pragma pack(pop)
/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2009 Whit Armstrong // // // // 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 3 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////////// #ifndef MCMC_HYPERPRIOR_HPP #define MCMC_HYPERPRIOR_HPP #include <cppmc/mcmc.specialized.hpp> namespace CppMC { template<typename DataT, template<typename> class ArmaT> class HyperPrior : public MCMCSpecialized<DataT,ArmaT> { public: // init w/ existing armadillo object HyperPrior(const ArmaT<DataT>& shape) : MCMCSpecialized<DataT,ArmaT>(shape) {}; // init w/ scalar (assumes vec is ArmaT, b/c mat can't be initialized w/ 'x(1)') HyperPrior(const DataT value) : MCMCSpecialized<DataT,ArmaT>(ArmaT<DataT>(1)) { MCMCSpecialized<DataT,ArmaT>::value_[0] = value; }; void getParents(std::vector<MCMCObject*>& parents) const {} void jump() {} void update() {} void preserve() {} void revert() {} void tally() {} double logp() const { return static_cast<double>(0); } void print() const { cout << MCMCSpecialized<DataT,ArmaT>::value_ << endl; } bool isDeterministc() const { return false; } bool isStochastic() const { return false; } }; } // namespace CppMC #endif // MCMC_HYPERPRIOR_HPP
/** * 1505080 * Error Detection using CRC checksum * Error Correction using Hamming distance **/ /** * Code to change consol text color: * #include <windows.h> * #include <iostream> * color = 4 RED * color = 10 GREEN * color = 11 CYAN * color = 15 WHITE * SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),colour), std::cout << "Using colour:" << colour << std::endl; **/ #include <windows.h> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> #include <iostream> #include <random> #include <vector> #include <queue> #define MAX_MSG_SIZE 80 #define MAX_POLYNOMIAL_SIZE 20 #define DIV_VAL 100000 #define RED 4 #define GREEN 10 #define CYAN 11 #define WHITE 15 using namespace std; random_device rand_dev; default_random_engine generator(rand_dev()); uniform_int_distribution<int> distribution(0,DIV_VAL); char *charToBinaryString(char ch){ char *binaryString = new char[12]; int mask = 1; for(int i=7; i>=0; i--){ if(ch & mask > 0){ binaryString[i] = '1'; } else{ binaryString[i] = '0'; } ch = ch >> 1; } binaryString[8] = 0; return binaryString; } char binaryStringToChar(char *binaryString){ char ch = 0; for(int i=0; i<8; i++){ ch = ch << 1; if(binaryString[i]=='1'){ ch |= 1; } //printf("%s\n", charToBinaryString(ch)); } return ch; } void printCharArray(int row, int col, char **array, int COLOR=WHITE, bool **colorArray=NULL){ for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if(colorArray==NULL || !colorArray[i][j]){ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << array[i][j]; } else{ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),COLOR), std::cout << array[i][j]; } } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << endl; } } int getHammingR(int m){ for(int r=0; ; r++){ if(pow(2, r) >= m+r+1){ return r; } } } char *calculateCRCBits(int crcDataLen, const char *key, const char *dataWithCRC){ // printf("Calculating CRC Checksum of: \n"); // printf("%s\n", dataWithCRC); int keySize = strlen(key); char *crc = new char[keySize+5]; ///initialize for (int i = 0; i < keySize; ++i) { crc[i] = dataWithCRC[i]; // printf("INIT: %c=%d, %c=%d\n", crc[i], crc[i], key[i], key[i]); } for (int nextBit = keySize; nextBit <= crcDataLen; nextBit++) { if(crc[0]=='1'){ for (int i = 0; i < keySize; ++i) { // printf("i=%d, %c=%d, %c=%d\n", i, crc[i], crc[i], key[i], key[i]); crc[i] = (crc[i]-'0')^(key[i]-'0')+'0'; } } ///for next iteration for (int i = 0; i < keySize-1; ++i) { crc[i] = crc[i+1]; } crc[keySize-1] = dataWithCRC[nextBit]; //crc[keySize] = 0; //printf("crc = %s\n", crc); } printf("\ncrc = %s\n", crc); return crc; } double randomGenerator(){ int idx = distribution(generator); int number = 0; for(int i=0; i<idx; i++){ ///random indexed random number number = distribution(generator); } return (1.0*number/DIV_VAL); } int main(){ //printf("%s %s %s\n", charToBinaryString('A'), charToBinaryString(16), charToBinaryString(7)); // char ch = binaryStringToChar("01100001"); // printf("%c %d\n", ch, ch); printf("******Error Detection and Correction Simulation******\n"); ///============================================================================= /// Taking Input ///============================================================================= char *inputDataString = new char[MAX_MSG_SIZE]; printf("Enter Data String:"); gets(inputDataString); printf("Data String:%s\n", inputDataString); int m; printf("Enter Number of Data Bytes in a Row <m>:"); scanf("%d", &m); printf("m=%d\n", m); if(m==0){ printf("m Must be Greater than 0\n"); exit(0); } double p; printf("Enter Probability <p>:"); scanf("%lf", &p); printf("p=%f\n", p); char *generatorPolynomial = new char[MAX_POLYNOMIAL_SIZE]; printf("Enter Generator Polynomial:"); gets(generatorPolynomial); //dummy gets(generatorPolynomial); printf("Generator Polynomial:%s\n", generatorPolynomial); ///============================================================================= /// 1.Padding ///============================================================================= int inputLen = strlen(inputDataString); for (int i = inputLen; i%m!=0 ; i++) { inputDataString[i] = '~'; inputDataString[i+1] = 0; } printf("\nData String after Padding:%s\n", inputDataString); ///============================================================================= /// 2.Generating Data Block ///============================================================================= inputLen = strlen(inputDataString); char *binaryString = new char[MAX_MSG_SIZE*8+1]; sprintf(binaryString, ""); for (int i = 0; i < inputLen; i++) { sprintf(binaryString, "%s%s", binaryString, charToBinaryString(inputDataString[i])); } //printf("\nBinary String:%s\n", binaryString); int numRow = inputLen/m; char **dataBlock = new char* [numRow]; for (int i = 0, k = 0; i < numRow; i++) { dataBlock[i] = new char[m*8]; for (int j = 0; j < m*8; j++, k++) { dataBlock[i][j] = binaryString[k]; } } printf("\nData Block <ASCII Code of m Characters Per Row>:\n"); printCharArray(numRow, m * 8, dataBlock); ///============================================================================= /// 3.Adding Check Bits (EVEN PARITY) ///============================================================================= int r = getHammingR(m*8); char **dataBlockWithCheckBits = new char* [numRow]; for (int i = 0; i < numRow; i++) { dataBlockWithCheckBits[i] = new char[m*8+r]; int power=0; int dataIdx = 0; for (int j = 0; j < m*8+r; j++) { if(j == pow(2, power)-1){ dataBlockWithCheckBits[i][j]= 'X'; power++; continue; } else{ dataBlockWithCheckBits[i][j] = dataBlock[i][dataIdx]; dataIdx++; } } } // printf("\nDataBlock With Checkbit Space Created:\n"); // printCharArray(numRow, m*8+r, dataBlockWithCheckBits); printf("\nDataBlock With Checkbits Added:\n"); for (int i = 0; i < numRow; i++) { int level=1; for (int j = 0; j < m*8+r; j++) { if(dataBlockWithCheckBits[i][j]=='X'){ int sum = 0; for (int base = j; base < m*8+r; base+=level*2) { for (int k = base; k < base+level; k++) { if(k >= m*8+r){ break; } else if(dataBlockWithCheckBits[i][k]=='1'){ sum++; } } } dataBlockWithCheckBits[i][j] = (char)(sum%2)+'0'; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),GREEN), std::cout << dataBlockWithCheckBits[i][j]; level *= 2; } else{ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << dataBlockWithCheckBits[i][j]; } } cout << endl; } ///============================================================================= /// 4.Serialize ///============================================================================= int serializedBits = numRow*(m*8+r); char *serializedData = new char[serializedBits+10]; //10 bit extra for safety for (int i = 0, dataIdx = 0; i < m * 8 + r; i++) { for (int j = 0; j < numRow; j++, dataIdx++) { serializedData[dataIdx] = dataBlockWithCheckBits[j][i]; } } serializedData[serializedBits] = 0; printf("\nData Bits after Column-wise Serialization:\n"); printf("%s\n", serializedData); ///============================================================================= /// 5.CRC Checksum ///============================================================================= int crcLen = strlen(generatorPolynomial)-1; int crcDataLen = serializedBits+crcLen; char *dataWithCRC = new char[crcDataLen+10]; strcpy(dataWithCRC, serializedData); for (int i = serializedBits; i < crcDataLen; ++i) { dataWithCRC[i] = '0'; } dataWithCRC[crcDataLen] = 0; char *crc = calculateCRCBits(crcDataLen, generatorPolynomial, dataWithCRC); for (int i = 0; i < crcLen; ++i) { dataWithCRC[serializedBits+i] = crc[i]; } printf("\nData Bits after Appending CRC Checksum <Sent Frame>:\n"); for (int i = 0; i < serializedBits; ++i) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << dataWithCRC[i]; } for (int i = serializedBits; i < crcDataLen; ++i) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),CYAN), std::cout << dataWithCRC[i]; } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << endl; ///============================================================================= /// 6.Toggle ///============================================================================= char *receivedFrame = new char[crcDataLen+10]; bool *errorArray = new bool[crcDataLen+10]; strcpy(receivedFrame, dataWithCRC); printf("\nReceived Frame:\n"); for (int i = 0; i < crcDataLen; i++) { if(randomGenerator() < p){ receivedFrame[i] = (char) ((receivedFrame[i]-'0')^1) + '0'; ///toggle errorArray[i] = true; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),RED), std::cout << receivedFrame[i]; } else{ SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << receivedFrame[i]; errorArray[i] = false; } } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << endl; ///============================================================================= /// 7.Verify CRC Checksum ///============================================================================= bool error = false; char *tempCRC = calculateCRCBits(crcDataLen, generatorPolynomial, receivedFrame); for (int i = 0; i < crcLen; ++i) { if(tempCRC[i] != '0' ){ error = true; } } printf("\nResult of CRC Checksum Matching: "); if(error){ printf("ERROR DETECTED\n"); } else{ printf("NO ERROR\n"); } ///============================================================================= /// 8.Remove CRC Checksum and Deserialize ///============================================================================= receivedFrame[serializedBits] = 0; // printf("\nAfter Removing CRC Checksum:\n"); // for (int i = 0; i < serializedBits; i++) { // if(errorArray[i]){ // SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),RED), std::cout << receivedFrame[i]; // } // else{ // SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << receivedFrame[i]; // } // // } // SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),WHITE), std::cout << endl; char **receivedBlockWithCheckBits = new char* [numRow]; bool **errorBlock = new bool* [numRow]; for (int i = 0; i < numRow; i++) { receivedBlockWithCheckBits[i] = new char[m*8+r]; errorBlock[i] = new bool[m*8+r]; } for (int i = 0, dataIdx = 0; i < m * 8 + r; i++) { for (int j = 0; j < numRow; j++, dataIdx++) { receivedBlockWithCheckBits[j][i] = receivedFrame[dataIdx]; errorBlock[j][i] = errorArray[dataIdx]; } } printf("\nData Bits after Removing CRC Checksum <Deserialized>:\n"); printCharArray(numRow, m*8+r, receivedBlockWithCheckBits, RED, errorBlock); ///============================================================================= /// 9.Correct Data and Remove Checkbits ///============================================================================= printf("\nAttempting to Correct Error Bits:\n"); for (int i = 0; i < numRow; i++) { int level = 1; int power = 0; int correctionIdx = 0; for (int j = 0; j < m*8+r; j++) { if(j == pow(2, power)-1){ power++; int sum = 0; for (int base = j; base < m*8+r; base+=level*2) { for (int k = base; k < base+level; k++) { if(k >= m*8+r){ break; } else if(receivedBlockWithCheckBits[i][k]=='1'){ sum++; } } } if(sum%2>0){ ///error found correctionIdx += j+1; } level *= 2; } } correctionIdx--; if(correctionIdx>=0 && correctionIdx< m*8+r){ receivedBlockWithCheckBits[i][correctionIdx] = (char) ((receivedBlockWithCheckBits[i][correctionIdx]-'0')^1)+'0'; printf("Correcting (%d,%d)\n", i, correctionIdx); } } printf("\nAfter Attempt to Correct Error Bits:\n"); printCharArray(numRow, m*8+r, receivedBlockWithCheckBits, RED, errorBlock); for (int i = 0; i < numRow; i++) { int power=0; int dataIdx = 0; for (int j = 0; j < m*8+r; j++) { if(j == pow(2, power)-1){ receivedBlockWithCheckBits[i][j]= 'X'; power++; continue; } } } // printf("\nRemoving Checkbits:\n"); // printCharArray(numRow, m*8+r, receivedBlockWithCheckBits); char **extractedDataBlock = new char*[numRow]; for (int i = 0; i < numRow; i++) { extractedDataBlock[i] = new char[m*8]; for (int j = 0, dataIdx=0; j < m*8+r; j++) { if(receivedBlockWithCheckBits[i][j]=='X'){ continue; } else{ extractedDataBlock[i][dataIdx] = receivedBlockWithCheckBits[i][j]; dataIdx++; } } } printf("\nData Block After Removing Checkbits:\n"); printCharArray(numRow, m*8, extractedDataBlock); ///============================================================================= /// 10.Correct Data and Remove Checkbits ///============================================================================= printf("\nOutput Frame: "); char *msg = new char[MAX_MSG_SIZE]; strcpy(msg, ""); for (int i = 0; i < numRow; i++) { for (int j = 0; j < m*8; j+=8) { char *str = new char[10]; strncpy(str, extractedDataBlock[i]+j, 8); char ch = binaryStringToChar(str); printf("%c", ch); sprintf(msg, "%s%c", msg, ch); delete []str; } } printf("\n"); for(int i = strlen(msg)-1; i>=0; i--){ if(msg[i] != '~'){ break; } msg[i]=0; } printf("\nExtracted Message: "); printf("%s\n", msg); ///============================================================================= /// Free Taken Memory ///============================================================================= delete []inputDataString; delete []generatorPolynomial; delete []binaryString; delete []serializedData; delete []dataWithCRC; delete []crc; delete []receivedFrame; delete []errorArray; delete []tempCRC; delete []msg; for (int i = 0; i < numRow; ++i) { delete [] dataBlock[i]; delete [] dataBlockWithCheckBits[i]; delete [] receivedBlockWithCheckBits[i]; delete [] errorBlock[i]; delete [] extractedDataBlock[i]; } delete []dataBlock; delete []dataBlockWithCheckBits; delete []receivedBlockWithCheckBits; delete []errorBlock; delete []extractedDataBlock; return 0; }
#include <iostream> using namespace std; int main() { long long n, ans = 0, a[200001], next = 1000000001; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = n - 1; i > -1; i--) { if (a[i] < next) { next = a[i]; ans += a[i]; } else if (next > 1) { next--; ans += next; } else break; } cout << ans << endl; }
class Matrix{ int row, col; int [][] storage; public: Matrix(int row, int col); ~Matrix(); void set(int row, int col, int data); int get(int row, int col); }
/**************************************************************************** ** Meta object code from reading C++ file 'CHTTPDownloader.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../CHTTPDownloader.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'CHTTPDownloader.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.3.2. 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 struct qt_meta_stringdata_CHTTPDownloader_t { QByteArrayData data[10]; char stringdata[122]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CHTTPDownloader_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CHTTPDownloader_t qt_meta_stringdata_CHTTPDownloader = { { QT_MOC_LITERAL(0, 0, 15), QT_MOC_LITERAL(1, 16, 15), QT_MOC_LITERAL(2, 32, 0), QT_MOC_LITERAL(3, 33, 14), QT_MOC_LITERAL(4, 48, 10), QT_MOC_LITERAL(5, 59, 16), QT_MOC_LITERAL(6, 76, 12), QT_MOC_LITERAL(7, 89, 14), QT_MOC_LITERAL(8, 104, 6), QT_MOC_LITERAL(9, 111, 10) }, "CHTTPDownloader\0sig_DownPercent\0\0" "lDownloadBytes\0totalBytes\0sig_DownFinished\0" "sig_DownQuit\0sig_ErrorOccur\0errMsg\0" "errorOccur" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CHTTPDownloader[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 5, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 4, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 39, 2, 0x06 /* Public */, 5, 0, 44, 2, 0x06 /* Public */, 6, 0, 45, 2, 0x06 /* Public */, 7, 1, 46, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 9, 1, 49, 2, 0x0a /* Public */, // signals: parameters QMetaType::Void, QMetaType::Long, QMetaType::Int, 3, 4, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, 8, // slots: parameters QMetaType::Void, QMetaType::QString, 8, 0 // eod }; void CHTTPDownloader::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { CHTTPDownloader *_t = static_cast<CHTTPDownloader *>(_o); switch (_id) { case 0: _t->sig_DownPercent((*reinterpret_cast< long(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: _t->sig_DownFinished(); break; case 2: _t->sig_DownQuit(); break; case 3: _t->sig_ErrorOccur((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 4: _t->errorOccur((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (CHTTPDownloader::*_t)(long , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CHTTPDownloader::sig_DownPercent)) { *result = 0; } } { typedef void (CHTTPDownloader::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CHTTPDownloader::sig_DownFinished)) { *result = 1; } } { typedef void (CHTTPDownloader::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CHTTPDownloader::sig_DownQuit)) { *result = 2; } } { typedef void (CHTTPDownloader::*_t)(const QString & ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CHTTPDownloader::sig_ErrorOccur)) { *result = 3; } } } } const QMetaObject CHTTPDownloader::staticMetaObject = { { &QThread::staticMetaObject, qt_meta_stringdata_CHTTPDownloader.data, qt_meta_data_CHTTPDownloader, qt_static_metacall, 0, 0} }; const QMetaObject *CHTTPDownloader::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CHTTPDownloader::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CHTTPDownloader.stringdata)) return static_cast<void*>(const_cast< CHTTPDownloader*>(this)); return QThread::qt_metacast(_clname); } int CHTTPDownloader::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QThread::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 5) qt_static_metacall(this, _c, _id, _a); _id -= 5; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 5) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 5; } return _id; } // SIGNAL 0 void CHTTPDownloader::sig_DownPercent(long _t1, int _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void CHTTPDownloader::sig_DownFinished() { QMetaObject::activate(this, &staticMetaObject, 1, 0); } // SIGNAL 2 void CHTTPDownloader::sig_DownQuit() { QMetaObject::activate(this, &staticMetaObject, 2, 0); } // SIGNAL 3 void CHTTPDownloader::sig_ErrorOccur(const QString & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } QT_END_MOC_NAMESPACE
/* @author Aytaç Kahveci */ #ifndef KRLAXIS_H #define KRLAXIS_H #include <kuka_ros_open_comm/KRLVariable.h> #include <vector> #include <string> #include <map> #include <stdexcept> #include <sstream> #include <algorithm> /** * Represents a Axis Struct variable from the KRL language * * @author Aytac Kahveci */ class KRLAxis { public: template<typename Out> void split(const std::string &s, char delim, Out result) { std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { *(result++) = item; } } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } private: std::string name_; long readTime_; int id_; KRLVariable *krl_var_; std::vector<std::string> nodes_; public: std::map<std::string, double> map_; KRLAxis(){} KRLAxis(std::string name, std::vector<std::string> nodes = {"A1", "A2", "A3", "A4", "A5", "A6"}) { krl_var_ = new KRLVariable(name); id_ = krl_var_->getId(); name_ = krl_var_->getName(); nodes_ = nodes; for(std::string str : nodes) { map_.insert(std::pair<std::string,double>(str, 0.0)); } } ~KRLAxis() { delete krl_var_; } std::vector<std::string> getNodes() { return nodes_; } void setA1ToA6(std::vector<double> values) { if (values.size() != 6) { throw std::invalid_argument("The number of values should be exatly 6!"); } setA1(values[0]); setA2(values[1]); setA3(values[2]); setA4(values[3]); setA5(values[4]); setA6(values[5]); } void setA1(double d) { map_["A1"] = d; } void setA2(double d) { map_["A2"] = d; } void setA3(double d) { map_["A3"] = d; } void setA4(double d) { map_["A4"] = d; } void setA5(double d) { map_["A5"] = d; } void setA6(double d) { map_["A6"] = d; } /** * Get a double array representation of this object * * @return a new double array with the values contained in this struct */ std::vector<double> asArray() { std::vector<double> arr; arr.resize(this->getNodes().size()); for (int i = 0; i < arr.size(); i++) { arr[i] = map_[this->getNodes()[i]]; } return arr; } std::vector<double> asArrayA1ToA6() { std::vector<double> arr = {map_["A1"], map_["A2"], map_["A3"], map_["A4"], map_["A5"], map_["A6"]}; return arr; } void setValue(std::string str, std::string obj) { std::string::size_type sz; double db = std::stod(obj, &sz); map_[str] = db; } std::map<std::string, double> getValue() { return map_; } std::string getStringValue() { std::string sb=""; sb.append("{"); unsigned int i = 0; for(std::string str : nodes_) { if(map_.count(str) > 0) { double get = map_[str]; map_.erase(map_.find(str)); sb.append(str).append(" ").append(std::to_string(get)); if(!map_.empty() && (i != map_.size())) { sb.append(", "); } } } sb.append("}"); return sb; } void setValueFromString(std::string strValue) { std::string substring; if(strValue.find(":") != std::string::npos) { std::vector<std::string> split_ = split(strValue,':'); std::string trim_ = trim(split_[1]); substring = trim_.substr(0, trim_.find('}')); } else { std::string trim_ = trim(strValue); substring = trim_.substr(1, trim_.size() - 1); } std::vector<std::string> split1 = split(substring,','); for(std::string n : split1) { trim(n); std::vector<std::string> split2 = split(n, ' '); setValue(split2[0], split2[1]); } } void update(int id, std::string strValue, long readTime) { if( id_ != id) { throw std::runtime_error("The returned id does not match the variable id! Should not happen..."); } readTime_ = readTime; setValueFromString(strValue); } std::vector<unsigned char> getReadCommand() { return krl_var_->getReadCommand(); } std::vector<unsigned char> getWriteCommand() { return krl_var_->getWriteCommand(getStringValue()); } }; #endif
#pragma once #include<iostream> #include<vector> using namespace std; void setZeroes(vector<vector<int>> &matrix) { if(matrix.size() == 0) return ; int col = matrix[0].size(); int row = matrix.size(); bool fc = false; bool fr = false; for(int i = 0; i < col; i++) { if(matrix[0][i] == 0) { fc = true; break; } } for(int i = 0; i < row; i++) { if(matrix[i][0] == 0) { fr = true; break; } } for(int i = 1; i < row; i++) { for(int j = 1; j < col; j++) { if(matrix[i][j] == 0) { matrix[0][j] = 0; matrix[i][0] = 0; } } } for(int i = 1; i < col; i++) { if(matrix[0][i] == 0) { for(int j = 1; j < row; j++) { matrix[j][i] = 0; } } } for(int i = 1; i < row; i++) { if(matrix[i][0] == 0) { for(int j = 1; j < col; j++) { matrix[i][j] = 0; } } } if(fr) { for(int i = 0; i < row; i++) { matrix[i][0] = 0; } } if(fc) { for(int i = 0; i < col; i++) { matrix[0][i] = 0; } } }
/* Create a Class Distance which contains members as Kilometer and Meter. Write C++ program to perform following functions: 1. To accept distance 2. To display distance 3. Overload += operator to add 2 distances. 4. Overload > operator to comapre 2 distances. */ #include<iostream> using namespace std; class Distance{ private: int kilometer,meter; public: Distance() { this->kilometer = 0; this->meter = 0; } Distance(int kilometer, int meter) { this->kilometer = kilometer; this->meter = meter; } void accept(int kilometer,int meter) { this->kilometer = kilometer; this->meter = meter; } void display() { cout<<"Distance:"<<this->kilometer<<" KM "<<this->meter<<" M"<<endl; } Distance operator +=(Distance object) { Distance newObject; newObject.kilometer = this->kilometer + object.kilometer; newObject.meter = this->meter + object.meter; return newObject; } Distance operator >(Distance object) { Distance newObject; int meter = this->kilometer * 1000; meter += this->meter; int meter_ = object.kilometer * 1000; meter_ += object.meter; if(meter>meter_) { newObject.kilometer = this->kilometer; newObject.meter = this->meter; } else { newObject.kilometer = object.kilometer; newObject.meter = object.meter; } return newObject; } }; int main(void) { Distance first,second,summation,compare; first.accept(5,256); second.accept(5,255); first.display(); second.display(); summation = first += second; summation.display(); compare = first > second; cout<<"Greater Distance"<<endl; compare.display(); }