<commit_before>//============================================================================
// Name        : brainfuck_rpc_emulator.cpp
// Author      : Artem Kashkanov
// Version     :
// Copyright   :
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <cstring>

#include "Console.h"

#include <fstream>

#include <vector>

#include "bfutils.h"

using namespace std;

uint8_t  LoadImage(std::ifstream &File, BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;

	File.read(reinterpret_cast<char *>(Header), sizeof(BfHeader_t));

	BfSection_t Code;
	Code.Position.Byte.high = Header->Code.Position.Byte.high;
	Code.Position.Byte.low = Header->Code.Position.Byte.low;

	Code.Length.Byte.high = Header->Code.Length.Byte.high;
	Code.Length.Byte.low = Header->Code.Length.Byte.low;

	BfSection_t Data;
	Data.Position.Byte.high = Header->Data.Position.Byte.high;
	Data.Position.Byte.low = Header->Data.Position.Byte.low;

	Data.Length.Byte.high = Header->Data.Length.Byte.high;
	Data.Length.Byte.low = Header->Data.Length.Byte.low;

	File.read(reinterpret_cast<char *>(MemoryPtr+Code.Position.Word), sizeof(uint16_t)*Code.Length.Word);
	if (Data.Length.Word != 0){
		File.read(reinterpret_cast<char *>(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
	}

	return status;
}

uint8_t LoadBF(char *fName, BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;
	std::ifstream File(fName, std::ifstream::binary);
	if (!File.good()){
		return -1;
	}
	LoadImage(File, Header, MemoryPtr);
	return status;
}

bool SegFault(const BfSection_t &section, uint16_t Ptr){
	bool result = false;
	if ((Ptr < section.Position.Word) ||(Ptr > section.Position.Word + section.Length.Word)){
		result = true;
	}
	return result;
}

uint8_t ExecCmd(BfHeader_t *Header, uint16_t *MemoryPtr, uint16_t &IP, uint16_t &AP){
	uint8_t status = SUCCESS;
	uint16_t cmd = MemoryPtr[IP];
	uint16_t cmd_bin = ((cmd>>13) & 0x0007);
	bool sign = ((cmd >> 12)&0x01)? true: false;
	uint16_t bias = (cmd&0x0FFF);

	switch (cmd_bin){
	case 0:
		MemoryPtr[AP] = sign? MemoryPtr[AP] - bias: MemoryPtr[AP] + bias;
		break;
	case 1:
		AP = sign? AP - bias: AP + bias;
		if (SegFault(Header->Data, AP)){
			return -1;
		}
		break;
	case 2:
		MemoryPtr[AP] = In();
		break;
	case 3:
		Out(MemoryPtr[AP]);
		break;
	case 4:
		IP = MemoryPtr[AP]? IP : (sign? IP - bias: IP + bias);
		if (SegFault(Header->Data, IP)){
			return -1;
		}
		break;
	case 5:
		IP = MemoryPtr[AP]? (sign? IP - bias: IP + bias) : IP;
		if (SegFault(Header->Data, IP)){
			return -1;
		}
		break;
	case 6:
		IP = bias;
		if (SegFault(Header->Data, IP)){
			return -1;
		}
		break;
	case 7:
		AP = Header->Data.Position.Word + bias;
		if (SegFault(Header->Data, AP)){
			return -1;
		}
		break;
	}
	return status;
}

uint8_t ExecCode(BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;

	uint16_t IP = Header->Code.Position.Word;
	uint16_t AP = Header->Data.Position.Word;

	do {

		status = ExecCmd(Header,MemoryPtr, IP, AP);
		if (status){
			return -1;
		}

		IP++;
	}while (IP < Header->Code.Position.Word + Header->Code.Length.Word);

	return status;
}

int main(int argc, char *argv[]) {
	int status = -1;
	int c = 0;
	char filePath[4096] = {0x00};
	while((c = getopt(argc, argv, "f:c:di")) != -1){
		switch(c)
		{
		case 'f':
			strcpy(filePath,optarg);
			break;
		}
	}
	if (*filePath == 0){
		cout << "Fatal error: add input file"<< endl;
		return -1;
	}
	BfHeader_t *Header = new BfHeader_t;
	uint16_t Memory[65536];
	memset(&Memory,0,sizeof(Memory));
	status = LoadBF(filePath,Header,Memory);
	if (status){
		return -1;
	}
	ExecCode(Header, Memory);

	return 0;
}
<commit_msg>FIX: BFRUN perform helloworld correctly<commit_after>//============================================================================
// Name        : brainfuck_rpc_emulator.cpp
// Author      : Artem Kashkanov
// Version     :
// Copyright   :
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <cstring>

#include "Console.h"

#include <fstream>

#include <vector>

#include "bfutils.h"

using namespace std;

bool ProtectedModeEnabled = false;

void SetProtectedMode(bool mode){
     ProtectedModeEnabled = mode;
}

bool GetProtectedMode(void){
     return ProtectedModeEnabled;
}
//Set 16-bit word mode:
bool WordModeEnabled = false;

void SetWordMode(bool mode){
     WordModeEnabled = mode;
}

bool GetWordMode(void){
     return WordModeEnabled;
}

void swapLEtoBE(WordToBigEndian_t *array, size_t size){

	uint8_t  tmp = 0;
	for (size_t i = 0; i < size/sizeof(uint16_t); ++i){
		tmp = array[i].Byte.low;
		array[i].Byte.low = array[i].Byte.high;
		array[i].Byte.high = tmp;
	}

}

uint8_t  LoadImage(std::ifstream &File, BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;

	File.read(reinterpret_cast<char *>(Header), sizeof(BfHeader_t));

	swapLEtoBE((WordToBigEndian_t*)(Header), sizeof(BfHeader_t));
	BfSection_t Code;
	Code.Position.Byte.high = Header->Code.Position.Byte.high;
	Code.Position.Byte.low = Header->Code.Position.Byte.low;

	Code.Length.Byte.high = Header->Code.Length.Byte.high;
	Code.Length.Byte.low = Header->Code.Length.Byte.low;

	BfSection_t Data;
	Data.Position.Byte.high = Header->Data.Position.Byte.high;
	Data.Position.Byte.low = Header->Data.Position.Byte.low;

	Data.Length.Byte.high = Header->Data.Length.Byte.high;
	Data.Length.Byte.low = Header->Data.Length.Byte.low;

	File.read(reinterpret_cast<char *>(MemoryPtr+Code.Position.Word), sizeof(uint16_t)*Code.Length.Word);
	swapLEtoBE((WordToBigEndian_t*)(MemoryPtr+Code.Position.Word),sizeof(uint16_t)*Code.Length.Word);
	if (Data.Length.Word != 0){
		File.read(reinterpret_cast<char *>(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
		swapLEtoBE((WordToBigEndian_t*)(MemoryPtr+Data.Position.Word), sizeof(uint16_t)*Data.Length.Word);
	}

	return status;
}

uint8_t LoadBF(char *fName, BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;
	std::ifstream File(fName, std::ifstream::binary);
	if (!File.good()){
		return -1;
	}
	LoadImage(File, Header, MemoryPtr);
	return status;
}

bool SegFault(const BfSection_t &section, uint16_t Ptr){
	bool result = false;
	if ((Ptr < section.Position.Word) ||(Ptr > section.Position.Word + section.Length.Word)){
		result = true;
	}
	return (GetProtectedMode()? result : false);
}

uint8_t ExecCmd(BfHeader_t *Header, uint16_t *MemoryPtr, uint16_t &IP, uint16_t &AP){
	uint8_t status = SUCCESS;
	uint16_t cmd = MemoryPtr[IP];
	uint16_t cmd_bin = ((cmd>>13) & 0x0007);
	bool sign = ((cmd >> 12)&0x01)? true: false;
	uint16_t bias = (cmd&0x0FFF);
	switch (cmd_bin){
	case 0:// '<' and '>' commands
		MemoryPtr[AP] = sign? MemoryPtr[AP] - bias: MemoryPtr[AP] + bias;
		break;
	case 1:// '+' and '-' commands
		AP = sign? AP - bias: AP + bias;
		if (SegFault(Header->Data, AP)){
			return -1;
		}
		break;
	case 2://Console input cmd
		if (GetWordMode()){
			MemoryPtr[AP] = In();
		}
		else{
			MemoryPtr[AP] = In() & 0xFF;
		}
		break;
	case 3://console output cmd
		if (GetWordMode()){
			Out(MemoryPtr[AP]);
		}
		else{
			Out(MemoryPtr[AP] & 0xFF);
		}
		break;
	case 4://Jump If Zero
		if (GetWordMode()){
			IP = MemoryPtr[AP]? IP : (sign? IP - bias: IP + bias);
		}
		else{
			IP = (MemoryPtr[AP] & 0xFF)? IP : (sign? IP - bias: IP + bias);
		}
		if (SegFault(Header->Data, IP)){
			return -2;
		}
		break;
	case 5://Jump If not zero
		if (GetWordMode()){
			IP = MemoryPtr[AP]? (sign? IP - bias: IP + bias) : IP;
		}
		else{
			IP = (MemoryPtr[AP] & 0xFF)? (sign? IP - bias: IP + bias) : IP;
		}
		if (SegFault(Header->Data, IP)){
			return -3;
		}
		break;
	case 6://Set IP
		IP = bias;
		if (SegFault(Header->Data, IP)){
			return -4;
		}
		break;
	case 7://Set AP
		AP = Header->Data.Position.Word + bias;
		if (SegFault(Header->Data, AP)){
			return -5;
		}
		break;
	}
	return status;
}

uint8_t ExecCode(BfHeader_t *Header, uint16_t *MemoryPtr){
	uint8_t status = 0;

	uint16_t IP = Header->Code.Position.Word;
	uint16_t AP = Header->Data.Position.Word;
	size_t i = 0;
	do {
		i++;
		status = ExecCmd(Header,MemoryPtr, IP, AP);
		if (status){
			return -1;
		}

		IP++;
	}while (IP < Header->Code.Position.Word + Header->Code.Length.Word);
	cerr << "\r\nIstructions_retired:" << i << "\r\n";
	return status;
}

int main(int argc, char *argv[]) {
	int status = -1;
	int c = 0;
	char filePath[4096] = {0x00};
	while((c = getopt(argc, argv, "f:px")) != -1){
		switch(c)
		{
		case 'f':
			strcpy(filePath,optarg);
			break;
		case 'p':
			SetProtectedMode(true);
		break;
		case 'x':
			SetWordMode(true);
		break;
		}
	}
	if (*filePath == 0){
		cout << "Fatal error: add input file"<< endl;
		return -1;
	}
	BfHeader_t *Header = new BfHeader_t;
	uint16_t Memory[65536];
	memset(&Memory,0,sizeof(Memory));
	status = LoadBF(filePath,Header,Memory);
	if (status){
		cerr << "Load BF buffer Error, Status =" << status << endl;
		return -1;
	}
	status = ExecCode(Header, Memory);
	if (status){
		cerr << "Code Execution Error, Status =" << status << endl;
		return -1;
	}

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: breakiterator_unicode.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2005-11-17 20:30:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_

#include <breakiteratorImpl.hxx>
#include <unicode/brkiter.h>

namespace com { namespace sun { namespace star { namespace i18n {

#define LOAD_CHARACTER_BREAKITERATOR    0
#define LOAD_WORD_BREAKITERATOR         1
#define LOAD_SENTENCE_BREAKITERATOR     2
#define LOAD_LINE_BREAKITERATOR         3

//  ----------------------------------------------------
//  class BreakIterator_Unicode
//  ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
    BreakIterator_Unicode();
    ~BreakIterator_Unicode();

    virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
        sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
        sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);

    virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
    virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
    virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
        throw(com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);

    virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
        const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
        throw(com::sun::star::uno::RuntimeException);

    //XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( com::sun::star::uno::RuntimeException );

protected:
    const sal_Char *cBreakIterator, *wordRule, *lineRule;
    Boundary result; // for word break iterator

    struct {
        rtl::OUString aText;
        icu::BreakIterator *aBreakIterator;
    } character, word, sentence, line, *icuBI;
    com::sun::star::lang::Locale aLocale;
    sal_Int16 aBreakType, aWordType;
    void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
        sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};

} } } }

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.12.16); FILE MERGED 2006/03/08 13:19:07 nn 1.12.16.1: #i53898# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: breakiterator_unicode.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 04:40:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    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.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _I18N_BREAKITERATOR_UNICODE_HXX_
#define _I18N_BREAKITERATOR_UNICODE_HXX_

#include <breakiteratorImpl.hxx>

// External unicode includes (from icu) cause warning C4668 on Windows.
// We want to minimize the patches to external headers, so the warnings are
// disabled here instead of in the header file itself.
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <unicode/brkiter.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

namespace com { namespace sun { namespace star { namespace i18n {

#define LOAD_CHARACTER_BREAKITERATOR    0
#define LOAD_WORD_BREAKITERATOR         1
#define LOAD_SENTENCE_BREAKITERATOR     2
#define LOAD_LINE_BREAKITERATOR         3

//  ----------------------------------------------------
//  class BreakIterator_Unicode
//  ----------------------------------------------------
class BreakIterator_Unicode : public BreakIteratorImpl
{
public:
    BreakIterator_Unicode();
    ~BreakIterator_Unicode();

    virtual sal_Int32 SAL_CALL previousCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
        sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL nextCharacters( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& rLocale, sal_Int16 nCharacterIteratorMode, sal_Int32 nCount,
        sal_Int32& nDone ) throw(com::sun::star::uno::RuntimeException);

    virtual Boundary SAL_CALL previousWord( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
    virtual Boundary SAL_CALL nextWord( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType) throw(com::sun::star::uno::RuntimeException);
    virtual Boundary SAL_CALL getWordBoundary( const rtl::OUString& Text, sal_Int32 nPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int16 WordType, sal_Bool bDirection )
        throw(com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL beginOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL endOfSentence( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale ) throw(com::sun::star::uno::RuntimeException);

    virtual LineBreakResults SAL_CALL getLineBreak( const rtl::OUString& Text, sal_Int32 nStartPos,
        const com::sun::star::lang::Locale& nLocale, sal_Int32 nMinBreakPos,
        const LineBreakHyphenationOptions& hOptions, const LineBreakUserOptions& bOptions )
        throw(com::sun::star::uno::RuntimeException);

    //XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( com::sun::star::uno::RuntimeException );

protected:
    const sal_Char *cBreakIterator, *wordRule, *lineRule;
    Boundary result; // for word break iterator

    struct {
        rtl::OUString aText;
        icu::BreakIterator *aBreakIterator;
    } character, word, sentence, line, *icuBI;
    com::sun::star::lang::Locale aLocale;
    sal_Int16 aBreakType, aWordType;
    void SAL_CALL loadICUBreakIterator(const com::sun::star::lang::Locale& rLocale,
        sal_Int16 rBreakType, sal_Int16 rWordType, const sal_Char* name, const rtl::OUString& rText) throw(com::sun::star::uno::RuntimeException);
};

} } } }

#endif
<|endoftext|>


<commit_before><commit_msg>Removed unnecessary dynamic_cast.<commit_after><|endoftext|>


<commit_before>#include "dataFile.h"
#include "debugUtils.h"

DataFile::DataFile(void)
    : file(0)
    , fileIsOpen(false)
{
}

DataFile::DataFile(const std::string& in_filename, std::ios_base::openmode mode)
    : file(0)
{
    open(in_filename, mode);
}

DataFile::~DataFile(void)
{
    close();
}

void DataFile::writeScalar(const std::string& name, const double x)
{
    require_file_open();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(0, NULL, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
    H5Dclose(dataset);
}

double DataFile::readScalar(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) !=  0) {
        throw DebugException((format(
            "DataFile::readScalar: '%s' is not a scalar.") % name).str());
    }

    double value;
    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
    H5Dclose(dataset);
    return value;
}

void DataFile::writeVector(const std::string& name, const dvector& v)
{
    require_file_open();

    hsize_t dims = v.size();
    if (dims == 0) {
        logFile.write(format(
            "DataFile::writeVector: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
    H5Dclose(dataset);
}

void DataFile::writeVec(const std::string& name, const dvec& v)
{
    require_file_open();

    hsize_t dims = v.rows();
    if (dims == 0) {
        logFile.write(format(
            "DataFile::writeVector: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, v.data());
    H5Dclose(dataset);
}

dvector DataFile::readVector(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 1D array.") % name).str());
    }

    hssize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvector values(static_cast<size_t>(N));

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
    H5Dclose(dataset);
    return values;
}

dvec DataFile::readVec(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 1D array.") % name).str());
    }

    hssize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvec values(static_cast<size_t>(N));

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, values.data());
    H5Dclose(dataset);
    return values;
}

void DataFile::writeArray2D(const std::string& name, const dmatrix& y, bool transpose)
{
    require_file_open();

    dmatrix yt;
    if (transpose) {
        yt = y.transpose();
    } else {
        yt = y;
    }

    hsize_t dims[2];
    dims[0] = yt.cols(); // TODO: double check the order of these
    dims[1] = yt.rows();

    if (dims[0] == 0 || dims[1] == 0) {
        logFile.write(format(
            "DataFile::writeArray2D: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(2, dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, yt.data());
    H5Dclose(dataset);
}

dmatrix DataFile::readArray2D(const std::string& name, bool transpose)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 2) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 2D array.\n"
            "(file: '%s'; ndims: %i") % name % filename %
            H5Sget_simple_extent_ndims(dataspace)).str());
    }

    hsize_t ndim = 2;
    vector<hsize_t> dimensions(2);
    H5Sget_simple_extent_dims(dataspace, &dimensions[0], &ndim);

    dmatrix y(dimensions[1], dimensions[0]);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL,
            H5S_ALL, H5P_DEFAULT, y.data());
    H5Dclose(dataset);

    if (transpose) {
        y = y.transpose().eval();
    }

    return y;
}

void DataFile::open(const std::string& in_filename, std::ios_base::openmode mode)
{
    if (file) {
        close();
    }

    filename = in_filename;
    std::ifstream test(filename.c_str());
    bool exists = test.good();
    test.close();

    if (exists && (mode & std::ios_base::app)) {
        file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    } else {
        file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC,
                         H5P_DEFAULT, H5P_DEFAULT);
    }
    fileIsOpen = true;
}

void DataFile::close()
{
    if (file) {
        H5Fclose(file);
        file = 0;
    }
    fileIsOpen = false;
}

void DataFile::require_file_open()
{
    if (!file) {
        throw DebugException(
            "Can't access DataFile object: H5File object not initialized.");
    } else if (!fileIsOpen) {
        throw DebugException(
            "Can't access DataFile object: H5File is closed.");
    }
}

hid_t DataFile::get_dataset
(const std::string& name, hid_t datatype, hid_t dataspace)
{
    if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
        H5Ldelete(file, name.c_str(), H5P_DEFAULT);
    }
    return H5Dcreate(file, name.c_str(), datatype, dataspace,
                     H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}

void dataFileTest()
{
    // Test reading from / writing to an HDF5 data file
    DataFile f("test.h5");
    double x = 9001;
    f.writeScalar("x", x);

    dvector v(10);
    for (size_t i=0; i<v.size(); i++) {
        v[i] = static_cast<double>(i*i);
    }

    f.writeVector("v", v);

    dmatrix A(3,7);
    for (dmatrix::Index i=0; i<A.rows(); i++) {
        for (dmatrix::Index j=0; j<A.cols(); j++) {
            A(i,j) = static_cast<double>(10*i + j);
        }
    }

    logFile.write(format("rows: %i") % A.rows());
    logFile.write(format("cols: %i") % A.cols());

    f.writeArray2D("A", A);
    f.close();

    DataFile g("test.h5");
    dvector w = g.readVector("v");
    for (size_t i=0; i<w.size(); i++) {
        logFile.write(format("%g") % w[i]);
    }

    logFile.write(format("%g") % g.readScalar("x"));
    logFile.write(g.readArray2D("A"));

    g.close();
}
<commit_msg>Fix invalid memory access in DataFile::readArray2D<commit_after>#include "dataFile.h"
#include "debugUtils.h"

DataFile::DataFile(void)
    : file(0)
    , fileIsOpen(false)
{
}

DataFile::DataFile(const std::string& in_filename, std::ios_base::openmode mode)
    : file(0)
{
    open(in_filename, mode);
}

DataFile::~DataFile(void)
{
    close();
}

void DataFile::writeScalar(const std::string& name, const double x)
{
    require_file_open();

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(0, NULL, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &x);
    H5Dclose(dataset);
}

double DataFile::readScalar(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) !=  0) {
        throw DebugException((format(
            "DataFile::readScalar: '%s' is not a scalar.") % name).str());
    }

    double value;
    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
    H5Dclose(dataset);
    return value;
}

void DataFile::writeVector(const std::string& name, const dvector& v)
{
    require_file_open();

    hsize_t dims = v.size();
    if (dims == 0) {
        logFile.write(format(
            "DataFile::writeVector: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &v[0]);
    H5Dclose(dataset);
}

void DataFile::writeVec(const std::string& name, const dvec& v)
{
    require_file_open();

    hsize_t dims = v.rows();
    if (dims == 0) {
        logFile.write(format(
            "DataFile::writeVector: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(1, &dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, v.data());
    H5Dclose(dataset);
}

dvector DataFile::readVector(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 1D array.") % name).str());
    }

    hssize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvector values(static_cast<size_t>(N));

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &values[0]);
    H5Dclose(dataset);
    return values;
}

dvec DataFile::readVec(const std::string& name)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 1) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 1D array.") % name).str());
    }

    hssize_t N = H5Sget_simple_extent_npoints(dataspace);
    dvec values(static_cast<size_t>(N));

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, values.data());
    H5Dclose(dataset);
    return values;
}

void DataFile::writeArray2D(const std::string& name, const dmatrix& y, bool transpose)
{
    require_file_open();

    dmatrix yt;
    if (transpose) {
        yt = y.transpose();
    } else {
        yt = y;
    }

    hsize_t dims[2];
    dims[0] = yt.cols(); // TODO: double check the order of these
    dims[1] = yt.rows();

    if (dims[0] == 0 || dims[1] == 0) {
        logFile.write(format(
            "DataFile::writeArray2D: Warning: '%s' is empty.") % name);
        return;
    }

    hid_t dataspace, dataset, datatype;
    dataspace = H5Screate_simple(2, dims, NULL);
    datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
    H5Tset_order(datatype, H5T_ORDER_LE);

    dataset = get_dataset(name, datatype, dataspace);
    H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, yt.data());
    H5Dclose(dataset);
}

dmatrix DataFile::readArray2D(const std::string& name, bool transpose)
{
    require_file_open();

    hid_t dataspace, dataset;
    dataset = H5Dopen(file, name.c_str(), H5P_DEFAULT);
    dataspace = H5Dget_space(dataset);

    if (H5Sget_simple_extent_ndims(dataspace) != 2) {
        throw DebugException((format(
            "DataFile::readVector: '%s' is not a 2D array.\n"
            "(file: '%s'; ndims: %i") % name % filename %
            H5Sget_simple_extent_ndims(dataspace)).str());
    }

    hsize_t dimensions[2];
    H5Sget_simple_extent_dims(dataspace, dimensions, NULL);

    dmatrix y(dimensions[1], dimensions[0]);

    H5Dread(dataset, H5T_NATIVE_DOUBLE, H5S_ALL,
            H5S_ALL, H5P_DEFAULT, y.data());
    H5Dclose(dataset);

    if (transpose) {
        y = y.transpose().eval();
    }

    return y;
}

void DataFile::open(const std::string& in_filename, std::ios_base::openmode mode)
{
    if (file) {
        close();
    }

    filename = in_filename;
    std::ifstream test(filename.c_str());
    bool exists = test.good();
    test.close();

    if (exists && (mode & std::ios_base::app)) {
        file = H5Fopen(filename.c_str(), H5F_ACC_RDWR, H5P_DEFAULT);
    } else {
        file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC,
                         H5P_DEFAULT, H5P_DEFAULT);
    }
    fileIsOpen = true;
}

void DataFile::close()
{
    if (file) {
        H5Fclose(file);
        file = 0;
    }
    fileIsOpen = false;
}

void DataFile::require_file_open()
{
    if (!file) {
        throw DebugException(
            "Can't access DataFile object: H5File object not initialized.");
    } else if (!fileIsOpen) {
        throw DebugException(
            "Can't access DataFile object: H5File is closed.");
    }
}

hid_t DataFile::get_dataset
(const std::string& name, hid_t datatype, hid_t dataspace)
{
    if (H5Lexists(file, name.c_str(), H5P_DEFAULT)) {
        H5Ldelete(file, name.c_str(), H5P_DEFAULT);
    }
    return H5Dcreate(file, name.c_str(), datatype, dataspace,
                     H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}

void dataFileTest()
{
    // Test reading from / writing to an HDF5 data file
    DataFile f("test.h5");
    double x = 9001;
    f.writeScalar("x", x);

    dvector v(10);
    for (size_t i=0; i<v.size(); i++) {
        v[i] = static_cast<double>(i*i);
    }

    f.writeVector("v", v);

    dmatrix A(3,7);
    for (dmatrix::Index i=0; i<A.rows(); i++) {
        for (dmatrix::Index j=0; j<A.cols(); j++) {
            A(i,j) = static_cast<double>(10*i + j);
        }
    }

    logFile.write(format("rows: %i") % A.rows());
    logFile.write(format("cols: %i") % A.cols());

    f.writeArray2D("A", A);
    f.close();

    DataFile g("test.h5");
    dvector w = g.readVector("v");
    for (size_t i=0; i<w.size(); i++) {
        logFile.write(format("%g") % w[i]);
    }

    logFile.write(format("%g") % g.readScalar("x"));
    logFile.write(g.readArray2D("A"));

    g.close();
}
<|endoftext|>


<commit_before><commit_msg>Error messages added by PeiYong Zhang.<commit_after><|endoftext|>


<commit_before>
#include <stdarg.h>
#include <stdio.h>

#include "../imgui/imgui.h"

#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif

extern "C" API ImGuiIO* ImGui_GetIO()
{
	return &ImGui::GetIO();
}

extern "C" API void ImGui_Shutdown()
{
	ImGui::Shutdown();
}

extern "C" API void ImGui_NewFrame()
{
	ImGui::NewFrame();
}

extern "C" API void ImGui_Render()
{
	ImGui::Render();
}

extern "C" API void ImGui_ShowTestWindow(bool* opened)
{
	ImGui::ShowTestWindow(opened);
}

extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
	return ImGui::Begin(name, p_opened, flags);
}

extern "C" API void ImGui_End()
{
	ImGui::End();
}

extern "C" API void ImGui_Text(const char* text, ...)
{
	char buffer[256];
  	va_list args;
  	va_start (args, text);
  	vsprintf (buffer, text, args);
  	va_end (args);

	ImGui::Text(buffer);
}

extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
	return ImGui::ColorEdit3(label,col);
}

extern "C" API void ImGui_SetNextWindowPos(const ImVec2 pos, ImGuiSetCond cond)
{
	ImGui::SetNextWindowPos(pos,cond);
}

extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
	ImGui::SetNextWindowSize(size, cond);
}

extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
	ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}

extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
	return ImGui::Button(label,size,repeat_when_held);
}

extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
	atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}

extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
	atlas->TexID = tex;
}

extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
	return list->vtx_buffer.size();
}

extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
	return &list->vtx_buffer[n];
}

extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
	return list->commands.size();
}

extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
	return &list->commands[n];
}

extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
	ImGui::GetIO().AddInputCharacter(c);
}
<commit_msg>more bindings<commit_after>
#include <stdarg.h>
#include <stdio.h>

#include "../imgui/imgui.h"

#if defined _WIN32 || defined __CYGWIN__
#define API __declspec(dllexport)
#else
#define API
#endif

extern "C" API ImGuiIO* ImGui_GetIO()
{
	return &ImGui::GetIO();
}

extern "C" API void ImGui_Shutdown()
{
	ImGui::Shutdown();
}

extern "C" API void ImGui_NewFrame()
{
	ImGui::NewFrame();
}

extern "C" API void ImGui_Render()
{
	ImGui::Render();
}

extern "C" API void ImGui_ShowTestWindow(bool* opened)
{
	ImGui::ShowTestWindow(opened);
}

extern "C" API bool ImGui_Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags)
{
	return ImGui::Begin(name, p_opened, flags);
}

extern "C" API void ImGui_End()
{
	ImGui::End();
}

extern "C" API void ImGui_Text(const char* text, ...)
{
	char buffer[256];
  	va_list args;
  	va_start (args, text);
  	vsprintf (buffer, text, args);
  	va_end (args);

	ImGui::Text(buffer);
}

extern "C" API bool ImGui_ColorEdit3(const char* label, float col[3])
{
	return ImGui::ColorEdit3(label,col);
}

extern "C" API void ImGui_SetNextWindowPos(const ImVec2 pos, ImGuiSetCond cond)
{
	ImGui::SetNextWindowPos(pos,cond);
}

extern "C" API void ImGui_SetNextWindowSize(const ImVec2 size, ImGuiSetCond cond)
{
	ImGui::SetNextWindowSize(size, cond);
}

extern "C" API void ImGui_SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
	ImGui::SliderFloat(label,v,v_min,v_max,display_format,power);
}

extern "C" API bool ImGui_Button(const char* label, const ImVec2& size, bool repeat_when_held)
{
	return ImGui::Button(label,size,repeat_when_held);
}

extern "C" API bool ImGui_SmallButton(const char* label)
{
	return ImGui::SmallButton(label);
}

extern "C" API bool ImGui_TreeNode(const char* str_label_id)
{
	return ImGui::TreeNode(str_label_id);
}

extern "C" API bool ImGui_TreeNode_IdFmt(const void* ptr_id, const char* fmt, ...)
{
	char buffer[256];
  	va_list args;
  	va_start (args, fmt);
  	vsprintf (buffer, fmt, args);
  	va_end (args);

  	//TODO: use TreeNodeV
	return ImGui::TreeNode(ptr_id,"%s",buffer);
}

extern "C" API void ImGui_TreePop()
{
	ImGui::TreePop();
}

extern "C" API void ImGui_SameLine(int column_x, int spacing_w)
{
	ImGui::SameLine(column_x,spacing_w);
}

extern "C" API void ImFontAtlas_GetTexDataAsRGBA32(ImFontAtlas* atlas, unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
	atlas->GetTexDataAsRGBA32(out_pixels,out_width,out_height,out_bytes_per_pixel);
}

extern "C" API void ImFontAtlas_SetTexID(ImFontAtlas* atlas, void* tex)
{
	atlas->TexID = tex;
}

extern "C" API int ImDrawList_GetVertexBufferSize(ImDrawList* list)
{
	return list->vtx_buffer.size();
}

extern "C" API ImDrawVert* ImDrawList_GetVertexPtr(ImDrawList* list, int n)
{
	return &list->vtx_buffer[n];
}

extern "C" API int ImDrawList_GetCmdSize(ImDrawList* list)
{
	return list->commands.size();
}

extern "C" API ImDrawCmd* ImDrawList_GetCmdPtr(ImDrawList* list, int n)
{
	return &list->commands[n];
}

extern "C" API void ImGuiIO_AddInputCharacter(unsigned short c)
{
	ImGui::GetIO().AddInputCharacter(c);
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(k)

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @param k: As described
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums, int k) {
        unordered_map<int, int> hash;
        int n = nums.size();

        for (auto& i : nums) {
            ++hash[i];
            // Detecting k items in hash, at least one of them must have exactly
            // one in it. We will discard those k items by one for each.
            // This action keeps the same mojority numbers in the remaining numbers.
            // Because if x / n  > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
            if (hash.size() == k) {
                auto it = hash.begin();
                while (it != hash.end()) {
                    if (--(it->second) == 0) {
                        hash.erase(it++);
                    } else {
                        ++it;
                    }
                }
            }
        }

        // Resets hash for the following counting.
        for (auto& it : hash) {
            it.second = 0;
        }

        // Counts the occurrence of each candidate integer.
        for (auto& i : nums) {
            auto it = hash.find(i);
            if (it != hash.end()) {
                ++it->second;
            }
        }

        // Selects the integer which occurs > n / k times.
        vector<int> ret;
        for (const pair<int, int>& it : hash) {
            if (it.second > static_cast<double>(n) / k) {
                ret.emplace_back(it.first);
            }
        }

        return ret[0];
    }
};

<commit_msg>update<commit_after>// Time:  O(n)
// Space: O(k)

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @param k: As described
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums, int k) {
        const int n = nums.size();
        unordered_map<int, int> hash;

        for (const auto& i : nums) {
            ++hash[i];
            // Detecting k items in hash, at least one of them must have exactly
            // one in it. We will discard those k items by one for each.
            // This action keeps the same mojority numbers in the remaining numbers.
            // Because if x / n  > 1 / k is true, then (x - 1) / (n - k) > 1 / k is also true.
            if (hash.size() == k) {
                auto it = hash.begin();
                while (it != hash.end()) {
                    if (--(it->second) == 0) {
                        hash.erase(it++);
                    } else {
                        ++it;
                    }
                }
            }
        }

        // Resets hash for the following counting.
        for (auto& it : hash) {
            it.second = 0;
        }

        // Counts the occurrence of each candidate integer.
        for (const auto& i : nums) {
            auto it = hash.find(i);
            if (it != hash.end()) {
                ++it->second;
            }
        }

        // Selects the integer which occurs > n / k times.
        vector<int> ret;
        for (const pair<int, int>& it : hash) {
            if (it.second > static_cast<double>(n) / k) {
                ret.emplace_back(it.first);
            }
        }

        return ret[0];
    }
};

<|endoftext|>


<commit_before>// Copyright 2008 Google Inc.
//
// 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.
/*
  An example running of this program:

  ./lda           \
  --num_topics 2 \
  --alpha 0.1    \
  --beta 0.01                                           \
  --training_data_file ./testdata/test_data.txt \
  --model_file /tmp/lda_model.txt                       \
  --burn_in_iterations 100                              \
  --total_iterations 150
*/

#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <map>

#include "common.h"
#include "document.h"
#include "model.h"
#include "accumulative_model.h"
#include "sampler.h"
#include "cmd_flags.h"

namespace learning_lda {

using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::set;
using std::map;

int LoadAndInitTrainingCorpus(std::vector<string> &lines,
                              int num_topics,
                              LDACorpus* corpus,
                              map<string, int>* word_index_map) {
  corpus->clear();
  word_index_map->clear();
  string line;
  for (int i=0; i < lines.size(); i++){  // Each line is a training document.
    string line = lines[i];
    if (line.size() > 0 &&      // Skip empty lines.
        line[0] != '\r' &&      // Skip empty lines.
        line[0] != '\n' &&      // Skip empty lines.
        line[0] != '#') {       // Skip comment lines.
      istringstream ss(line);
      DocumentWordTopicsPB document;
      string word;
      int count;
      while (ss >> word >> count) {  // Load and init a document.
        vector<int32> topics;
        for (int i = 0; i < count; ++i) {
          topics.push_back(RandInt(num_topics));
        }
        int word_index;
        map<string, int>::const_iterator iter = word_index_map->find(word);
        if (iter == word_index_map->end()) {
          word_index = word_index_map->size();
          (*word_index_map)[word] = word_index;
        } else {
          word_index = iter->second;
        }
        document.add_wordtopics(word, word_index, topics);
      }
      corpus->push_back(new LDADocument(document, num_topics));
    }
  }
  return corpus->size();

}

int LoadAndInitTrainingCorpus(const string& corpus_file,
                              int num_topics,
                              LDACorpus* corpus,
                              map<string, int>* word_index_map) {
  ifstream fin(corpus_file.c_str());
  string line;
  vector<string> lines;
  while (getline(fin, line)) {  // Each line is a training document.
    if (line.size() > 0 &&      // Skip empty lines.
        line[0] != '\r' &&      // Skip empty lines.
        line[0] != '\n' &&      // Skip empty lines.
        line[0] != '#') {       // Skip comment lines.
      lines.push_back(line);
    }
  }
  return LoadAndInitTrainingCorpus(lines,num_topics,corpus,word_index_map);
}

void FreeCorpus(LDACorpus* corpus) {
  for (list<LDADocument*>::iterator iter = corpus->begin();
       iter != corpus->end();
       ++iter) {
    if (*iter != NULL) {
      delete *iter;
      *iter = NULL;
    }
  }
}

LDAAccumulativeModel* LearnFromFile(const string& corpus_file,int num_topics,map<string, int>* word_index_map, int total_iterations, int burn_in_iterations, double alpha, double beta)
{
  using learning_lda::LDACorpus;
  using learning_lda::LDAModel;
  using learning_lda::LDAAccumulativeModel;
  using learning_lda::LDASampler;
  using learning_lda::LDADocument;
  using learning_lda::LoadAndInitTrainingCorpus;
  using std::list;
  LDACorpus corpus;
  int ret = LoadAndInitTrainingCorpus(corpus_file,
                                     num_topics,
                                     &corpus, word_index_map);

  LDAAccumulativeModel *accum_model = new LDAAccumulativeModel(num_topics, (*word_index_map).size());
  LDAModel model(num_topics, *word_index_map);
  LDASampler sampler(alpha, beta, &model, accum_model);
  sampler.InitModelGivenTopics(corpus);

  for (int iter = 0; iter < total_iterations; ++iter) {
    std::cout << "Iteration " << iter << " ...\n";
    double loglikelihood = 0;
    for (list<LDADocument*>::const_iterator iterator = corpus.begin();
        iterator != corpus.end();
        ++iterator) {
      loglikelihood += sampler.LogLikelihood(*iterator);
    }
    std::cout << "Loglikelihood: " << loglikelihood << std::endl;
    sampler.DoIteration(&corpus, true, iter < burn_in_iterations);
    std::cout << "DONEa" << "\n";
  }
  std::cout << "DONE1" << "\n";
  (*accum_model).AverageModel(total_iterations - burn_in_iterations);
  std::cout << "DONE1" << "\n";
  FreeCorpus(&corpus);
  std::cout << "DONE1" << "\n";
  return accum_model;
}

}  // namespace learning_lda

int main(int argc, char** argv) {

  using learning_lda::LDACmdLineFlags;
  using learning_lda::LearnFromFile;
  using learning_lda::LDAAccumulativeModel;
  map<string, int> word_index_map;
  srand(time(NULL));

  LDACmdLineFlags flags;
  flags.ParseCmdFlags(argc, argv);

  if (!flags.CheckTrainingValidity()) {
    return -1;
  }

  LDAAccumulativeModel *accum_model = LearnFromFile(flags.training_data_file_,flags.num_topics_,&word_index_map, flags.total_iterations_, flags.burn_in_iterations_, flags.alpha_, flags.beta_);

  std::cout << "OUTPUTTING TO " << flags.model_file_ << "\n";
  std::ofstream fout(flags.model_file_.c_str());
  (*accum_model).AppendAsString(word_index_map, fout);

  return 0;
}
<commit_msg>Can now pass a std::vector rather than file handle<commit_after>// Copyright 2008 Google Inc.
//
// 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.
/*
  An example running of this program:

  ./lda           \
  --num_topics 2 \
  --alpha 0.1    \
  --beta 0.01                                           \
  --training_data_file ./testdata/test_data.txt \
  --model_file /tmp/lda_model.txt                       \
  --burn_in_iterations 100                              \
  --total_iterations 150
*/

#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <map>

#include "common.h"
#include "document.h"
#include "model.h"
#include "accumulative_model.h"
#include "sampler.h"
#include "cmd_flags.h"

namespace learning_lda {

using std::ifstream;
using std::ofstream;
using std::istringstream;
using std::set;
using std::map;

int LoadAndInitTrainingCorpus(std::vector<string> &lines,
                              int num_topics,
                              LDACorpus* corpus,
                              map<string, int>* word_index_map) {
  corpus->clear();
  word_index_map->clear();
  string line;
  for (int i=0; i < lines.size(); i++){  // Each line is a training document.
    string line = lines[i];
    if (line.size() > 0 &&      // Skip empty lines.
        line[0] != '\r' &&      // Skip empty lines.
        line[0] != '\n' &&      // Skip empty lines.
        line[0] != '#') {       // Skip comment lines.
      istringstream ss(line);
      DocumentWordTopicsPB document;
      string word;
      int count;
      while (ss >> word >> count) {  // Load and init a document.
        vector<int32> topics;
        for (int i = 0; i < count; ++i) {
          topics.push_back(RandInt(num_topics));
        }
        int word_index;
        map<string, int>::const_iterator iter = word_index_map->find(word);
        if (iter == word_index_map->end()) {
          word_index = word_index_map->size();
          (*word_index_map)[word] = word_index;
        } else {
          word_index = iter->second;
        }
        document.add_wordtopics(word, word_index, topics);
      }
      corpus->push_back(new LDADocument(document, num_topics));
    }
  }
  return corpus->size();

}

std::vector<string>* LoadCorpusFile(const string& corpus_file)
{
  ifstream fin(corpus_file.c_str());
  string line;
  std::vector<string> *lines = new std::vector<string>();
  while (getline(fin, line)) {  // Each line is a training document.
    if (line.size() > 0 &&      // Skip empty lines.
        line[0] != '\r' &&      // Skip empty lines.
        line[0] != '\n' &&      // Skip empty lines.
        line[0] != '#') {       // Skip comment lines.
      lines->push_back(line);
    }
  }
return lines;
}

void FreeCorpus(LDACorpus* corpus) {
  for (list<LDADocument*>::iterator iter = corpus->begin();
       iter != corpus->end();
       ++iter) {
    if (*iter != NULL) {
      delete *iter;
      *iter = NULL;
    }
  }
}

LDAAccumulativeModel* LearnFromCorpus(std::vector<string> *lines,int num_topics,map<string, int>* word_index_map, int total_iterations, int burn_in_iterations, double alpha, double beta)
{
  using learning_lda::LDACorpus;
  using learning_lda::LDAModel;
  using learning_lda::LDAAccumulativeModel;
  using learning_lda::LDASampler;
  using learning_lda::LDADocument;
  using learning_lda::LoadAndInitTrainingCorpus;
  using std::list;
  LDACorpus corpus;
  int ret = LoadAndInitTrainingCorpus(*lines,
                                     num_topics,
                                     &corpus, word_index_map);

  LDAAccumulativeModel *accum_model = new LDAAccumulativeModel(num_topics, (*word_index_map).size());
  LDAModel model(num_topics, *word_index_map);
  LDASampler sampler(alpha, beta, &model, accum_model);
  sampler.InitModelGivenTopics(corpus);

  for (int iter = 0; iter < total_iterations; ++iter) {
    std::cout << "Iteration " << iter << " ...\n";
    double loglikelihood = 0;
    for (list<LDADocument*>::const_iterator iterator = corpus.begin();
        iterator != corpus.end();
        ++iterator) {
      loglikelihood += sampler.LogLikelihood(*iterator);
    }
    std::cout << "Loglikelihood: " << loglikelihood << std::endl;
    sampler.DoIteration(&corpus, true, iter < burn_in_iterations);
    std::cout << "DONEa" << "\n";
  }
  std::cout << "DONE1" << "\n";
  (*accum_model).AverageModel(total_iterations - burn_in_iterations);
  std::cout << "DONE1" << "\n";
  FreeCorpus(&corpus);
  std::cout << "DONE1" << "\n";
  return accum_model;
}

}  // namespace learning_lda

int main(int argc, char** argv) {

  using learning_lda::LDACmdLineFlags;
  using learning_lda::LearnFromCorpus;
  using learning_lda::LoadCorpusFile;
  using learning_lda::LDAAccumulativeModel;
  map<string, int> word_index_map;
  srand(time(NULL));

  LDACmdLineFlags flags;
  flags.ParseCmdFlags(argc, argv);

  if (!flags.CheckTrainingValidity()) {
    return -1;
  }

  LDAAccumulativeModel *accum_model = LearnFromCorpus(LoadCorpusFile(flags.training_data_file_),flags.num_topics_,&word_index_map, flags.total_iterations_, flags.burn_in_iterations_, flags.alpha_, flags.beta_);

  std::cout << "OUTPUTTING TO " << flags.model_file_ << "\n";
  std::ofstream fout(flags.model_file_.c_str());
  (*accum_model).AppendAsString(word_index_map, fout);

  return 0;
}
<|endoftext|>


<commit_before>#ifndef DUBINS_TRAFFIC_PROBLEM_H
#define DUBINS_TRAFFIC_PROBLEM_H

#include <iostream>
#include <vector>
#include <string>

#include <Eigen/Dense>

#include "roadnet.hpp"

namespace dubins_traffic {

/** Representation of problem instances.

    \ingroup dubins_traffic */
class Problem {
public:
    double intersection_radius;
    std::vector<size_t> goals;
    RoadNetwork rnd;

    Problem( const RoadNetwork &rnd_ );
    Problem( const Problem &to_be_copied );

    static Problem random( const RoadNetwork &rnd_,
                           const Eigen::Vector2i &number_goals_bounds );

    /** Create formula using SPIN LTL syntax <http://spinroot.com/spin/Man/ltl.html>.
       Support for other syntax is coming soon. */
    void to_formula( std::ostream &out ) const;

    /** Output description of problem in JSON to a stream */
    friend std::ostream & operator<<( std::ostream &out, const Problem &prob );

    /** Get description of problem in JSON. */
    std::string dumpJSON() const;
};

Problem::Problem( const RoadNetwork &rnd_ )
    : rnd(rnd_)
{
    intersection_radius = 0.0;
}

Problem::Problem( const Problem &to_be_copied )
    : intersection_radius( to_be_copied.intersection_radius ),
      goals( to_be_copied.goals ),
      rnd( to_be_copied.rnd )
{
    assert( intersection_radius > 0 );
}

Problem Problem::random( const RoadNetwork &rnd_,
                         const Eigen::Vector2i &number_goals_bounds )
{
    assert( number_goals_bounds(0) >= 0
            && number_goals_bounds(0) <= number_goals_bounds(1) );

    Problem pinstance( rnd_ );
    pinstance.intersection_radius = 1.0;

    int number_goals = number_goals_bounds(0);
    if (number_goals_bounds(1) != number_goals_bounds(0))
        number_goals += (std::rand()
                         % (1+number_goals_bounds(1)
                            - number_goals_bounds(0)));

    for (size_t goal_idx = 0; goal_idx < number_goals; goal_idx++)
        pinstance.goals.push_back( std::rand() % rnd_.number_of_intersections() );

    return pinstance;
}

void Problem::to_formula( std::ostream &out ) const
{
    if (goals.size() > 0) {
        for (size_t i = 0; i < goals.size(); i++) {
            if (i > 0)
                out << " && ";
            out << "([]<> ego_" << rnd.get_intersection_str( goals[i] ) << ")";
        }
    }
}

std::ostream & operator<<( std::ostream &out, const Problem &prob )
{
    out << "{" << std::endl << "\"version\": " << 0 << "," << std::endl;
    out << "\"goals\": [" << std::endl;
    for (int i = 0; i < prob.goals.size(); i++) {
        if (i > 0)
            out << ", ";
        out << "\"ego_" << prob.rnd.get_intersection_str( prob.goals[i] ) << "\"";
        out << std::endl;
    }
    out << "]";
    out << std::endl << "}";
    return out;
}

std::string Problem::dumpJSON() const
{
    std::ostringstream out;
    out << *this;
    return out.str();
}

} // namespace dubins_traffic

#endif
<commit_msg>Include road net in dubins_traffic problem instance JSON<commit_after>#ifndef DUBINS_TRAFFIC_PROBLEM_H
#define DUBINS_TRAFFIC_PROBLEM_H

#include <iostream>
#include <vector>
#include <string>

#include <Eigen/Dense>

#include "roadnet.hpp"

namespace dubins_traffic {

/** Representation of problem instances.

    \ingroup dubins_traffic */
class Problem {
public:
    double intersection_radius;
    std::vector<size_t> goals;
    RoadNetwork rnd;

    Problem( const RoadNetwork &rnd_ );
    Problem( const Problem &to_be_copied );

    static Problem random( const RoadNetwork &rnd_,
                           const Eigen::Vector2i &number_goals_bounds );

    /** Create formula using SPIN LTL syntax <http://spinroot.com/spin/Man/ltl.html>.
       Support for other syntax is coming soon. */
    void to_formula( std::ostream &out ) const;

    /** Output description of problem in JSON to a stream */
    friend std::ostream & operator<<( std::ostream &out, const Problem &prob );

    /** Get description of problem in JSON. */
    std::string dumpJSON() const;
};

Problem::Problem( const RoadNetwork &rnd_ )
    : rnd(rnd_)
{
    intersection_radius = 0.0;
}

Problem::Problem( const Problem &to_be_copied )
    : intersection_radius( to_be_copied.intersection_radius ),
      goals( to_be_copied.goals ),
      rnd( to_be_copied.rnd )
{
    assert( intersection_radius > 0 );
}

Problem Problem::random( const RoadNetwork &rnd_,
                         const Eigen::Vector2i &number_goals_bounds )
{
    assert( number_goals_bounds(0) >= 0
            && number_goals_bounds(0) <= number_goals_bounds(1) );

    Problem pinstance( rnd_ );
    pinstance.intersection_radius = 1.0;

    int number_goals = number_goals_bounds(0);
    if (number_goals_bounds(1) != number_goals_bounds(0))
        number_goals += (std::rand()
                         % (1+number_goals_bounds(1)
                            - number_goals_bounds(0)));

    for (size_t goal_idx = 0; goal_idx < number_goals; goal_idx++)
        pinstance.goals.push_back( std::rand() % rnd_.number_of_intersections() );

    return pinstance;
}

void Problem::to_formula( std::ostream &out ) const
{
    if (goals.size() > 0) {
        for (size_t i = 0; i < goals.size(); i++) {
            if (i > 0)
                out << " && ";
            out << "([]<> ego_" << rnd.get_intersection_str( goals[i] ) << ")";
        }
    }
}

std::ostream & operator<<( std::ostream &out, const Problem &prob )
{
    out << "{" << std::endl << "\"version\": " << 0 << "," << std::endl;
    out << "\"goals\": [" << std::endl;
    for (int i = 0; i < prob.goals.size(); i++) {
        if (i > 0)
            out << ", ";
        out << "\"ego_" << prob.rnd.get_intersection_str( prob.goals[i] ) << "\"";
        out << std::endl;
    }
    out << "]," << std::endl;
    out << "\"rnd\": " << prob.rnd << std::endl;
    out << std::endl << "}";
    return out;
}

std::string Problem::dumpJSON() const
{
    std::ostringstream out;
    out << *this;
    return out.str();
}

} // namespace dubins_traffic

#endif
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFCObject.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-03-01
//    @Module           :    NFCObject
//
// -------------------------------------------------------------------------

#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"

NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
    mSelf = self;
    m_pPluginManager = pLuginManager;

    m_pRecordManager = new NFCRecordManager(mSelf);
    m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
    m_pPropertyManager = new NFCPropertyManager(mSelf);
    m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}

NFCObject::~NFCObject()
{
    delete m_pComponentManager;
    delete m_pPropertyManager;
    delete m_pRecordManager;
    delete m_pHeartBeatManager;
}

bool NFCObject::Init()
{
    return true;
}

bool NFCObject::Shut()
{

    return true;
}

bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
    //ѭУɾԼ
    GetHeartBeatManager()->Execute(fLastTime, fAllTime);
    GetComponentManager()->Execute(fLastTime, fAllTime);

    return true;
}

bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
    return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}

bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
    return GetHeartBeatManager()->Exist(strHeartBeatName);
}

bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
    return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}

bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        pRecord->AddRecordHook(cb);

        return true;
    }

    return false;
}

bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
    if (pProperty)
    {
        pProperty->RegisterCallback(cb, NFCValueList());

        return true;
    }

    return false;
}

bool NFCObject::FindProperty(const std::string& strPropertyName)
{
    if (GetPropertyManager()->GetElement(strPropertyName))
    {
        return true;
    }

    return false;
}

bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetInt(nValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyFloat(const std::string& strPropertyName,  const float fValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetFloat(fValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetDouble(dwValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetString(strValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetObject(obj);

        return true;
    }

    return false;
}

int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryInt();
    }

    return -1;
}

float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryFloat();
    }

    return 0.0f;
}

double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryDouble();
    }

    return 0.0;
}

const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryString();
    }

    return NULL_STR;
}

NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryObject();
    }

    return 0;
}

bool NFCObject::FindRecord(const std::string& strRecordName)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return true;
    }

    return false;
}

bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
    }

    return false;
}

bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
    if (pRecord)
    {
        return pRecord->SetInt(nRow, nCol, nValue);
    }

    return false;
}

bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
    }

    return false;
}

bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
    if (pRecord)
    {
        return pRecord->SetFloat(nRow, nCol, fValue);
    }

    return false;
}

bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
    }

    return false;
}

bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
    if (pRecord)
    {
        return pRecord->SetDouble(nRow, nCol, dwValue);
    }

    return false;
}

bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
    }

    return false;
}

bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
    if (pRecord)
    {
        return pRecord->SetString(nRow, nCol, strValue.c_str());
    }

    return false;
}

bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
    }

    return false;
}

bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
    if (pRecord)
    {
        return pRecord->SetObject(nRow, nCol, obj);
    }

    return false;
}

int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
    }

    return 0;
}

int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryInt(nRow, nCol);
    }

    return 0;
}

float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
    }

    return 0.0f;
}

float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryFloat(nRow, nCol);
    }

    return 0.0f;
}

double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
    }

    return 0.0;
}

double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryDouble(nRow, nCol);
    }

    return 0.0;
}

const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordString(pRecord, strRecordName, nRow, nCol);
    }

    return NULL_STR;
}

const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryString(nRow, nCol);
    }

    return NULL_STR;
}

NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
    }

    return 0;
}

NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryObject(nRow, nCol);
    }

    return 0;
}

NFIRecordManager* NFCObject::GetRecordManager()
{
    return m_pRecordManager;
}

NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
    return m_pHeartBeatManager;
}

NFIPropertyManager* NFCObject::GetPropertyManager()
{
    return m_pPropertyManager;
}

NFIDENTID NFCObject::Self()
{
    return mSelf;
}

NFIComponentManager* NFCObject::GetComponentManager()
{
    return m_pComponentManager;
}

NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
    return m_pComponentManager->AddComponent(strComponentName);
}

NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
    return m_pComponentManager->Findomponent(strComponentName);
}
<commit_msg>fixed for build error<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFCObject.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-03-01
//    @Module           :    NFCObject
//
// -------------------------------------------------------------------------

#include "NFCObject.h"
#include "NFCRecordManager.h"
#include "NFCHeartBeatManager.h"
#include "NFCPropertyManager.h"
#include "NFCComponentManager.h"

NFCObject::NFCObject(const NFIDENTID& self, NFIPluginManager* pLuginManager)
{
    mSelf = self;
    m_pPluginManager = pLuginManager;

    m_pRecordManager = new NFCRecordManager(mSelf);
    m_pHeartBeatManager = new NFCHeartBeatManager(mSelf);
    m_pPropertyManager = new NFCPropertyManager(mSelf);
    m_pComponentManager = new NFCComponentManager(mSelf, m_pPluginManager);
}

NFCObject::~NFCObject()
{
    delete m_pComponentManager;
    delete m_pPropertyManager;
    delete m_pRecordManager;
    delete m_pHeartBeatManager;
}

bool NFCObject::Init()
{
    return true;
}

bool NFCObject::Shut()
{

    return true;
}

bool NFCObject::Execute(const float fLastTime, const float fAllTime)
{
    //ѭУɾԼ
    GetHeartBeatManager()->Execute(fLastTime, fAllTime);
    GetComponentManager()->Execute(fLastTime, fAllTime);

    return true;
}

bool NFCObject::AddHeartBeat(const std::string& strHeartBeatName, const HEART_BEAT_FUNCTOR_PTR& cb, const NFIValueList& var, const float fTime, const int nCount)
{
    return GetHeartBeatManager()->AddHeartBeat(mSelf , strHeartBeatName, cb, var, fTime, nCount);
}

bool NFCObject::FindHeartBeat(const std::string& strHeartBeatName)
{
    return GetHeartBeatManager()->Exist(strHeartBeatName);
}

bool NFCObject::RemoveHeartBeat(const std::string& strHeartBeatName)
{
    return GetHeartBeatManager()->RemoveHeartBeat(strHeartBeatName);
}

bool NFCObject::AddRecordCallBack(const std::string& strRecordName, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        pRecord->AddRecordHook(cb);

        return true;
    }

    return false;
}

bool NFCObject::AddPropertyCallBack(const std::string& strCriticalName, const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strCriticalName);
    if (pProperty)
    {
        pProperty->RegisterCallback(cb, NFCValueList());

        return true;
    }

    return false;
}

bool NFCObject::FindProperty(const std::string& strPropertyName)
{
    if (GetPropertyManager()->GetElement(strPropertyName))
    {
        return true;
    }

    return false;
}

bool NFCObject::SetPropertyInt(const std::string& strPropertyName, const int nValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetInt(nValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyFloat(const std::string& strPropertyName,  const float fValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetFloat(fValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyDouble(const std::string& strPropertyName, const double dwValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetDouble(dwValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyString(const std::string& strPropertyName, const std::string& strValue)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetString(strValue);

        return true;
    }

    return false;
}

bool NFCObject::SetPropertyObject(const std::string& strPropertyName, const NFIDENTID& obj)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {
        pProperty->SetObject(obj);

        return true;
    }

    return false;
}

int NFCObject::QueryPropertyInt(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryInt();
    }

    return -1;
}

float NFCObject::QueryPropertyFloat(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryFloat();
    }

    return 0.0f;
}

double NFCObject::QueryPropertyDouble(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryDouble();
    }

    return 0.0;
}

const std::string& NFCObject::QueryPropertyString(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryString();
    }

    return NULL_STR;
}

NFIDENTID NFCObject::QueryPropertyObject(const std::string& strPropertyName)
{
    NFIProperty* pProperty = GetPropertyManager()->GetElement(strPropertyName);
    if (pProperty)
    {

        return pProperty->QueryObject();
    }

    return 0;
}

bool NFCObject::FindRecord(const std::string& strRecordName)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return true;
    }

    return false;
}

bool NFCObject::SetRecordInt(const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordInt(pRecord, strRecordName, nRow, nCol, nValue);
    }

    return false;
}

bool NFCObject::SetRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const int nValue)
{
    if (pRecord)
    {
        return pRecord->SetInt(nRow, nCol, nValue);
    }

    return false;
}

bool NFCObject::SetRecordFloat(const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordFloat(pRecord, strRecordName, nRow, nCol, fValue);
    }

    return false;
}

bool NFCObject::SetRecordFloat(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const float fValue)
{
    if (pRecord)
    {
        return pRecord->SetFloat(nRow, nCol, fValue);
    }

    return false;
}

bool NFCObject::SetRecordDouble(const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordDouble(pRecord, strRecordName, nRow, nCol, dwValue);
    }

    return false;
}

bool NFCObject::SetRecordDouble(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const double dwValue)
{
    if (pRecord)
    {
        return pRecord->SetDouble(nRow, nCol, dwValue);
    }

    return false;
}

bool NFCObject::SetRecordString(const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordString(pRecord, strRecordName, nRow, nCol, strValue);
    }

    return false;
}

bool NFCObject::SetRecordString(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const std::string& strValue)
{
    if (pRecord)
    {
        return pRecord->SetString(nRow, nCol, strValue.c_str());
    }

    return false;
}

bool NFCObject::SetRecordObject(const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return SetRecordObject(pRecord, strRecordName, nRow, nCol, obj);
    }

    return false;
}

bool NFCObject::SetRecordObject(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol, const NFIDENTID& obj)
{
    if (pRecord)
    {
        return pRecord->SetObject(nRow, nCol, obj);
    }

    return false;
}

int NFCObject::QueryRecordInt(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordInt(pRecord, strRecordName, nRow, nCol);
    }

    return 0;
}

int NFCObject::QueryRecordInt(NFIRecord* pRecord, const std::string& strRecordName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryInt(nRow, nCol);
    }

    return 0;
}

float NFCObject::QueryRecordFloat(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordFloat(pRecord, strRecordName, nRow, nCol);
    }

    return 0.0f;
}

float NFCObject::QueryRecordFloat(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryFloat(nRow, nCol);
    }

    return 0.0f;
}

double NFCObject::QueryRecordDouble(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordDouble(pRecord, strRecordName, nRow, nCol);
    }

    return 0.0;
}

double NFCObject::QueryRecordDouble(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryDouble(nRow, nCol);
    }

    return 0.0;
}

const std::string& NFCObject::QueryRecordString(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordString(pRecord, strRecordName, nRow, nCol);
    }

    return NULL_STR;
}

const std::string& NFCObject::QueryRecordString(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryString(nRow, nCol);
    }

    return NULL_STR;
}

NFIDENTID NFCObject::QueryRecordObject(const std::string& strRecordName, const int nRow, const int nCol)
{
    NFIRecord* pRecord = GetRecordManager()->GetElement(strRecordName);
    if (pRecord)
    {
        return QueryRecordObject(pRecord, strRecordName, nRow, nCol);
    }

    return 0;
}

NFIDENTID NFCObject::QueryRecordObject(NFIRecord* pRecord, const std::string& strPropertyName, const int nRow, const int nCol)
{
    if (pRecord)
    {
        return pRecord->QueryObject(nRow, nCol);
    }

    return 0;
}

NFIRecordManager* NFCObject::GetRecordManager()
{
    return m_pRecordManager;
}

NFIHeartBeatManager* NFCObject::GetHeartBeatManager()
{
    return m_pHeartBeatManager;
}

NFIPropertyManager* NFCObject::GetPropertyManager()
{
    return m_pPropertyManager;
}

NFIDENTID NFCObject::Self()
{
    return mSelf;
}

NFIComponentManager* NFCObject::GetComponentManager()
{
    return m_pComponentManager;
}

NFIComponent* NFCObject::AddComponent( const std::string& strComponentName )
{
    return m_pComponentManager->AddComponent(strComponentName);
}

NFIComponent* NFCObject::FindComponent( const std::string& strComponentName )
{
    return m_pComponentManager->FindComponent(strComponentName);
}
<|endoftext|>