text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* $RCSfile: document.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2004-10-04 18:02:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DOCUMENT_HXX
#define DOCUMENT_HXX
#define SMDLL 1
#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif
#include <vcl/jobset.hxx>
class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;
#define HINT_DATACHANGED 1004
#define SM30BIDENT ((ULONG)0x534D3033L)
#define SM30IDENT ((ULONG)0x30334d53L)
#define SM304AIDENT ((ULONG)0x34303330L)
#define SM30VERSION ((ULONG)0x00010000L)
#define SM50VERSION ((ULONG)0x00010001L) //Unterschied zur SM30VERSION ist
//der neue Border im Format.
#define FRMIDENT ((ULONG)0x03031963L)
#define FRMVERSION ((ULONG)0x00010001L)
#define STAROFFICE_XML "StarOffice XML (Math)"
#define MATHML_XML "MathML XML (Math)"
/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
* ==========================================================================
*
* Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
* das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
* grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
* einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
* im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
* Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
* (etwa waehrend des Paints).
* Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
* oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
* fuer die der Access auch Friend der DocShell ist.
*/
class SmDocShell;
class EditEngine;
class EditEngineItemPool;
class SmPrinterAccess
{
Printer* pPrinter;
OutputDevice* pRefDev;
public:
SmPrinterAccess( SmDocShell &rDocShell );
~SmPrinterAccess();
Printer* GetPrinter() { return pPrinter; }
OutputDevice* GetRefDev() { return pRefDev; }
};
////////////////////////////////////////////////////////////
class SmDocShell : public SfxObjectShell, public SfxListener
{
friend class SmPrinterAccess;
String aText;
SmFormat aFormat;
SmParser aInterpreter;
String aAccText;
SmSymSetManager *pSymSetMgr;
SmNode *pTree;
SfxMenuBarManager *pMenuMgr;
SfxItemPool *pEditEngineItemPool;
EditEngine *pEditEngine;
SfxPrinter *pPrinter; //Siehe Kommentar zum SmPrinter Access!
Printer *pTmpPrinter; //ebenfalls
long nLeftBorder,
nRightBorder,
nTopBorder,
nBottomBorder;
USHORT nModifyCount;
BOOL bIsFormulaArranged;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType);
void RestartFocusTimer ();
BOOL Try3x( SvStorage *pStor, StreamMode eMode);
BOOL Try2x( SvStorage *pStor, StreamMode eMode);
BOOL WriteAsMathType3( SfxMedium& );
virtual void Draw(OutputDevice *pDevice,
const JobSetup & rSetup,
USHORT nAspect = ASPECT_CONTENT);
virtual void FillClass(SvGlobalName* pClassName,
ULONG* pFormat,
String* pAppName,
String* pFullTypeName,
String* pShortTypeName,
sal_Int32 nFileFormat ) const;
virtual BOOL SetData( const String& rData );
virtual ULONG GetMiscStatus() const;
virtual void OnDocumentPrinterChanged( Printer * );
virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Insert( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
void ImplSave( SvStorageStreamRef xStrm );
virtual BOOL Save();
virtual BOOL SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
Printer *GetPrt();
OutputDevice* GetRefDev();
// used to convert the formula text between different office versions
void ConvertText( String &rText, SmConvert eConv );
BOOL IsFormulaArranged() const { return bIsFormulaArranged; }
void SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
void ArrangeFormula();
virtual BOOL ConvertFrom(SfxMedium &rMedium);
BOOL InsertFrom(SfxMedium &rMedium);
BOOL ImportSM20File(SvStream *pStream);
void UpdateText();
public:
TYPEINFO();
SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
SFX_DECL_OBJECTFACTORY();
SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
virtual ~SmDocShell();
void LoadSymbols();
void SaveSymbols();
//Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
//und fuer die Kommunikation mit dem SFX!
//Alle internen Verwendungen des Printers sollten ausschlieslich uber
//den SmPrinterAccess funktionieren.
BOOL HasPrinter() { return 0 != pPrinter; }
SfxPrinter *GetPrinter() { GetPrt(); return pPrinter; }
void SetPrinter( SfxPrinter * );
const String &GetTitle() const;
const String &GetComment() const;
void SetText(const String& rBuffer);
String& GetText() { return (aText); }
void SetFormat(SmFormat& rFormat);
SmFormat& GetFormat() { return (aFormat); }
void Parse();
SmParser & GetParser() { return aInterpreter; }
const SmNode * GetFormulaTree() const { return pTree; }
void SetFormulaTree(SmNode *&rTree) { pTree = rTree; }
String GetAccessibleText();
EditEngine & GetEditEngine();
SfxItemPool & GetEditEngineItemPool();
SmSymSetManager & GetSymSetManager();
const SmSymSetManager & GetSymSetManager() const
{
return ((SmDocShell *) this)->GetSymSetManager();
}
void Draw(OutputDevice &rDev, Point &rPosition);
Size GetSize();
void Resize();
virtual SfxUndoManager *GetUndoManager ();
virtual SfxItemPool& GetPool();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet &);
virtual void SetVisArea (const Rectangle & rVisArea);
virtual void UIActivate (BOOL bActivate);
virtual void SetModified(BOOL bModified);
};
#endif
<commit_msg>INTEGRATION: CWS tl03 (1.18.124); FILE MERGED 2004/10/12 11:09:50 tl 1.18.124.2: RESYNC: (1.18-1.19); FILE MERGED 2004/09/24 11:25:41 tl 1.18.124.1: #i32296# loading of text font attributes in XML import fixed<commit_after>/*************************************************************************
*
* $RCSfile: document.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: obo $ $Date: 2004-11-15 16:42:02 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DOCUMENT_HXX
#define DOCUMENT_HXX
#define SMDLL 1
#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif
#include <vcl/jobset.hxx>
class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;
#define HINT_DATACHANGED 1004
#define SM30BIDENT ((ULONG)0x534D3033L)
#define SM30IDENT ((ULONG)0x30334d53L)
#define SM304AIDENT ((ULONG)0x34303330L)
#define SM30VERSION ((ULONG)0x00010000L)
#define SM50VERSION ((ULONG)0x00010001L) //Unterschied zur SM30VERSION ist
//der neue Border im Format.
#define FRMIDENT ((ULONG)0x03031963L)
#define FRMVERSION ((ULONG)0x00010001L)
#define STAROFFICE_XML "StarOffice XML (Math)"
#define MATHML_XML "MathML XML (Math)"
/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
* ==========================================================================
*
* Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
* das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
* grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
* einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
* im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
* Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
* (etwa waehrend des Paints).
* Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
* oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
* fuer die der Access auch Friend der DocShell ist.
*/
class SmDocShell;
class EditEngine;
class EditEngineItemPool;
class SmPrinterAccess
{
Printer* pPrinter;
OutputDevice* pRefDev;
public:
SmPrinterAccess( SmDocShell &rDocShell );
~SmPrinterAccess();
Printer* GetPrinter() { return pPrinter; }
OutputDevice* GetRefDev() { return pRefDev; }
};
////////////////////////////////////////////////////////////
class SmDocShell : public SfxObjectShell, public SfxListener
{
friend class SmPrinterAccess;
String aText;
SmFormat aFormat;
SmParser aInterpreter;
String aAccText;
SmSymSetManager *pSymSetMgr;
SmNode *pTree;
SfxMenuBarManager *pMenuMgr;
SfxItemPool *pEditEngineItemPool;
EditEngine *pEditEngine;
SfxPrinter *pPrinter; //Siehe Kommentar zum SmPrinter Access!
Printer *pTmpPrinter; //ebenfalls
long nLeftBorder,
nRightBorder,
nTopBorder,
nBottomBorder;
USHORT nModifyCount;
BOOL bIsFormulaArranged;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType);
void RestartFocusTimer ();
BOOL Try3x( SvStorage *pStor, StreamMode eMode);
BOOL Try2x( SvStorage *pStor, StreamMode eMode);
BOOL WriteAsMathType3( SfxMedium& );
virtual void Draw(OutputDevice *pDevice,
const JobSetup & rSetup,
USHORT nAspect = ASPECT_CONTENT);
virtual void FillClass(SvGlobalName* pClassName,
ULONG* pFormat,
String* pAppName,
String* pFullTypeName,
String* pShortTypeName,
sal_Int32 nFileFormat ) const;
virtual BOOL SetData( const String& rData );
virtual ULONG GetMiscStatus() const;
virtual void OnDocumentPrinterChanged( Printer * );
virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Insert( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
void ImplSave( SvStorageStreamRef xStrm );
virtual BOOL Save();
virtual BOOL SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
Printer *GetPrt();
OutputDevice* GetRefDev();
// used to convert the formula text between different office versions
void ConvertText( String &rText, SmConvert eConv );
BOOL IsFormulaArranged() const { return bIsFormulaArranged; }
void SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
void ArrangeFormula();
virtual BOOL ConvertFrom(SfxMedium &rMedium);
BOOL InsertFrom(SfxMedium &rMedium);
BOOL ImportSM20File(SvStream *pStream);
void UpdateText();
public:
TYPEINFO();
SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
SFX_DECL_OBJECTFACTORY();
SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
virtual ~SmDocShell();
void LoadSymbols();
void SaveSymbols();
//Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
//und fuer die Kommunikation mit dem SFX!
//Alle internen Verwendungen des Printers sollten ausschlieslich uber
//den SmPrinterAccess funktionieren.
BOOL HasPrinter() { return 0 != pPrinter; }
SfxPrinter *GetPrinter() { GetPrt(); return pPrinter; }
void SetPrinter( SfxPrinter * );
const String &GetTitle() const;
const String &GetComment() const;
void SetText(const String& rBuffer);
String& GetText() { return (aText); }
void SetFormat(SmFormat& rFormat);
const SmFormat& GetFormat() { return (aFormat); }
void Parse();
SmParser & GetParser() { return aInterpreter; }
const SmNode * GetFormulaTree() const { return pTree; }
void SetFormulaTree(SmNode *&rTree) { pTree = rTree; }
String GetAccessibleText();
EditEngine & GetEditEngine();
SfxItemPool & GetEditEngineItemPool();
SmSymSetManager & GetSymSetManager();
const SmSymSetManager & GetSymSetManager() const
{
return ((SmDocShell *) this)->GetSymSetManager();
}
void Draw(OutputDevice &rDev, Point &rPosition);
Size GetSize();
void Repaint();
virtual SfxUndoManager *GetUndoManager ();
virtual SfxItemPool& GetPool();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet &);
virtual void SetVisArea (const Rectangle & rVisArea);
virtual void UIActivate (BOOL bActivate);
virtual void SetModified(BOOL bModified);
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>Sequence24 targeted.<commit_after><|endoftext|>
|
<commit_before>// $Author: afinit $
// $Date$
// $Log$
// Contains the Process class for afin
#include "process.hpp"
#include <thread>
int max_search_loops;
int contig_sub_len;
int extend_len;
int max_sort_char;
int min_cov;
int min_overlap;
int max_threads;
int initial_trim;
int max_missed;
double stop_ext;
bool test_run;
int print_fused;
int screen_output;
int log_output;
int verbose;
int no_fusion;
double mismatch_threshold;
std::mutex log_mut;
////////////////////////////////////
//////// PROCESS DEFINITIONS ///////
////////////////////////////////////
// Process constructor
Process::Process(){
outfile = "afin_out";
readsfiles = "";
contigsfiles = "";
reads = 0;
contigs = 0;
fuse = 0;
max_iterations = 1;
// initialize unordered_map for iterable options
iterable_opts["max_search_loops"] = "10";
iterable_opts["contig_sub_len"] = "100";
iterable_opts["extend_len"] = "40";
iterable_opts["max_sort_char"] = "4";
iterable_opts["min_cov"] = "3";
iterable_opts["min_overlap"] = "20";
iterable_opts["initial_trim"] = "0";
iterable_opts["max_missed"] = "5";
iterable_opts["stop_ext"] = "0.5";
iterable_opts["mismatch_threshold"] = "0.1";
// Declare vector variables for storing iterable_opts
std::vector<int> max_search_loops_iter;
std::vector<int> contig_sub_len_iter;
std::vector<int> extend_len_iter;
std::vector<int> max_sort_char_iter;
std::vector<int> min_cov_iter;
std::vector<int> min_overlap_iter;
std::vector<int> initial_trim_iter;
std::vector<int> max_missed_iter;
std::vector<double> stop_ext_iter;
std::vector<double> mismatch_threshold_iter;
}
Process::~Process(){
delete fuse;
delete reads;
delete contigs;
}
// initalize logfile
void Process::logfile_init(){
Log::Inst()->open_log( outfile + ".log" );
// output starting option values
Log::Inst()->log_it( "OPTION VALUES" );
Log::Inst()->log_it( "contig_sub_len: " + std::to_string(contig_sub_len) );
Log::Inst()->log_it( "extend_len: " + std::to_string(extend_len) );
Log::Inst()->log_it( "max_search_loops: " + std::to_string(max_search_loops) );
Log::Inst()->log_it( "max_sort_char: " + std::to_string(max_sort_char) );
Log::Inst()->log_it( "min_cov: " + std::to_string(min_cov) );
Log::Inst()->log_it( "min_overlap: " + std::to_string(min_overlap) );
Log::Inst()->log_it( "initial_trim: " + std::to_string(initial_trim) );
Log::Inst()->log_it( "max_missed: " + std::to_string(max_missed) );
Log::Inst()->log_it( "mismatch_threshold: " + std::to_string(mismatch_threshold) );
Log::Inst()->log_it( "max_threads: " + std::to_string(max_threads) );
Log::Inst()->log_it( "stop_ext: " + std::to_string(stop_ext) );
}
// Parse option int
void Process::parse_option( std::string opt_key, std::vector<int>* iter_vect ){
std::string opt = iterable_opts[opt_key];
try{
// check for commas in string
if( ! opt.find(',') ){
iter_vect->push_back(std::stoi(opt));
}
else{
// split along commas if found
std::stringstream ss(opt);
std::string item;
while( getline( ss, item, ',' )){
iter_vect->push_back(std::stoi(item));
}
}
}
catch( std::exception const & e ){
Log::Inst()->log_it( "Error: " + std::string(e.what(), std::strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key );
exit(0);
}
}
// Parse option double
void Process::parse_option( std::string opt_key, std::vector<double>* iter_vect ){
std::string opt = iterable_opts[opt_key];
try{
// check for commas in string
if( ! opt.find(',') ){
iter_vect->push_back(std::stof(opt));
}
else{
// split along commas if found
std::stringstream ss(opt);
std::string item;
while( getline( ss, item, ',' )){
iter_vect->push_back(std::stof(item));
}
}
}
catch( std::exception const & e ){
Log::Inst()->log_it( "Error: " + std::string(e.what(), std::strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key );
exit(0);
}
}
// Populate iterable options vector
void Process::populate_iterables(){
// process iterable options
parse_option( "max_search_loops", &max_search_loops_iter );
parse_option( "contig_sub_len", &contig_sub_len_iter );
parse_option( "extend_len", &extend_len_iter );
parse_option( "max_sort_char", &max_sort_char_iter );
parse_option( "min_cov", &min_cov_iter );
parse_option( "min_overlap", &min_overlap_iter );
parse_option( "initial_trim", &initial_trim_iter );
parse_option( "max_missed", &max_missed_iter );
parse_option( "stop_ext", &stop_ext_iter );
parse_option( "mismatch_threshold", &mismatch_threshold_iter );
}
// set iterables global values at each iteration
// NOTE:: rebuild to check for length of vector
void Process::set_iterables( int i ){
// max_search_loops_iter
if( max_search_loops_iter.size() > i ){
max_search_loops = max_search_loops_iter[i];
}
else{
max_search_loops = max_search_loops_iter.back();
}
// contig_sub_len_iter
if( contig_sub_len_iter.size() > i ){
contig_sub_len = contig_sub_len_iter[i];
}
else{
contig_sub_len = contig_sub_len_iter.back();
}
// extend_len_iter
if( extend_len_iter.size() > i ){
extend_len = extend_len_iter[i];
}
else{
extend_len = extend_len_iter.back();
}
// max_sort_char_iter
if( max_sort_char_iter.size() > i ){
max_sort_char = max_sort_char_iter[i];
}
else{
max_sort_char = max_sort_char_iter.back();
}
// min_cov_iter
if( min_cov_iter.size() > i ){
min_cov = min_cov_iter[i];
}
else{
min_cov = min_cov_iter.back();
}
// min_overlap_iter
if( min_overlap_iter.size() > i ){
min_overlap = min_overlap_iter[i];
}
else{
min_overlap = min_overlap_iter.back();
}
// initial_trim_iter
if( initial_trim_iter.size() > i ){
initial_trim = initial_trim_iter[i];
}
else{
initial_trim = initial_trim_iter.back();
}
// max_missed_iter
if( max_missed_iter.size() > i ){
max_missed = max_missed_iter[i];
}
else{
max_missed = max_missed_iter.back();
}
// stop_ext_iter
if( stop_ext_iter.size() > i ){
stop_ext = stop_ext_iter[i];
}
else{
stop_ext = stop_ext_iter.back();
}
// mismatch_threshold_iter
if( mismatch_threshold_iter.size() > i ){
mismatch_threshold = mismatch_threshold_iter[i];
}
else{
mismatch_threshold = mismatch_threshold_iter.back();
}
}
// Initializes data structures and turns over control to run_manager()
void Process::start_run(){
// initialize logfile if logging enabled
if( log_output || screen_output ){
logfile_init();
}
// process iterable options
populate_iterables();
// import reads once
reads = new Readlist( readsfiles );
// loop through iterated options if present
for( int i=0; i < max_iterations; i++ ){
// prevent printing of fused contigs
if( no_fusion )
print_fused = 0;
// Set options for this iteration
set_iterables(i);
// log output file
Log::Inst()->log_it( std::string("output file: ") + outfile );
// initialize objects
contigs = new Contiglist( reads, contigsfiles, outfile );
fuse = new Fusion( contigs, reads );
Log::Inst()->log_it( "End initialization phase" );
// make initial attempt to fuse contigs
if( ! no_fusion )
fuse->run_fusion( true );
if( test_run )
contigs->output_contigs( 0, outfile + ".fus", "mid" );
run_manager();
// write contigs to fasta
contigs->create_final_fasta(i);
}
}
// Manages run
void Process::run_manager(){
// create thread array with max_thread entries
std::vector<std::thread> t;
Queue<int> qu;
// loop max search loops
for( int j=0; j<max_search_loops; j++ ){
Log::Inst()->log_it( "Begin Extensions" );
// initialize threads
for( int i=0; i<max_threads; i++ ){
t.push_back(std::thread( &Process::thread_worker, this, std::ref(qu), i ));
}
if( test_run ){
Log::Inst()->log_it( "contigs.size(): " + std::to_string(contigs->get_list_size()) + " max_threads: " + std::to_string(max_threads) );
}
// push each thread onto queue
for( int i=0; i<contigs->get_list_size(); i++ ){
qu.push( i );
}
// push stop signals onto queue for each thread
for( int i=0; i<max_threads; i++ ){
qu.push( -1 );
}
// join threads
for( int i=0; i<max_threads; i++ ){
t[i].join();
}
// remove threads from vector
t.erase( t.begin(), t.begin()+max_threads );
// removed for master branch until algorithm can be adjusted
if( ! no_fusion )
fuse->run_fusion( false );
if( test_run ){
contigs->output_contigs( 0, outfile + ".fus" + std::to_string(j), "mid" );
}
}
}
// Consume function which will act as the driver for an individual thread
void Process::thread_worker( Queue<int>& q, unsigned int id) {
for (;;) {
auto item = q.pop();
if( item == -1 ){
break;
}
else{
contigs->get_contig_ref(item)->extend( false );
contigs->get_contig_ref(item)->extend( true );
}
}
}
//////////////////////////
// END PROCESS ///////////
//////////////////////////
<commit_msg>add cstring include to process.cpp<commit_after>// $Author: afinit $
// $Date$
// $Log$
// Contains the Process class for afin
#include "process.hpp"
#include <cstring>
#include <thread>
int max_search_loops;
int contig_sub_len;
int extend_len;
int max_sort_char;
int min_cov;
int min_overlap;
int max_threads;
int initial_trim;
int max_missed;
double stop_ext;
bool test_run;
int print_fused;
int screen_output;
int log_output;
int verbose;
int no_fusion;
double mismatch_threshold;
std::mutex log_mut;
////////////////////////////////////
//////// PROCESS DEFINITIONS ///////
////////////////////////////////////
// Process constructor
Process::Process(){
outfile = "afin_out";
readsfiles = "";
contigsfiles = "";
reads = 0;
contigs = 0;
fuse = 0;
max_iterations = 1;
// initialize unordered_map for iterable options
iterable_opts["max_search_loops"] = "10";
iterable_opts["contig_sub_len"] = "100";
iterable_opts["extend_len"] = "40";
iterable_opts["max_sort_char"] = "4";
iterable_opts["min_cov"] = "3";
iterable_opts["min_overlap"] = "20";
iterable_opts["initial_trim"] = "0";
iterable_opts["max_missed"] = "5";
iterable_opts["stop_ext"] = "0.5";
iterable_opts["mismatch_threshold"] = "0.1";
// Declare vector variables for storing iterable_opts
std::vector<int> max_search_loops_iter;
std::vector<int> contig_sub_len_iter;
std::vector<int> extend_len_iter;
std::vector<int> max_sort_char_iter;
std::vector<int> min_cov_iter;
std::vector<int> min_overlap_iter;
std::vector<int> initial_trim_iter;
std::vector<int> max_missed_iter;
std::vector<double> stop_ext_iter;
std::vector<double> mismatch_threshold_iter;
}
Process::~Process(){
delete fuse;
delete reads;
delete contigs;
}
// initalize logfile
void Process::logfile_init(){
Log::Inst()->open_log( outfile + ".log" );
// output starting option values
Log::Inst()->log_it( "OPTION VALUES" );
Log::Inst()->log_it( "contig_sub_len: " + std::to_string(contig_sub_len) );
Log::Inst()->log_it( "extend_len: " + std::to_string(extend_len) );
Log::Inst()->log_it( "max_search_loops: " + std::to_string(max_search_loops) );
Log::Inst()->log_it( "max_sort_char: " + std::to_string(max_sort_char) );
Log::Inst()->log_it( "min_cov: " + std::to_string(min_cov) );
Log::Inst()->log_it( "min_overlap: " + std::to_string(min_overlap) );
Log::Inst()->log_it( "initial_trim: " + std::to_string(initial_trim) );
Log::Inst()->log_it( "max_missed: " + std::to_string(max_missed) );
Log::Inst()->log_it( "mismatch_threshold: " + std::to_string(mismatch_threshold) );
Log::Inst()->log_it( "max_threads: " + std::to_string(max_threads) );
Log::Inst()->log_it( "stop_ext: " + std::to_string(stop_ext) );
}
// Parse option int
void Process::parse_option( std::string opt_key, std::vector<int>* iter_vect ){
std::string opt = iterable_opts[opt_key];
try{
// check for commas in string
if( ! opt.find(',') ){
iter_vect->push_back(std::stoi(opt));
}
else{
// split along commas if found
std::stringstream ss(opt);
std::string item;
while( getline( ss, item, ',' )){
iter_vect->push_back(std::stoi(item));
}
}
}
catch( std::exception const & e ){
Log::Inst()->log_it( "Error: " + std::string(e.what(), strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key );
exit(0);
}
}
// Parse option double
void Process::parse_option( std::string opt_key, std::vector<double>* iter_vect ){
std::string opt = iterable_opts[opt_key];
try{
// check for commas in string
if( ! opt.find(',') ){
iter_vect->push_back(std::stof(opt));
}
else{
// split along commas if found
std::stringstream ss(opt);
std::string item;
while( getline( ss, item, ',' )){
iter_vect->push_back(std::stof(item));
}
}
}
catch( std::exception const & e ){
Log::Inst()->log_it( "Error: " + std::string(e.what(), strlen(e.what())) + " : Invalid values: " + opt + " For option: " + opt_key );
exit(0);
}
}
// Populate iterable options vector
void Process::populate_iterables(){
// process iterable options
parse_option( "max_search_loops", &max_search_loops_iter );
parse_option( "contig_sub_len", &contig_sub_len_iter );
parse_option( "extend_len", &extend_len_iter );
parse_option( "max_sort_char", &max_sort_char_iter );
parse_option( "min_cov", &min_cov_iter );
parse_option( "min_overlap", &min_overlap_iter );
parse_option( "initial_trim", &initial_trim_iter );
parse_option( "max_missed", &max_missed_iter );
parse_option( "stop_ext", &stop_ext_iter );
parse_option( "mismatch_threshold", &mismatch_threshold_iter );
}
// set iterables global values at each iteration
// NOTE:: rebuild to check for length of vector
void Process::set_iterables( int i ){
// max_search_loops_iter
if( max_search_loops_iter.size() > i ){
max_search_loops = max_search_loops_iter[i];
}
else{
max_search_loops = max_search_loops_iter.back();
}
// contig_sub_len_iter
if( contig_sub_len_iter.size() > i ){
contig_sub_len = contig_sub_len_iter[i];
}
else{
contig_sub_len = contig_sub_len_iter.back();
}
// extend_len_iter
if( extend_len_iter.size() > i ){
extend_len = extend_len_iter[i];
}
else{
extend_len = extend_len_iter.back();
}
// max_sort_char_iter
if( max_sort_char_iter.size() > i ){
max_sort_char = max_sort_char_iter[i];
}
else{
max_sort_char = max_sort_char_iter.back();
}
// min_cov_iter
if( min_cov_iter.size() > i ){
min_cov = min_cov_iter[i];
}
else{
min_cov = min_cov_iter.back();
}
// min_overlap_iter
if( min_overlap_iter.size() > i ){
min_overlap = min_overlap_iter[i];
}
else{
min_overlap = min_overlap_iter.back();
}
// initial_trim_iter
if( initial_trim_iter.size() > i ){
initial_trim = initial_trim_iter[i];
}
else{
initial_trim = initial_trim_iter.back();
}
// max_missed_iter
if( max_missed_iter.size() > i ){
max_missed = max_missed_iter[i];
}
else{
max_missed = max_missed_iter.back();
}
// stop_ext_iter
if( stop_ext_iter.size() > i ){
stop_ext = stop_ext_iter[i];
}
else{
stop_ext = stop_ext_iter.back();
}
// mismatch_threshold_iter
if( mismatch_threshold_iter.size() > i ){
mismatch_threshold = mismatch_threshold_iter[i];
}
else{
mismatch_threshold = mismatch_threshold_iter.back();
}
}
// Initializes data structures and turns over control to run_manager()
void Process::start_run(){
// initialize logfile if logging enabled
if( log_output || screen_output ){
logfile_init();
}
// process iterable options
populate_iterables();
// import reads once
reads = new Readlist( readsfiles );
// loop through iterated options if present
for( int i=0; i < max_iterations; i++ ){
// prevent printing of fused contigs
if( no_fusion )
print_fused = 0;
// Set options for this iteration
set_iterables(i);
// log output file
Log::Inst()->log_it( std::string("output file: ") + outfile );
// initialize objects
contigs = new Contiglist( reads, contigsfiles, outfile );
fuse = new Fusion( contigs, reads );
Log::Inst()->log_it( "End initialization phase" );
// make initial attempt to fuse contigs
if( ! no_fusion )
fuse->run_fusion( true );
if( test_run )
contigs->output_contigs( 0, outfile + ".fus", "mid" );
run_manager();
// write contigs to fasta
contigs->create_final_fasta(i);
}
}
// Manages run
void Process::run_manager(){
// create thread array with max_thread entries
std::vector<std::thread> t;
Queue<int> qu;
// loop max search loops
for( int j=0; j<max_search_loops; j++ ){
Log::Inst()->log_it( "Begin Extensions" );
// initialize threads
for( int i=0; i<max_threads; i++ ){
t.push_back(std::thread( &Process::thread_worker, this, std::ref(qu), i ));
}
if( test_run ){
Log::Inst()->log_it( "contigs.size(): " + std::to_string(contigs->get_list_size()) + " max_threads: " + std::to_string(max_threads) );
}
// push each thread onto queue
for( int i=0; i<contigs->get_list_size(); i++ ){
qu.push( i );
}
// push stop signals onto queue for each thread
for( int i=0; i<max_threads; i++ ){
qu.push( -1 );
}
// join threads
for( int i=0; i<max_threads; i++ ){
t[i].join();
}
// remove threads from vector
t.erase( t.begin(), t.begin()+max_threads );
// removed for master branch until algorithm can be adjusted
if( ! no_fusion )
fuse->run_fusion( false );
if( test_run ){
contigs->output_contigs( 0, outfile + ".fus" + std::to_string(j), "mid" );
}
}
}
// Consume function which will act as the driver for an individual thread
void Process::thread_worker( Queue<int>& q, unsigned int id) {
for (;;) {
auto item = q.pop();
if( item == -1 ){
break;
}
else{
contigs->get_contig_ref(item)->extend( false );
contigs->get_contig_ref(item)->extend( true );
}
}
}
//////////////////////////
// END PROCESS ///////////
//////////////////////////
<|endoftext|>
|
<commit_before>#include "FileIO.h"
#include "Symbol.h"
#include "Sprite.h"
#include "ChangeWindowViewSizeSJ.h"
#include <ee/FileHelper.h>
#include <ee/SymbolSearcher.h>
#include <ee/SymbolMgr.h>
#include <ee/SpriteFactory.h>
#include <ee/FetchAllVisitor.h>
#include <ee/Exception.h>
#include <easycomplex.h>
#include <fstream>
namespace eui
{
namespace window
{
void FileIO::Store(const char* filepath, const Symbol* sym)
{
Json::Value value;
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
value["name"] = sym->name;
sym->GetAnchorMgr().StoreToFile(value, dir);
value["view"]["width"] = sym->GetWidth();
value["view"]["height"] = sym->GetHeight();
// std::vector<ee::Sprite*> sprs;
// const_cast<Symbol*>(sym)->GetAnchorMgr().Traverse(ee::FetchAllVisitor<ee::Sprite>(sprs));
// value["wrapper filepath"] = StoreWrapper(filepath, sym->name, sprs);
StoreRefs(value, sym, dir);
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(filepath);
std::locale::global(std::locale("C"));
writer.write(fout, value);
fout.close();
}
void FileIO::Load(const char* filepath, Symbol* sym)
{
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath);
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
sym->name = value["name"].asString();
if (!value["view"].isNull()) {
int w = value["view"]["width"].asInt(),
h = value["view"]["height"].asInt();
sym->SetWidth(w);
sym->SetHeight(h);
sym->GetAnchorMgr().OnViewChanged(w, h);
ChangeWindowViewSizeSJ::Instance()->Change(w, h);
}
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
LoadSprites(value, sym, dir);
LoadRefs(value, sym, dir);
}
void FileIO::FetchSprites(const std::string& filepath, std::vector<ee::Sprite*>& sprs)
{
std::string dir = ee::FileHelper::GetFileDir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
int idx = 0;
Json::Value spr_val = val["sprite"][idx++];
while (!spr_val.isNull()) {
std::string path = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(path);
if (!sym) {
std::string filepath = spr_val["filepath"].asString();
throw ee::Exception("Symbol doesn't exist, [dir]:%s, [file]:%s !", dir.c_str(), filepath.c_str());
}
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
spr->AddReference();
sprs.push_back(spr);
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["sprite"][idx++];
}
idx = 0;
Json::Value ref_val = val["ref_spr"][idx++];
while (!ref_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, ref_val);
FetchSprites(filepath, sprs);
ref_val = val["ref_spr"][idx++];
}
}
std::string FileIO::StoreWrapper(const std::string& filepath, const std::string& name,
const std::vector<ee::Sprite*>& sprs)
{
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
ecomplex::Symbol wrapper_complex;
for (int i = 0, n = sprs.size(); i < n; ++i) {
wrapper_complex.Add(sprs[i]);
}
std::string filename = filepath.substr(0, filepath.find_last_of('_'));
std::string wrapper_path = filename + "_wrapper_complex[gen].json";
wrapper_complex.SetFilepath(wrapper_path);
wrapper_complex.name = name;
ecomplex::FileStorer::Store(wrapper_path.c_str(), &wrapper_complex);
return ee::FileHelper::GetRelativePath(dir, wrapper_path);
}
void FileIO::LoadSprites(const Json::Value& val, Symbol* sym, const std::string& dir)
{
AnchorMgr& anchors = sym->GetAnchorMgr();
int idx = 0;
Json::Value spr_val = val["sprite"][idx++];
while (!spr_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
anchors.Insert(spr);
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["sprite"][idx++];
}
}
void FileIO::StoreRefs(Json::Value& val, const Symbol* sym, const std::string& dir)
{
const std::vector<Sprite*>& sprs = sym->GetExtRefs();
for (int i = 0, n = sprs.size(); i < n; ++i) {
Sprite* spr = sprs[i];
std::string filepath = dynamic_cast<const ee::Symbol*>(spr->GetSymbol())->GetFilepath();
Json::Value spr_val;
spr_val["filepath"] = ee::FileHelper::GetRelativePath(dir, filepath);
spr->Store(spr_val);
val["ref_spr"][i] = spr_val;
FileIO::Store(filepath.c_str(), dynamic_cast<const Symbol*>(spr->GetSymbol()));
}
}
void FileIO::LoadRefs(const Json::Value& val, Symbol* sym, const std::string& dir)
{
int idx = 0;
Json::Value spr_val = val["ref_spr"][idx++];
while (!spr_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
dynamic_cast<Symbol*>(sym)->InsertExtRef(static_cast<Sprite*>(spr));
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["ref_spr"][idx++];
}
}
}
}<commit_msg>[FIXED] eui load<commit_after>#include "FileIO.h"
#include "Symbol.h"
#include "Sprite.h"
#include "ChangeWindowViewSizeSJ.h"
#include <ee/FileHelper.h>
#include <ee/SymbolSearcher.h>
#include <ee/SymbolMgr.h>
#include <ee/SpriteFactory.h>
#include <ee/FetchAllVisitor.h>
#include <ee/Exception.h>
#include <easycomplex.h>
#include <fstream>
namespace eui
{
namespace window
{
void FileIO::Store(const char* filepath, const Symbol* sym)
{
Json::Value value;
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
value["name"] = sym->name;
sym->GetAnchorMgr().StoreToFile(value, dir);
value["view"]["width"] = sym->GetWidth();
value["view"]["height"] = sym->GetHeight();
// std::vector<ee::Sprite*> sprs;
// const_cast<Symbol*>(sym)->GetAnchorMgr().Traverse(ee::FetchAllVisitor<ee::Sprite>(sprs));
// value["wrapper filepath"] = StoreWrapper(filepath, sym->name, sprs);
StoreRefs(value, sym, dir);
Json::StyledStreamWriter writer;
std::locale::global(std::locale(""));
std::ofstream fout(filepath);
std::locale::global(std::locale("C"));
writer.write(fout, value);
fout.close();
}
void FileIO::Load(const char* filepath, Symbol* sym)
{
Json::Value value;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath);
std::locale::global(std::locale("C"));
reader.parse(fin, value);
fin.close();
sym->name = value["name"].asString();
if (!value["view"].isNull()) {
int w = value["view"]["width"].asInt(),
h = value["view"]["height"].asInt();
sym->SetWidth(w);
sym->SetHeight(h);
sym->GetAnchorMgr().OnViewChanged(w, h);
ChangeWindowViewSizeSJ::Instance()->Change(w, h);
}
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
LoadSprites(value, sym, dir);
LoadRefs(value, sym, dir);
}
void FileIO::FetchSprites(const std::string& filepath, std::vector<ee::Sprite*>& sprs)
{
std::string dir = ee::FileHelper::GetFileDir(filepath);
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
int idx = 0;
Json::Value spr_val = val["sprite"][idx++];
while (!spr_val.isNull()) {
std::string path = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(path);
if (!sym) {
std::string filepath = spr_val["filepath"].asString();
throw ee::Exception("Symbol doesn't exist, [dir]:%s, [file]:%s !", dir.c_str(), filepath.c_str());
}
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
spr->AddReference();
sprs.push_back(spr);
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["sprite"][idx++];
}
idx = 0;
Json::Value ref_val = val["ref_spr"][idx++];
while (!ref_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, ref_val);
FetchSprites(filepath, sprs);
ref_val = val["ref_spr"][idx++];
}
}
std::string FileIO::StoreWrapper(const std::string& filepath, const std::string& name,
const std::vector<ee::Sprite*>& sprs)
{
std::string dir = ee::FileHelper::GetFileDir(filepath) + "\\";
ecomplex::Symbol wrapper_complex;
for (int i = 0, n = sprs.size(); i < n; ++i) {
wrapper_complex.Add(sprs[i]);
}
std::string filename = filepath.substr(0, filepath.find_last_of('_'));
std::string wrapper_path = filename + "_wrapper_complex[gen].json";
wrapper_complex.SetFilepath(wrapper_path);
wrapper_complex.name = name;
ecomplex::FileStorer::Store(wrapper_path.c_str(), &wrapper_complex);
return ee::FileHelper::GetRelativePath(dir, wrapper_path);
}
void FileIO::LoadSprites(const Json::Value& val, Symbol* sym, const std::string& dir)
{
AnchorMgr& anchors = sym->GetAnchorMgr();
int idx = 0;
Json::Value spr_val = val["sprite"][idx++];
while (!spr_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
anchors.Insert(spr);
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["sprite"][idx++];
}
}
void FileIO::StoreRefs(Json::Value& val, const Symbol* sym, const std::string& dir)
{
const std::vector<Sprite*>& sprs = sym->GetExtRefs();
for (int i = 0, n = sprs.size(); i < n; ++i) {
Sprite* spr = sprs[i];
std::string filepath = dynamic_cast<const ee::Symbol*>(spr->GetSymbol())->GetFilepath();
Json::Value spr_val;
spr_val["filepath"] = ee::FileHelper::GetRelativePath(dir, filepath);
spr->Store(spr_val);
val["ref_spr"][i] = spr_val;
FileIO::Store(filepath.c_str(), dynamic_cast<const Symbol*>(spr->GetSymbol()));
}
}
void FileIO::LoadRefs(const Json::Value& val, Symbol* top_sym, const std::string& dir)
{
int idx = 0;
Json::Value spr_val = val["ref_spr"][idx++];
while (!spr_val.isNull()) {
std::string filepath = ee::SymbolSearcher::GetSymbolPath(dir, spr_val);
ee::Symbol* sym = ee::SymbolMgr::Instance()->FetchSymbol(filepath);
ee::Sprite* spr = ee::SpriteFactory::Instance()->Create(sym);
spr->Load(spr_val);
top_sym->InsertExtRef(static_cast<Sprite*>(spr));
spr->RemoveReference();
sym->RemoveReference();
spr_val = val["ref_spr"][idx++];
}
}
}
}<|endoftext|>
|
<commit_before><commit_msg>Added noexcept example.<commit_after><|endoftext|>
|
<commit_before>#include "binary_data_figures_reader.h"
namespace data_source {
using namespace dom::figures;
bool BinaryDataFiguresReader::isFigureQueueEmpty() {
std::lock_guard<std::mutex> lock(m_queue_mutex);
return m_figure_queue.empty();
}
std::shared_ptr<Figure> BinaryDataFiguresReader::popFigure() {
std::lock_guard<std::mutex> lock(m_queue_mutex);
std::shared_ptr<Figure> figure = m_figure_queue.front();
m_figure_queue.pop();
return figure;
}
uint32_t BinaryDataFiguresReader::read(const char* data, const int data_size) {
uint32_t cursor = 0;
int32_t data_available = data_size - cursor;
while (data_available > 0) {
int figure_id = data[cursor];
BinaryFigureReader* binaryreader = nullptr;
cursor++;
data_available = data_size - cursor;
Type type = m_id_to_type_ref[figure_id];
switch (type) {
case Type::square:
binaryreader = &m_square_reader;
break;
case Type::rectangle:
binaryreader = &m_rectangle_reader;
break;
case Type::circle:
binaryreader = &m_circle_reader;
break;
case Type::polygon:
binaryreader = &m_polygon_reader;
break;
default:
// TODO: handle unknown figure!
break;
}
if (binaryreader != nullptr) {
std::shared_ptr<dom::figures::Figure> figure;
cursor += binaryreader->read(&data[cursor], data_available);
{
std::lock_guard<std::mutex> lock(m_queue_mutex);
m_figure_queue.push(binaryreader->getFigure());
}
}
data_available = data_size - cursor;
}
return cursor;
}
} // namespace
<commit_msg>very small refactor in binary data reader<commit_after>#include "binary_data_figures_reader.h"
namespace data_source {
using namespace dom::figures;
bool BinaryDataFiguresReader::isFigureQueueEmpty() {
std::lock_guard<std::mutex> lock(m_queue_mutex);
return m_figure_queue.empty();
}
std::shared_ptr<Figure> BinaryDataFiguresReader::popFigure() {
std::lock_guard<std::mutex> lock(m_queue_mutex);
std::shared_ptr<Figure> figure = m_figure_queue.front();
m_figure_queue.pop();
return figure;
}
uint32_t BinaryDataFiguresReader::read(const char* data, const int data_size) {
uint32_t cursor = 0;
while (data_size - cursor > 0) {
BinaryFigureReader* binaryreader = nullptr;
int figure_id = data[cursor++];
Type type = m_id_to_type_ref[figure_id];
switch (type) {
case Type::square:
binaryreader = &m_square_reader;
break;
case Type::rectangle:
binaryreader = &m_rectangle_reader;
break;
case Type::circle:
binaryreader = &m_circle_reader;
break;
case Type::polygon:
binaryreader = &m_polygon_reader;
break;
default:
std::cout << "Unknown figure in binary data: " << figure_id << std::endl;
throw std::exception();
}
if (binaryreader != nullptr) {
std::shared_ptr<dom::figures::Figure> figure;
cursor += binaryreader->read(&data[cursor], data_size - cursor);
{
std::lock_guard<std::mutex> lock(m_queue_mutex);
m_figure_queue.push(binaryreader->getFigure());
}
}
else
{
std::cout << "Binary reader is nullptr!" << std::endl;
throw std::exception();
}
}
return cursor;
}
} // namespace
<|endoftext|>
|
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/Filesystem.h>
#include <GG/adobe/future/widgets/headers/window_server.hpp>
#include <GG/adobe/future/widgets/headers/factory.hpp>
#include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp>
#include <GG/adobe/algorithm/for_each.hpp>
#include <GG/adobe/future/resources.hpp>
#include <GG/GUI.h>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
window_server_t::window_server_t(sheet_t& sheet,
behavior_t& behavior,
vm_lookup_t& vm_lookup,
const button_notifier_t& button_notifier,
const signal_notifier_t& signal_notifier,
const row_factory_t* row_factory,
const widget_factory_t& factory) :
sheet_m(sheet),
behavior_m(behavior),
vm_lookup_m(vm_lookup),
button_notifier_m(button_notifier),
signal_notifier_m(signal_notifier),
row_factory_m(row_factory),
widget_factory_m(factory)
{}
/*************************************************************************************************/
eve_client_holder& window_server_t::client_holder()
{
if (!window_m)
throw std::runtime_error("No top view!");
return *window_m;
}
/*************************************************************************************************/
void window_server_t::run(const char* name)
{
boost::filesystem::path path(GG::UTF8ToPath(name));
boost::filesystem::path file_name;
try {
file_name = find_resource(name);
} catch (...) {
file_name = path;
}
boost::filesystem::ifstream stream(file_name);
/* Update before attaching the window so that we can correctly capture
contributing for reset. */
sheet_m.update();
window_m.reset(
make_view(GG::PathToUTF8(file_name),
line_position_t::getline_proc_t(),
stream,
sheet_m,
behavior_m,
vm_lookup_m,
button_notifier_m,
boost::bind(&window_server_t::button_handler, this, _1, _2),
signal_notifier_m,
row_factory_m ? *row_factory_m : row_factory_t(),
size_enum_t(),
default_widget_factory_proc_with_factory(widget_factory_m)).release()
);
sheet_m.update(); // Force values to their correct states.
window_m->path_m = file_name;
window_m->eve_m.evaluate(eve_t::evaluate_nested);
window_m->show_window_m();
window_m->root_display_m->Run();
}
/*************************************************************************************************/
void window_server_t::run(
std::istream& data,
const boost::filesystem::path& path,
const line_position_t::getline_proc_t& getline_proc
) {
/* Update before attaching the window so that we can correctly capture
contributing for reset. */
sheet_m.update();
//
// REVISIT (ralpht): Where does this made-up filename get used? Does it
// need to be localized or actually be an existing file?
//
// REVISIT (fbrereto) : The file name is for error reporting purposes;
// see the const char* push_back API where this is filled in. It should
// be valid, lest the user not know the erroneous file.
//
window_m.reset(
make_view(GG::PathToUTF8(path),
getline_proc,
data,
sheet_m,
behavior_m,
vm_lookup_m,
button_notifier_m,
boost::bind(&window_server_t::button_handler, this, _1, _2),
signal_notifier_m,
row_factory_m ? *row_factory_m : row_factory_t(),
size_enum_t(),
default_widget_factory_proc_with_factory(widget_factory_m)).release()
);
sheet_m.update(); // Force values to their correct states.
window_m->path_m = path;
window_m->eve_m.evaluate(eve_t::evaluate_nested);
window_m->show_window_m();
window_m->root_display_m->Run();
}
/****************************************************************************************************/
bool window_server_t::button_handler(adobe::name_t action,
const adobe::any_regular_t& value)
{
bool retval = false;
if (action == static_name_t("reset")) {
sheet_m.set(window_m->contributing_m);
sheet_m.update();
} else if (action == static_name_t("cancel")) {
sheet_m.set(window_m->contributing_m);
sheet_m.update();
retval = true;
} else if (action == static_name_t("ok")) {
retval = true;
} else {
retval = button_notifier_m(action, value);
}
if (retval)
window_m->root_display_m->EndRun();
return retval;
}
/****************************************************************************************************/
}
/****************************************************************************************************/
<commit_msg>Reimplemented window_server_t::run(const char*) in terms of the other run() overload.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/Filesystem.h>
#include <GG/adobe/future/widgets/headers/window_server.hpp>
#include <GG/adobe/future/widgets/headers/factory.hpp>
#include <GG/adobe/future/widgets/headers/virtual_machine_extension.hpp>
#include <GG/adobe/algorithm/for_each.hpp>
#include <GG/adobe/future/resources.hpp>
#include <GG/GUI.h>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
window_server_t::window_server_t(sheet_t& sheet,
behavior_t& behavior,
vm_lookup_t& vm_lookup,
const button_notifier_t& button_notifier,
const signal_notifier_t& signal_notifier,
const row_factory_t* row_factory,
const widget_factory_t& factory) :
sheet_m(sheet),
behavior_m(behavior),
vm_lookup_m(vm_lookup),
button_notifier_m(button_notifier),
signal_notifier_m(signal_notifier),
row_factory_m(row_factory),
widget_factory_m(factory)
{}
/*************************************************************************************************/
eve_client_holder& window_server_t::client_holder()
{
if (!window_m)
throw std::runtime_error("No top view!");
return *window_m;
}
/*************************************************************************************************/
void window_server_t::run(const char* name)
{
boost::filesystem::path path(GG::UTF8ToPath(name));
boost::filesystem::path file_name;
try {
file_name = find_resource(name);
} catch (...) {
file_name = path;
}
boost::filesystem::ifstream stream(file_name);
run(stream, file_name, line_position_t::getline_proc_t());
}
/*************************************************************************************************/
void window_server_t::run(
std::istream& data,
const boost::filesystem::path& path,
const line_position_t::getline_proc_t& getline_proc
) {
/* Update before attaching the window so that we can correctly capture
contributing for reset. */
sheet_m.update();
//
// REVISIT (ralpht): Where does this made-up filename get used? Does it
// need to be localized or actually be an existing file?
//
// REVISIT (fbrereto) : The file name is for error reporting purposes;
// see the const char* push_back API where this is filled in. It should
// be valid, lest the user not know the erroneous file.
//
window_m.reset(
make_view(GG::PathToUTF8(path),
getline_proc,
data,
sheet_m,
behavior_m,
vm_lookup_m,
button_notifier_m,
boost::bind(&window_server_t::button_handler, this, _1, _2),
signal_notifier_m,
row_factory_m ? *row_factory_m : row_factory_t(),
size_enum_t(),
default_widget_factory_proc_with_factory(widget_factory_m)).release()
);
sheet_m.update(); // Force values to their correct states.
window_m->path_m = path;
window_m->eve_m.evaluate(eve_t::evaluate_nested);
window_m->show_window_m();
window_m->root_display_m->Run();
}
/****************************************************************************************************/
bool window_server_t::button_handler(adobe::name_t action,
const adobe::any_regular_t& value)
{
bool retval = false;
if (action == static_name_t("reset")) {
sheet_m.set(window_m->contributing_m);
sheet_m.update();
} else if (action == static_name_t("cancel")) {
sheet_m.set(window_m->contributing_m);
sheet_m.update();
retval = true;
} else if (action == static_name_t("ok")) {
retval = true;
} else {
retval = button_notifier_m(action, value);
}
if (retval)
window_m->root_display_m->EndRun();
return retval;
}
/****************************************************************************************************/
}
/****************************************************************************************************/
<|endoftext|>
|
<commit_before>#include <ir/index_manager/index/OutputDescriptor.h>
#include <cassert>
using namespace izenelib::ir::indexmanager;
OutputDescriptor::OutputDescriptor()
:pVocOutput_(NULL)
,pDPostingOutput_(NULL)
,pPPostingOutput_(NULL)
,bDestroy_(false)
,pDirectory_(0)
{
}
OutputDescriptor::OutputDescriptor(IndexOutput* pVocOutput,IndexOutput* pDPostingOutput,IndexOutput* pPPostingOutput,bool bDestroy)
:pVocOutput_(pVocOutput)
,pDPostingOutput_(pDPostingOutput)
,pPPostingOutput_(pPPostingOutput)
,bDestroy_(bDestroy)
,pDirectory_(0)
{
}
OutputDescriptor::~OutputDescriptor()
{
if (bDestroy_)
{
if (pVocOutput_)
delete pVocOutput_;
if (pDPostingOutput_)
delete pDPostingOutput_;
if (pPPostingOutput_)
delete pPPostingOutput_;
}
pVocOutput_ = NULL;
pDPostingOutput_ = NULL;
pPPostingOutput_ = NULL;
}
void OutputDescriptor::flush()
{
assert(pVocOutput_ && pDPostingOutput_ && pPPostingOutput_);
pVocOutput_->flush();
pDPostingOutput_->flush();
if(pPPostingOutput_)
pPPostingOutput_->flush();
}
<commit_msg>when indexmode = DOCLEVEL, the pDPostingOutput_ is NULL, so delete the check for it<commit_after>#include <ir/index_manager/index/OutputDescriptor.h>
#include <cassert>
using namespace izenelib::ir::indexmanager;
OutputDescriptor::OutputDescriptor()
:pVocOutput_(NULL)
,pDPostingOutput_(NULL)
,pPPostingOutput_(NULL)
,bDestroy_(false)
,pDirectory_(0)
{
}
OutputDescriptor::OutputDescriptor(IndexOutput* pVocOutput,IndexOutput* pDPostingOutput,IndexOutput* pPPostingOutput,bool bDestroy)
:pVocOutput_(pVocOutput)
,pDPostingOutput_(pDPostingOutput)
,pPPostingOutput_(pPPostingOutput)
,bDestroy_(bDestroy)
,pDirectory_(0)
{
}
OutputDescriptor::~OutputDescriptor()
{
if (bDestroy_)
{
if (pVocOutput_)
delete pVocOutput_;
if (pDPostingOutput_)
delete pDPostingOutput_;
if (pPPostingOutput_)
delete pPPostingOutput_;
}
pVocOutput_ = NULL;
pDPostingOutput_ = NULL;
pPPostingOutput_ = NULL;
}
void OutputDescriptor::flush()
{
assert(pVocOutput_ && pDPostingOutput_);
pVocOutput_->flush();
pDPostingOutput_->flush();
if(pPPostingOutput_)
pPPostingOutput_->flush();
}
<|endoftext|>
|
<commit_before>#include "problemes.h"
#include "utilitaires.h"
#include "combinatoire.h"
typedef boost::multiprecision::cpp_int nombre;
namespace {
struct noeud {
noeud(long double x1_, long double y1_, long double x2_, long double y2_) :
x1(x1_), y1(y1_), x2(x2_), y2(y2_) {}
long double x1;
long double y1;
long double x2;
long double y2;
};
}
ENREGISTRER_PROBLEME(395, "Under The Rainbow") {
// The Pythagorean tree is a fractal generated by the following procedure:
//
//Start with a unit square. Then, calling one of the sides its base (in the animation, the bottom side is the base):
//
// 1. Attach a right triangle to the side opposite the base, with the hypotenuse coinciding with that side and with
// the sides in a 3-4-5 ratio. Note that the smaller side of the triangle must be on the 'right' side with respect
// to the base (see animation).
// 2. Attach a square to each leg of the right triangle, with one of its sides coinciding with that leg.
// 3. Repeat this procedure for both squares, considering as their bases the sides touching the triangle.
//
// The resulting figure, after an infinite number of iterations, is the Pythagorean tree.
//
// p395_pythagorean.gif
//
// It can be shown that there exists at least one rectangle, whose sides are parallel to the largest square of the
//
// Pythagorean tree, which encloses the Pythagorean tree completely.
//
// Find the smallest area possible for such a bounding rectangle, and give your answer rounded to 10 decimal places.
long double xMax = 1, yMax = 0, xMin = 0, yMin = -1;
std::vector<noeud> noeuds;
noeuds.emplace_back(0, 0, 1, 0);
for (int i = 1; i < 100; ++i) {
std::vector<noeud> suivants;
for (auto x : noeuds) {
xMax = std::max(xMax, std::max(x.x1, x.x2));
xMin = std::min(xMin, std::min(x.x1, x.x2));
yMax = std::max(yMax, std::max(x.y1, x.y2));
yMin = std::min(yMin, std::min(x.y1, x.y2));
long double dx = x.x2 - x.x1;
long double dy = x.y2 - x.y1;
if (xMin <= x.x1 + std::min(5 * dx, -5 * dx) + std::min(-5 * dy, 2 * dy) &&
xMax >= x.x1 + std::max(5 * dx, -5 * dx) + std::max(-5 * dy, 2 * dy) &&
yMin <= x.y1 + std::min(5 * dx, -2 * dx) + std::min(-5 * dy, 5 * dy) &&
yMax >= x.y1 + std::max(5 * dx, -2 * dx) + std::max(-5 * dy, 5 * dy))
continue;
suivants.emplace_back(x.x1 - 0.48l * dx - 0.64l * dy, x.y1 + 0.64l * dx - 0.48l * dy,
x.x1 + 0.16l * dx - 1.12l * dy, x.y1 + 1.12l * dx + 0.16l * dy);
suivants.emplace_back(x.x1 + 1.12l * dx - 0.84l * dy, x.y1 + 0.84l * dx + 1.12l * dy,
x.x1 + 1.48l * dx - 0.36l * dy, x.y1 + 0.36l * dx + 1.48l * dy);
}
std::swap(noeuds, suivants);
std::cout << "nodes.size() = " << noeuds.size() << ", aire = "
<< std::to_string((xMax - xMin) * (yMax - yMin), 10) << std::endl;
}
std::cout << "xMax = " << xMax << ", yMax = " << yMax << ", xMin = " << xMin << ", yMin = " << yMin << std::endl;
long double aire = (xMax - xMin) * (yMax - yMin);
return std::to_string(aire, 10);
}
<commit_msg>Update probleme395.cpp<commit_after>#include "problemes.h"
#include "utilitaires.h"
#include "combinatoire.h"
typedef boost::multiprecision::cpp_int nombre;
namespace {
struct noeud {
noeud(long double x1_, long double y1_, long double x2_, long double y2_) :
x1(x1_), y1(y1_), x2(x2_), y2(y2_) {}
long double x1;
long double y1;
long double x2;
long double y2;
};
}
ENREGISTRER_PROBLEME(395, "Pythagorean tree") {
// The Pythagorean tree is a fractal generated by the following procedure:
//
//Start with a unit square. Then, calling one of the sides its base (in the animation, the bottom side is the base):
//
// 1. Attach a right triangle to the side opposite the base, with the hypotenuse coinciding with that side and with
// the sides in a 3-4-5 ratio. Note that the smaller side of the triangle must be on the 'right' side with respect
// to the base (see animation).
// 2. Attach a square to each leg of the right triangle, with one of its sides coinciding with that leg.
// 3. Repeat this procedure for both squares, considering as their bases the sides touching the triangle.
//
// The resulting figure, after an infinite number of iterations, is the Pythagorean tree.
//
// p395_pythagorean.gif
//
// It can be shown that there exists at least one rectangle, whose sides are parallel to the largest square of the
//
// Pythagorean tree, which encloses the Pythagorean tree completely.
//
// Find the smallest area possible for such a bounding rectangle, and give your answer rounded to 10 decimal places.
long double xMax = 1, yMax = 0, xMin = 0, yMin = -1;
std::vector<noeud> noeuds;
noeuds.emplace_back(0, 0, 1, 0);
for (int i = 1; i < 100; ++i) {
std::vector<noeud> suivants;
for (auto x : noeuds) {
xMax = std::max(xMax, std::max(x.x1, x.x2));
xMin = std::min(xMin, std::min(x.x1, x.x2));
yMax = std::max(yMax, std::max(x.y1, x.y2));
yMin = std::min(yMin, std::min(x.y1, x.y2));
long double dx = x.x2 - x.x1;
long double dy = x.y2 - x.y1;
if (xMin <= x.x1 + std::min(5 * dx, -5 * dx) + std::min(-5 * dy, 2 * dy) &&
xMax >= x.x1 + std::max(5 * dx, -5 * dx) + std::max(-5 * dy, 2 * dy) &&
yMin <= x.y1 + std::min(5 * dx, -2 * dx) + std::min(-5 * dy, 5 * dy) &&
yMax >= x.y1 + std::max(5 * dx, -2 * dx) + std::max(-5 * dy, 5 * dy))
continue;
suivants.emplace_back(x.x1 - 0.48l * dx - 0.64l * dy, x.y1 + 0.64l * dx - 0.48l * dy,
x.x1 + 0.16l * dx - 1.12l * dy, x.y1 + 1.12l * dx + 0.16l * dy);
suivants.emplace_back(x.x1 + 1.12l * dx - 0.84l * dy, x.y1 + 0.84l * dx + 1.12l * dy,
x.x1 + 1.48l * dx - 0.36l * dy, x.y1 + 0.36l * dx + 1.48l * dy);
}
std::swap(noeuds, suivants);
std::cout << "nodes.size() = " << noeuds.size() << ", aire = "
<< std::to_string((xMax - xMin) * (yMax - yMin), 10) << std::endl;
}
std::cout << "xMax = " << xMax << ", yMax = " << yMax << ", xMin = " << xMin << ", yMin = " << yMin << std::endl;
long double aire = (xMax - xMin) * (yMax - yMin);
return std::to_string(aire, 10);
}
<|endoftext|>
|
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2005-2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/valid/TopologyValidationError.java rev. 1.14 (JTS-1.7)
*
**********************************************************************/
#include <geos/operation/valid/TopologyValidationError.h>
#include <geos/geom/Coordinate.h>
#include <string>
using namespace std;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace valid { // geos.operation.valid
const char* TopologyValidationError::errMsg[]={
"Topology Validation Error",
"Repeated Point",
"Hole lies outside shell",
"Holes are nested",
"Interior is disconnected",
"Self-intersection",
"Ring Self-intersection",
"Nested shells",
"Duplicate Rings",
"Too few points in geometry component",
"Invalid Coordinate",
"Ring is not closed"
};
TopologyValidationError::TopologyValidationError(int newErrorType,
const Coordinate& newPt)
:
errorType(newErrorType),
pt(newPt)
{
}
TopologyValidationError::TopologyValidationError(int newErrorType)
:
errorType(newErrorType),
pt(Coordinate::getNull())
{
}
int
TopologyValidationError::getErrorType()
{
return errorType;
}
Coordinate&
TopologyValidationError::getCoordinate()
{
return pt;
}
string
TopologyValidationError::getMessage()
{
return string(errMsg[errorType]);
}
string
TopologyValidationError::toString()
{
return (getMessage().append(" at or near point")).append(pt.toString());
}
} // namespace geos.operation.valid
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.15 2006/03/20 16:57:44 strk
* spatialindex.h and opValid.h headers split
*
* Revision 1.14 2006/03/03 10:46:22 strk
* Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46)
*
* Revision 1.13 2006/03/01 10:48:55 strk
* Changed static TopologyValidationError::errMsg[] from 'string' to 'const char*'
* to reduce dynamic memory allocations.
*
* Revision 1.12 2006/02/23 23:17:52 strk
* - Coordinate::nullCoordinate made private
* - Simplified Coordinate inline definitions
* - LMGeometryComponentFilter definition moved to LineMerger.cpp file
* - Misc cleanups
*
* Revision 1.11 2006/02/19 19:46:50 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.10 2006/01/20 19:11:09 strk
* Updated last port info
*
* Revision 1.9 2005/11/04 11:04:09 strk
* Ported revision 1.38 of IsValidOp.java (adding closed Ring checks).
* Changed NestedRingTester classes to use Coorinate pointers
* rather then actual objects, to speedup NULL tests.
* Added JTS port revision when applicable.
*
* Revision 1.8 2004/11/05 11:41:57 strk
* Made IsValidOp handle IllegalArgumentException throw from GeometryGraph
* as a sign of invalidity (just for Polygon geometries).
* Removed leaks generated by this specific exception.
*
* Revision 1.7 2004/09/13 10:14:47 strk
* Added INVALID_COORDINATE code num and error message.
*
* Revision 1.6 2004/07/02 13:28:29 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.5 2003/11/07 01:23:43 pramsey
* Add standard CVS headers licence notices and copyrights to all cpp and h
* files.
*
*
**********************************************************************/
<commit_msg>added missing space in exception message<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2005-2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/valid/TopologyValidationError.java rev. 1.14 (JTS-1.7)
*
**********************************************************************/
#include <geos/operation/valid/TopologyValidationError.h>
#include <geos/geom/Coordinate.h>
#include <string>
using namespace std;
using namespace geos::geom;
namespace geos {
namespace operation { // geos.operation
namespace valid { // geos.operation.valid
const char* TopologyValidationError::errMsg[]={
"Topology Validation Error",
"Repeated Point",
"Hole lies outside shell",
"Holes are nested",
"Interior is disconnected",
"Self-intersection",
"Ring Self-intersection",
"Nested shells",
"Duplicate Rings",
"Too few points in geometry component",
"Invalid Coordinate",
"Ring is not closed"
};
TopologyValidationError::TopologyValidationError(int newErrorType,
const Coordinate& newPt)
:
errorType(newErrorType),
pt(newPt)
{
}
TopologyValidationError::TopologyValidationError(int newErrorType)
:
errorType(newErrorType),
pt(Coordinate::getNull())
{
}
int
TopologyValidationError::getErrorType()
{
return errorType;
}
Coordinate&
TopologyValidationError::getCoordinate()
{
return pt;
}
string
TopologyValidationError::getMessage()
{
return string(errMsg[errorType]);
}
string
TopologyValidationError::toString()
{
return getMessage().append(" at or near point ").append(pt.toString());
}
} // namespace geos.operation.valid
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.16 2006/03/27 10:36:51 strk
* added missing space in exception message
*
* Revision 1.15 2006/03/20 16:57:44 strk
* spatialindex.h and opValid.h headers split
*
* Revision 1.14 2006/03/03 10:46:22 strk
* Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46)
*
* Revision 1.13 2006/03/01 10:48:55 strk
* Changed static TopologyValidationError::errMsg[] from 'string' to 'const char*'
* to reduce dynamic memory allocations.
*
* Revision 1.12 2006/02/23 23:17:52 strk
* - Coordinate::nullCoordinate made private
* - Simplified Coordinate inline definitions
* - LMGeometryComponentFilter definition moved to LineMerger.cpp file
* - Misc cleanups
*
* Revision 1.11 2006/02/19 19:46:50 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.10 2006/01/20 19:11:09 strk
* Updated last port info
*
* Revision 1.9 2005/11/04 11:04:09 strk
* Ported revision 1.38 of IsValidOp.java (adding closed Ring checks).
* Changed NestedRingTester classes to use Coorinate pointers
* rather then actual objects, to speedup NULL tests.
* Added JTS port revision when applicable.
*
* Revision 1.8 2004/11/05 11:41:57 strk
* Made IsValidOp handle IllegalArgumentException throw from GeometryGraph
* as a sign of invalidity (just for Polygon geometries).
* Removed leaks generated by this specific exception.
*
* Revision 1.7 2004/09/13 10:14:47 strk
* Added INVALID_COORDINATE code num and error message.
*
* Revision 1.6 2004/07/02 13:28:29 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.5 2003/11/07 01:23:43 pramsey
* Add standard CVS headers licence notices and copyrights to all cpp and h
* files.
*
*
**********************************************************************/
<|endoftext|>
|
<commit_before>#include "SolidMaterialProperties.h"
registerMooseObject("THMApp", SolidMaterialProperties);
template <>
InputParameters
validParams<SolidMaterialProperties>()
{
InputParameters params = validParams<GeneralUserObject>();
params.addRequiredParam<FunctionName>("k", "Thermal conductivity");
params.addRequiredParam<FunctionName>("Cp", "Specific heat");
params.addRequiredParam<FunctionName>("rho", "Density");
params.addPrivateParam<ExecFlagEnum>("execute_on");
params.addPrivateParam<bool>("use_displaced_mesh");
params.registerBase("SolidMaterialProperties");
return params;
}
SolidMaterialProperties::SolidMaterialProperties(const InputParameters & parameters)
: GeneralUserObject(parameters),
_k(getFunction("k")),
_Cp(getFunction("Cp")),
_rho(getFunction("rho"))
{
}
void
SolidMaterialProperties::initialize()
{
}
void
SolidMaterialProperties::execute()
{
}
void
SolidMaterialProperties::finalize()
{
}
Real
SolidMaterialProperties::k(Real temp) const
{
return _k.value(temp, Point());
}
Real
SolidMaterialProperties::Cp(Real temp) const
{
return _Cp.value(temp, Point());
}
Real
SolidMaterialProperties::rho(Real temp) const
{
return _rho.value(temp, Point());
}
<commit_msg>Adding units to SolidMaterialProperties<commit_after>#include "SolidMaterialProperties.h"
registerMooseObject("THMApp", SolidMaterialProperties);
template <>
InputParameters
validParams<SolidMaterialProperties>()
{
InputParameters params = validParams<GeneralUserObject>();
params.addRequiredParam<FunctionName>("k", "Thermal conductivity [W/(m-K)]");
params.addRequiredParam<FunctionName>("Cp", "Specific heat [J/(kg-K)]");
params.addRequiredParam<FunctionName>("rho", "Density [kg/m^3]");
params.addPrivateParam<ExecFlagEnum>("execute_on");
params.addPrivateParam<bool>("use_displaced_mesh");
params.registerBase("SolidMaterialProperties");
return params;
}
SolidMaterialProperties::SolidMaterialProperties(const InputParameters & parameters)
: GeneralUserObject(parameters),
_k(getFunction("k")),
_Cp(getFunction("Cp")),
_rho(getFunction("rho"))
{
}
void
SolidMaterialProperties::initialize()
{
}
void
SolidMaterialProperties::execute()
{
}
void
SolidMaterialProperties::finalize()
{
}
Real
SolidMaterialProperties::k(Real temp) const
{
return _k.value(temp, Point());
}
Real
SolidMaterialProperties::Cp(Real temp) const
{
return _Cp.value(temp, Point());
}
Real
SolidMaterialProperties::rho(Real temp) const
{
return _rho.value(temp, Point());
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "zbase/AnalyticsTableScan.h"
using namespace stx;
namespace zbase {
AnalyticsTableScan::AnalyticsTableScan() : rows_scanned_(0) {}
void AnalyticsTableScan::scanTable(cstable::CSTableReader* reader) {
per_session_.clear();
per_query_.clear();
per_queryitem_.clear();
per_cartitem_.clear();
per_itemvisit_.clear();
for (const auto& c : columns_) {
String colname =
StringUtil::find(c.first, '.') == String::npos
? "attr." + c.first
: "event." + c.first;
if (!reader->hasColumn(colname)) {
continue;
}
if (StringUtil::beginsWith(colname, "event.cart_items.")) {
per_cartitem_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.search_queries.result_items.")) {
per_queryitem_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.search_queries.")) {
per_query_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.item_visits.")) {
per_itemvisit_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
per_session_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
}
if (per_queryitem_.size() > 0) {
scanTableForQueryItems(reader->numRecords());
return;
}
if (per_query_.size() > 0) {
scanTableForQueries(reader->numRecords());
return;
}
if (per_cartitem_.size() > 0) {
scanTableForCartItems(reader->numRecords());
return;
}
if (per_itemvisit_.size() > 0) {
scanTableForItemVisits(reader->numRecords());
return;
}
RAISE(kIllegalStateError, "can't figure out how to run this query");
}
void AnalyticsTableScan::scanTableForQueryItems(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_queryitem_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
for (const auto& c : per_query_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_query_) {
f();
}
/* fallthrough */
case 2:
if (is_defined) {
for (const auto& f : on_queryitem_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForQueries(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_query_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_query_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForCartItems(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_cartitem_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_cartitem_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForItemVisits(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_itemvisit_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_itemvisit_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::onSession(Function<void ()> fn) {
on_session_.emplace_back(fn);
}
void AnalyticsTableScan::onQuery(Function<void ()> fn) {
on_query_.emplace_back(fn);
}
void AnalyticsTableScan::onQueryItem(Function<void ()> fn) {
on_queryitem_.emplace_back(fn);
}
void AnalyticsTableScan::onCartItem(Function<void ()> fn) {
on_cartitem_.emplace_back(fn);
}
void AnalyticsTableScan::onItemVisit(Function<void ()> fn) {
on_itemvisit_.emplace_back(fn);
}
RefPtr<AnalyticsTableScan::ColumnRef> AnalyticsTableScan::fetchColumn(
const String& column_name) {
auto iter = columns_.find(column_name);
if (iter == columns_.end()) {
RefPtr<ColumnRef> cr(new ColumnRef(column_name));
columns_.emplace(column_name, cr);
return cr;
} else {
return iter->second;
}
}
size_t AnalyticsTableScan::rowsScanned() const {
return rows_scanned_;
}
AnalyticsTableScan::ColumnRef::ColumnRef(
const String& name) :
column_name(name),
cur_data(nullptr),
cur_size(0) {}
uint32_t AnalyticsTableScan::ColumnRef::getUInt32() const {
if (cur_size == sizeof(uint64_t)) {
return *((uint64_t*) cur_data);
}
if (cur_size < sizeof(uint32_t)) {
return 0;
}
return *((uint32_t*) cur_data);
}
uint64_t AnalyticsTableScan::ColumnRef::getUInt64() const {
if (cur_size == sizeof(uint32_t)) {
return *((uint64_t*) cur_data);
}
if (cur_size < sizeof(uint64_t)) {
return 0;
}
return *((uint64_t*) cur_data);
}
bool AnalyticsTableScan::ColumnRef::getBool() const {
if (cur_size < sizeof(uint8_t)) {
return false;
}
return *((uint8_t*) cur_data) > 0;
}
String AnalyticsTableScan::ColumnRef::getString() const {
if (cur_size == 0) {
return "";
}
return String((char*) cur_data, cur_size);
}
} // namespace zbase
<commit_msg>fix legacy queries?<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "zbase/AnalyticsTableScan.h"
using namespace stx;
namespace zbase {
AnalyticsTableScan::AnalyticsTableScan() : rows_scanned_(0) {}
void AnalyticsTableScan::scanTable(cstable::CSTableReader* reader) {
per_session_.clear();
per_query_.clear();
per_queryitem_.clear();
per_cartitem_.clear();
per_itemvisit_.clear();
for (const auto& c : columns_) {
String colname =
StringUtil::find(c.first, '.') == String::npos
? "attr." + c.first
: "event." + c.first;
if (!reader->hasColumn(colname)) {
continue;
}
if (StringUtil::beginsWith(colname, "event.cart_items.")) {
per_cartitem_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.search_queries.result_items.")) {
StringUtil::replaceAll(&colname, "event.search_queries.", "event.search_query.");
per_queryitem_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.search_queries.")) {
StringUtil::replaceAll(&colname, "event.search_queries.", "event.search_query.");
per_query_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
if (StringUtil::beginsWith(colname, "event.item_visits.")) {
StringUtil::replaceAll(&colname, "event.item_visits.", "event.page_view.");
per_itemvisit_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
continue;
}
per_session_.emplace_back(
c.second.get(),
reader->getColumnReader(colname));
}
if (per_queryitem_.size() > 0) {
scanTableForQueryItems(reader->numRecords());
return;
}
if (per_query_.size() > 0) {
scanTableForQueries(reader->numRecords());
return;
}
if (per_cartitem_.size() > 0) {
scanTableForCartItems(reader->numRecords());
return;
}
if (per_itemvisit_.size() > 0) {
scanTableForItemVisits(reader->numRecords());
return;
}
RAISE(kIllegalStateError, "can't figure out how to run this query");
}
void AnalyticsTableScan::scanTableForQueryItems(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_queryitem_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
for (const auto& c : per_query_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_query_) {
f();
}
/* fallthrough */
case 2:
if (is_defined) {
for (const auto& f : on_queryitem_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForQueries(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_query_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_query_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForCartItems(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_cartitem_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_cartitem_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::scanTableForItemVisits(size_t n_max) {
uint64_t d;
uint64_t r;
for (size_t n = 1; n < n_max; ) {
rows_scanned_++;
bool is_defined = false;
for (const auto& c : per_itemvisit_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
if (d == c.second->maxDefinitionLevel()) {
is_defined = true;
}
}
switch (r) {
case 0:
++n;
for (const auto& c : per_session_) {
c.second->next(&r, &d, &c.first->cur_data, &c.first->cur_size);
}
for (const auto& f : on_session_) {
f();
}
/* fallthrough */
case 1:
if (is_defined) {
for (const auto& f : on_itemvisit_) {
f();
}
}
break;
}
}
}
void AnalyticsTableScan::onSession(Function<void ()> fn) {
on_session_.emplace_back(fn);
}
void AnalyticsTableScan::onQuery(Function<void ()> fn) {
on_query_.emplace_back(fn);
}
void AnalyticsTableScan::onQueryItem(Function<void ()> fn) {
on_queryitem_.emplace_back(fn);
}
void AnalyticsTableScan::onCartItem(Function<void ()> fn) {
on_cartitem_.emplace_back(fn);
}
void AnalyticsTableScan::onItemVisit(Function<void ()> fn) {
on_itemvisit_.emplace_back(fn);
}
RefPtr<AnalyticsTableScan::ColumnRef> AnalyticsTableScan::fetchColumn(
const String& column_name) {
auto iter = columns_.find(column_name);
if (iter == columns_.end()) {
RefPtr<ColumnRef> cr(new ColumnRef(column_name));
columns_.emplace(column_name, cr);
return cr;
} else {
return iter->second;
}
}
size_t AnalyticsTableScan::rowsScanned() const {
return rows_scanned_;
}
AnalyticsTableScan::ColumnRef::ColumnRef(
const String& name) :
column_name(name),
cur_data(nullptr),
cur_size(0) {}
uint32_t AnalyticsTableScan::ColumnRef::getUInt32() const {
if (cur_size == sizeof(uint64_t)) {
return *((uint64_t*) cur_data);
}
if (cur_size < sizeof(uint32_t)) {
return 0;
}
return *((uint32_t*) cur_data);
}
uint64_t AnalyticsTableScan::ColumnRef::getUInt64() const {
if (cur_size == sizeof(uint32_t)) {
return *((uint64_t*) cur_data);
}
if (cur_size < sizeof(uint64_t)) {
return 0;
}
return *((uint64_t*) cur_data);
}
bool AnalyticsTableScan::ColumnRef::getBool() const {
if (cur_size < sizeof(uint8_t)) {
return false;
}
return *((uint8_t*) cur_data) > 0;
}
String AnalyticsTableScan::ColumnRef::getString() const {
if (cur_size == 0) {
return "";
}
return String((char*) cur_data, cur_size);
}
} // namespace zbase
<|endoftext|>
|
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_ITEM_H__
#define __BSE_ITEM_H__
#include <bse/bseobject.hh>
#include <bse/bseundostack.hh>
/* --- object type macros --- */
#define BSE_TYPE_ITEM (BSE_TYPE_ID (BseItem))
#define BSE_ITEM(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), BSE_TYPE_ITEM, BseItem))
#define BSE_ITEM_CLASS(class) (G_TYPE_CHECK_CLASS_CAST ((class), BSE_TYPE_ITEM, BseItemClass))
#define BSE_IS_ITEM(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), BSE_TYPE_ITEM))
#define BSE_IS_ITEM_CLASS(class) (G_TYPE_CHECK_CLASS_TYPE ((class), BSE_TYPE_ITEM))
#define BSE_ITEM_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS ((object), BSE_TYPE_ITEM, BseItemClass))
/* --- BseItem member macros --- */
#define BSE_ITEM_SINGLETON(object) ((BSE_OBJECT_FLAGS (object) & BSE_ITEM_FLAG_SINGLETON) != 0)
#define BSE_ITEM_INTERNAL(item) ((BSE_OBJECT_FLAGS (item) & BSE_ITEM_FLAG_INTERN_BRANCH) != 0)
/* --- bse item flags --- */
typedef enum /*< skip >*/
{
BSE_ITEM_FLAG_SINGLETON = 1 << (BSE_OBJECT_FLAGS_USHIFT + 0),
BSE_ITEM_FLAG_INTERN = 1 << (BSE_OBJECT_FLAGS_USHIFT + 1),
BSE_ITEM_FLAG_INTERN_BRANCH = 1 << (BSE_OBJECT_FLAGS_USHIFT + 2)
} BseItemFlags;
#define BSE_ITEM_FLAGS_USHIFT (BSE_OBJECT_FLAGS_USHIFT + 3)
struct BseItem : BseObject {
guint use_count;
BseItem *parent;
void set_flag (BseItemFlags f) { change_flags (uint16_t (f), true); }
void unset_flag (BseItemFlags f) { change_flags (uint16_t (f), false); }
using BseObject::set_flag;
using BseObject::unset_flag;
};
struct BseItemClass : BseObjectClass {
void (*get_candidates) (BseItem *item, uint param_id, Bse::PropertyCandidates &pc, GParamSpec *pspec);
void (*set_parent) (BseItem *item,
BseItem *parent);
gboolean (*needs_storage) (BseItem *item,
BseStorage *storage);
void (*compat_setup) (BseItem *item,
guint vmajor,
guint vminor,
guint vmicro);
guint (*get_seqid) (BseItem *item);
BseUndoStack* (*get_undo) (BseItem *item);
};
typedef void (*BseItemUncross) (BseItem *owner,
BseItem *link);
typedef gboolean (*BseItemCheckContainer) (BseContainer *container,
BseItem *item,
gpointer data);
typedef gboolean (*BseItemCheckProxy) (BseItem *proxy,
BseItem *item,
gpointer data);
/* --- prototypes --- */
void bse_item_gather_items_typed (BseItem *item, Bse::ItemSeq &iseq, GType proxy_type, GType container_type, bool allow_ancestor);
gboolean bse_item_get_candidates (BseItem *item,
const Bse::String &property,
Bse::PropertyCandidates &pc);
void bse_item_set_internal (gpointer item,
gboolean internal);
gboolean bse_item_needs_storage (BseItem *item,
BseStorage *storage);
void bse_item_compat_setup (BseItem *item,
guint vmajor,
guint vminor,
guint vmicro);
guint bse_item_get_seqid (BseItem *item);
void bse_item_queue_seqid_changed (BseItem *item);
BseSuper* bse_item_get_super (BseItem *item);
BseSNet* bse_item_get_snet (BseItem *item);
BseProject* bse_item_get_project (BseItem *item);
BseItem* bse_item_get_toplevel (BseItem *item);
gboolean bse_item_has_ancestor (BseItem *item,
BseItem *ancestor);
BseItem* bse_item_common_ancestor (BseItem *item1,
BseItem *item2);
void bse_item_cross_link (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func);
void bse_item_cross_unlink (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func);
void bse_item_uncross_links (BseItem *owner,
BseItem *link);
BseItem* bse_item_use (BseItem *item);
void bse_item_unuse (BseItem *item);
void bse_item_set_parent (BseItem *item,
BseItem *parent);
/* undo-aware functions */
void bse_item_set_valist_undoable (gpointer object,
const gchar *first_property_name,
va_list var_args);
void bse_item_set_undoable (gpointer object,
const gchar *first_property_name,
...) G_GNUC_NULL_TERMINATED;
void bse_item_set_property_undoable (BseItem *self,
const gchar *name,
const GValue *value);
/* undo admin functions */
BseUndoStack* bse_item_undo_open_str (void *item, const std::string &string);
#define bse_item_undo_open(item,...) bse_item_undo_open_str (item, Bse::string_format (__VA_ARGS__).c_str())
void bse_item_undo_close (BseUndoStack *ustack);
/* undo helper functions */
void bse_item_backup_to_undo (BseItem *self,
BseUndoStack *ustack);
void bse_item_push_undo_storage (BseItem *self,
BseUndoStack *ustack,
BseStorage *storage);
/* convenience */
#define bse_item_set bse_item_set_undoable
#define bse_item_get g_object_get
Bse::MusicalTuning bse_item_current_musical_tuning (BseItem *self);
namespace Bse {
class ItemImpl : public ObjectImpl, public virtual ItemIface {
public: typedef std::function<Error (ItemImpl &item, BseUndoStack *ustack)> UndoLambda;
private:
void push_item_undo (const String &blurb, const UndoLambda &lambda);
struct UndoDescriptorData {
ptrdiff_t projectid;
String upath;
UndoDescriptorData() : projectid (0) {}
};
UndoDescriptorData make_undo_descriptor_data (ItemImpl &item);
ItemImpl& resolve_undo_descriptor_data (const UndoDescriptorData &udd);
protected:
virtual ~ItemImpl ();
public:
explicit ItemImpl (BseObject*);
ContainerImpl* parent ();
virtual ItemIfaceP use () override;
virtual void unuse () override;
virtual void set_name (const std::string &name) override;
virtual bool editable_property (const std::string &property_name) override;
virtual Icon icon () const override;
virtual void icon (const Icon&) override;
virtual ItemIfaceP common_ancestor (ItemIface &other) override;
virtual bool check_is_a (const String &type_name) override;
virtual void group_undo (const String &name) override;
virtual void ungroup_undo () override;
virtual ProjectIfaceP get_project () override;
virtual ItemIfaceP get_parent () override;
virtual int get_seqid () override;
virtual String get_type () override;
virtual String get_type_authors () override;
virtual String get_type_blurb () override;
virtual String get_type_license () override;
virtual String get_type_name () override;
virtual String get_uname_path () override;
virtual String get_name () override;
virtual String get_name_or_type () override;
virtual bool internal () override;
virtual PropertyCandidates get_property_candidates (const String &property_name) override;
/// Save the value of @a property_name onto the undo stack.
void push_property_undo (const String &property_name);
/// Push an undo @a function onto the undo stack, the @a self argument to @a function must match @a this.
template<typename ItemT, typename... FuncArgs, typename... CallArgs> void
push_undo (const String &blurb, ItemT &self, Error (ItemT::*function) (FuncArgs...), CallArgs... args)
{
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [function, args...] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
return (self.*function) (args...);
};
push_item_undo (blurb, lambda);
}
/// Push an undo @a function like push_undo(), but ignore the return value of @a function.
template<typename ItemT, typename R, typename... FuncArgs, typename... CallArgs> void
push_undo (const String &blurb, ItemT &self, R (ItemT::*function) (FuncArgs...), CallArgs... args)
{
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [function, args...] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
(self.*function) (args...); // ignoring return type R
return Error::NONE;
};
push_item_undo (blurb, lambda);
}
/// Push an undo lambda, using the signature: Error lambda (TypeDerivedFromItem&, BseUndoStack*);
template<typename ItemT, typename ItemTLambda> void
push_undo (const String &blurb, ItemT &self, const ItemTLambda &itemt_lambda)
{
const std::function<Error (ItemT &item, BseUndoStack *ustack)> &undo_lambda = itemt_lambda;
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [undo_lambda] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
return undo_lambda (self, ustack);
};
push_item_undo (blurb, lambda);
}
/// Push an undo step, that when executed, pushes @a itemt_lambda to the redo stack.
template<typename ItemT, typename ItemTLambda> void
push_undo_to_redo (const String &blurb, ItemT &self, const ItemTLambda &itemt_lambda)
{ // push itemt_lambda as undo step when this undo step is executed (i.e. itemt_lambda is for redo)
const std::function<Error (ItemT &item, BseUndoStack *ustack)> &undo_lambda = itemt_lambda;
BSE_ASSERT_RETURN (this == &self);
auto lambda = [blurb, undo_lambda] (ItemT &self, BseUndoStack *ustack) -> Error {
self.push_undo (blurb, self, undo_lambda);
return Error::NONE;
};
push_undo (blurb, self, lambda);
}
/// UndoDescriptor - type safe object handle to persist undo/redo steps
template<class Obj>
class UndoDescriptor {
friend class ItemImpl;
UndoDescriptorData data_;
UndoDescriptor (const UndoDescriptorData &d) : data_ (d) {}
public:
typedef Obj Type;
};
/// Create an object descriptor that persists undo/redo steps.
template<class Obj>
UndoDescriptor<Obj> undo_descriptor (Obj &item) { return UndoDescriptor<Obj> (make_undo_descriptor_data (item)); }
/// Resolve an undo descriptor back to an object, see also undo_descriptor().
template<class Obj>
Obj& undo_resolve (UndoDescriptor<Obj> udo) { return dynamic_cast<Obj&> (resolve_undo_descriptor_data (udo.data_)); }
static bool constrain_idl_enum (int64_t &i, const StringVector &kvlist);
static bool constrain_idl_int (int64_t &i, const StringVector &kvlist);
static bool constrain_idl_double (double &d, const StringVector &kvlist);
template<class T, Aida::REQUIRES< std::is_enum<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
int64_t i = int64_t (lvalue);
const bool valid = constrain_idl_enum (i, kvlist);
lvalue = T (i);
return valid;
}
template<class T, Aida::REQUIRES< std::is_integral<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
int64_t i = int64_t (lvalue);
const bool valid = constrain_idl_int (i, kvlist);
lvalue = T (i);
return valid;
}
template<class T, Aida::REQUIRES< std::is_floating_point<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
double d = lvalue;
const bool valid = constrain_idl_double (d, kvlist);
lvalue = d;
return valid;
}
/// Constrain and assign property value if it has changed, emit notification.
template<class T> bool
apply_idl_property (T &lvalue, const T &cvalue, const String &propname)
{
if (std::is_integral<T>::value || std::is_floating_point<T>::value || std::is_enum<T>::value)
{ // avoid value copy for non primitive types
T rvalue = cvalue;
if (!constrain_idl_property (rvalue, find_prop (propname)))
return false;
if (lvalue == rvalue)
return false;
push_property_undo (propname);
lvalue = std::move (rvalue);
}
else if (lvalue == cvalue)
{
return false;
lvalue = cvalue;
}
auto lifeguard = shared_from_this();
exec_now ([this, propname, lifeguard] () { this->notify (propname); });
return true;
}
};
#define BSE_OBJECT_APPLY_IDL_PROPERTY(lvalue, rvalue) this->apply_idl_property (lvalue, rvalue, __func__)
} // Bse
#endif /* __BSE_ITEM_H__ */
<commit_msg>BSE: bseitem: fix APPLY_IDL_PROPERTY() bugs for non primitive types<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_ITEM_H__
#define __BSE_ITEM_H__
#include <bse/bseobject.hh>
#include <bse/bseundostack.hh>
/* --- object type macros --- */
#define BSE_TYPE_ITEM (BSE_TYPE_ID (BseItem))
#define BSE_ITEM(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), BSE_TYPE_ITEM, BseItem))
#define BSE_ITEM_CLASS(class) (G_TYPE_CHECK_CLASS_CAST ((class), BSE_TYPE_ITEM, BseItemClass))
#define BSE_IS_ITEM(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), BSE_TYPE_ITEM))
#define BSE_IS_ITEM_CLASS(class) (G_TYPE_CHECK_CLASS_TYPE ((class), BSE_TYPE_ITEM))
#define BSE_ITEM_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS ((object), BSE_TYPE_ITEM, BseItemClass))
/* --- BseItem member macros --- */
#define BSE_ITEM_SINGLETON(object) ((BSE_OBJECT_FLAGS (object) & BSE_ITEM_FLAG_SINGLETON) != 0)
#define BSE_ITEM_INTERNAL(item) ((BSE_OBJECT_FLAGS (item) & BSE_ITEM_FLAG_INTERN_BRANCH) != 0)
/* --- bse item flags --- */
typedef enum /*< skip >*/
{
BSE_ITEM_FLAG_SINGLETON = 1 << (BSE_OBJECT_FLAGS_USHIFT + 0),
BSE_ITEM_FLAG_INTERN = 1 << (BSE_OBJECT_FLAGS_USHIFT + 1),
BSE_ITEM_FLAG_INTERN_BRANCH = 1 << (BSE_OBJECT_FLAGS_USHIFT + 2)
} BseItemFlags;
#define BSE_ITEM_FLAGS_USHIFT (BSE_OBJECT_FLAGS_USHIFT + 3)
struct BseItem : BseObject {
guint use_count;
BseItem *parent;
void set_flag (BseItemFlags f) { change_flags (uint16_t (f), true); }
void unset_flag (BseItemFlags f) { change_flags (uint16_t (f), false); }
using BseObject::set_flag;
using BseObject::unset_flag;
};
struct BseItemClass : BseObjectClass {
void (*get_candidates) (BseItem *item, uint param_id, Bse::PropertyCandidates &pc, GParamSpec *pspec);
void (*set_parent) (BseItem *item,
BseItem *parent);
gboolean (*needs_storage) (BseItem *item,
BseStorage *storage);
void (*compat_setup) (BseItem *item,
guint vmajor,
guint vminor,
guint vmicro);
guint (*get_seqid) (BseItem *item);
BseUndoStack* (*get_undo) (BseItem *item);
};
typedef void (*BseItemUncross) (BseItem *owner,
BseItem *link);
typedef gboolean (*BseItemCheckContainer) (BseContainer *container,
BseItem *item,
gpointer data);
typedef gboolean (*BseItemCheckProxy) (BseItem *proxy,
BseItem *item,
gpointer data);
/* --- prototypes --- */
void bse_item_gather_items_typed (BseItem *item, Bse::ItemSeq &iseq, GType proxy_type, GType container_type, bool allow_ancestor);
gboolean bse_item_get_candidates (BseItem *item,
const Bse::String &property,
Bse::PropertyCandidates &pc);
void bse_item_set_internal (gpointer item,
gboolean internal);
gboolean bse_item_needs_storage (BseItem *item,
BseStorage *storage);
void bse_item_compat_setup (BseItem *item,
guint vmajor,
guint vminor,
guint vmicro);
guint bse_item_get_seqid (BseItem *item);
void bse_item_queue_seqid_changed (BseItem *item);
BseSuper* bse_item_get_super (BseItem *item);
BseSNet* bse_item_get_snet (BseItem *item);
BseProject* bse_item_get_project (BseItem *item);
BseItem* bse_item_get_toplevel (BseItem *item);
gboolean bse_item_has_ancestor (BseItem *item,
BseItem *ancestor);
BseItem* bse_item_common_ancestor (BseItem *item1,
BseItem *item2);
void bse_item_cross_link (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func);
void bse_item_cross_unlink (BseItem *owner,
BseItem *link,
BseItemUncross uncross_func);
void bse_item_uncross_links (BseItem *owner,
BseItem *link);
BseItem* bse_item_use (BseItem *item);
void bse_item_unuse (BseItem *item);
void bse_item_set_parent (BseItem *item,
BseItem *parent);
/* undo-aware functions */
void bse_item_set_valist_undoable (gpointer object,
const gchar *first_property_name,
va_list var_args);
void bse_item_set_undoable (gpointer object,
const gchar *first_property_name,
...) G_GNUC_NULL_TERMINATED;
void bse_item_set_property_undoable (BseItem *self,
const gchar *name,
const GValue *value);
/* undo admin functions */
BseUndoStack* bse_item_undo_open_str (void *item, const std::string &string);
#define bse_item_undo_open(item,...) bse_item_undo_open_str (item, Bse::string_format (__VA_ARGS__).c_str())
void bse_item_undo_close (BseUndoStack *ustack);
/* undo helper functions */
void bse_item_backup_to_undo (BseItem *self,
BseUndoStack *ustack);
void bse_item_push_undo_storage (BseItem *self,
BseUndoStack *ustack,
BseStorage *storage);
/* convenience */
#define bse_item_set bse_item_set_undoable
#define bse_item_get g_object_get
Bse::MusicalTuning bse_item_current_musical_tuning (BseItem *self);
namespace Bse {
class ItemImpl : public ObjectImpl, public virtual ItemIface {
public: typedef std::function<Error (ItemImpl &item, BseUndoStack *ustack)> UndoLambda;
private:
void push_item_undo (const String &blurb, const UndoLambda &lambda);
struct UndoDescriptorData {
ptrdiff_t projectid;
String upath;
UndoDescriptorData() : projectid (0) {}
};
UndoDescriptorData make_undo_descriptor_data (ItemImpl &item);
ItemImpl& resolve_undo_descriptor_data (const UndoDescriptorData &udd);
protected:
virtual ~ItemImpl ();
public:
explicit ItemImpl (BseObject*);
ContainerImpl* parent ();
virtual ItemIfaceP use () override;
virtual void unuse () override;
virtual void set_name (const std::string &name) override;
virtual bool editable_property (const std::string &property_name) override;
virtual Icon icon () const override;
virtual void icon (const Icon&) override;
virtual ItemIfaceP common_ancestor (ItemIface &other) override;
virtual bool check_is_a (const String &type_name) override;
virtual void group_undo (const String &name) override;
virtual void ungroup_undo () override;
virtual ProjectIfaceP get_project () override;
virtual ItemIfaceP get_parent () override;
virtual int get_seqid () override;
virtual String get_type () override;
virtual String get_type_authors () override;
virtual String get_type_blurb () override;
virtual String get_type_license () override;
virtual String get_type_name () override;
virtual String get_uname_path () override;
virtual String get_name () override;
virtual String get_name_or_type () override;
virtual bool internal () override;
virtual PropertyCandidates get_property_candidates (const String &property_name) override;
/// Save the value of @a property_name onto the undo stack.
void push_property_undo (const String &property_name);
/// Push an undo @a function onto the undo stack, the @a self argument to @a function must match @a this.
template<typename ItemT, typename... FuncArgs, typename... CallArgs> void
push_undo (const String &blurb, ItemT &self, Error (ItemT::*function) (FuncArgs...), CallArgs... args)
{
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [function, args...] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
return (self.*function) (args...);
};
push_item_undo (blurb, lambda);
}
/// Push an undo @a function like push_undo(), but ignore the return value of @a function.
template<typename ItemT, typename R, typename... FuncArgs, typename... CallArgs> void
push_undo (const String &blurb, ItemT &self, R (ItemT::*function) (FuncArgs...), CallArgs... args)
{
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [function, args...] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
(self.*function) (args...); // ignoring return type R
return Error::NONE;
};
push_item_undo (blurb, lambda);
}
/// Push an undo lambda, using the signature: Error lambda (TypeDerivedFromItem&, BseUndoStack*);
template<typename ItemT, typename ItemTLambda> void
push_undo (const String &blurb, ItemT &self, const ItemTLambda &itemt_lambda)
{
const std::function<Error (ItemT &item, BseUndoStack *ustack)> &undo_lambda = itemt_lambda;
BSE_ASSERT_RETURN (this == &self);
UndoLambda lambda = [undo_lambda] (ItemImpl &item, BseUndoStack *ustack) {
ItemT &self = dynamic_cast<ItemT&> (item);
return undo_lambda (self, ustack);
};
push_item_undo (blurb, lambda);
}
/// Push an undo step, that when executed, pushes @a itemt_lambda to the redo stack.
template<typename ItemT, typename ItemTLambda> void
push_undo_to_redo (const String &blurb, ItemT &self, const ItemTLambda &itemt_lambda)
{ // push itemt_lambda as undo step when this undo step is executed (i.e. itemt_lambda is for redo)
const std::function<Error (ItemT &item, BseUndoStack *ustack)> &undo_lambda = itemt_lambda;
BSE_ASSERT_RETURN (this == &self);
auto lambda = [blurb, undo_lambda] (ItemT &self, BseUndoStack *ustack) -> Error {
self.push_undo (blurb, self, undo_lambda);
return Error::NONE;
};
push_undo (blurb, self, lambda);
}
/// UndoDescriptor - type safe object handle to persist undo/redo steps
template<class Obj>
class UndoDescriptor {
friend class ItemImpl;
UndoDescriptorData data_;
UndoDescriptor (const UndoDescriptorData &d) : data_ (d) {}
public:
typedef Obj Type;
};
/// Create an object descriptor that persists undo/redo steps.
template<class Obj>
UndoDescriptor<Obj> undo_descriptor (Obj &item) { return UndoDescriptor<Obj> (make_undo_descriptor_data (item)); }
/// Resolve an undo descriptor back to an object, see also undo_descriptor().
template<class Obj>
Obj& undo_resolve (UndoDescriptor<Obj> udo) { return dynamic_cast<Obj&> (resolve_undo_descriptor_data (udo.data_)); }
static bool constrain_idl_enum (int64_t &i, const StringVector &kvlist);
static bool constrain_idl_int (int64_t &i, const StringVector &kvlist);
static bool constrain_idl_double (double &d, const StringVector &kvlist);
template<class T, Aida::REQUIRES< std::is_enum<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
int64_t i = int64_t (lvalue);
const bool valid = constrain_idl_enum (i, kvlist);
lvalue = T (i);
return valid;
}
template<class T, Aida::REQUIRES< std::is_integral<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
int64_t i = int64_t (lvalue);
const bool valid = constrain_idl_int (i, kvlist);
lvalue = T (i);
return valid;
}
template<class T, Aida::REQUIRES< std::is_floating_point<T>::value > = true> bool
constrain_idl_property (T &lvalue, const StringVector &kvlist)
{
double d = lvalue;
const bool valid = constrain_idl_double (d, kvlist);
lvalue = d;
return valid;
}
/// Constrain and assign property value if it has changed, emit notification.
template<class T> bool
apply_idl_property (T &lvalue, const T &cvalue, const String &propname)
{
if (std::is_integral<T>::value || std::is_floating_point<T>::value || std::is_enum<T>::value)
{ // avoid value copy for non primitive types
T rvalue = cvalue;
if (!constrain_idl_property (rvalue, find_prop (propname)))
return false;
if (lvalue == rvalue)
return false;
push_property_undo (propname);
lvalue = std::move (rvalue);
}
else
{
if (lvalue == cvalue)
return false;
push_property_undo (propname);
lvalue = cvalue;
}
auto lifeguard = shared_from_this();
exec_now ([this, propname, lifeguard] () { this->notify (propname); });
return true;
}
};
#define BSE_OBJECT_APPLY_IDL_PROPERTY(lvalue, rvalue) this->apply_idl_property (lvalue, rvalue, __func__)
} // Bse
#endif /* __BSE_ITEM_H__ */
<|endoftext|>
|
<commit_before>#include "Level.h"
#include "Player.h"
#include "FoodSpawner.h"
//Initialize all static variables.
bool Level::m_initialized = false;
Player* Level::m_player = nullptr;
FoodSpawner* Level::m_foodSpawner = nullptr;
MapTile*** Level::m_MapArray = nullptr;
MapTile** Level::m_MapTiles = nullptr;
int Level::m_MapTileCount = 0;
int Level::m_Score = 0;
aie::Font* Level::m_font = nullptr;
aie::Texture* Level::m_headTex = nullptr;
aie::Texture* Level::m_bodyTex = nullptr;
aie::Texture* Level::m_tailTex = nullptr;
aie::Texture* Level::m_foodTex = nullptr;
aie::Texture* Level::m_backgroundTex = nullptr;
aie::Texture* Level::m_wallTex = nullptr;
void Level::Initializer()
{
if (m_initialized)
return;
m_initialized = true;
m_MapArray = new MapTile**[MAP_SIZE_X];
for (int i = 0; i < MAP_SIZE_X; i++)
{
m_MapArray[i] = new MapTile*[MAP_SIZE_Y];
for (int ii = 0; ii < MAP_SIZE_Y; ii++)
{
m_MapArray[i][ii] = new MapTile(E_LevelSlot_Empty, i, ii);
}
}
m_foodSpawner = new FoodSpawner(0.0f);
//Setup map tiles with maximum number of tiles possible.
m_MapTiles = new MapTile*[MAP_SIZE_X * MAP_SIZE_Y];
for (int i = 0; i < MAP_SIZE_X * MAP_SIZE_Y; i++)
m_MapTiles[i] = nullptr;
m_MapTileCount = 0;
//Load font:
m_font = new aie::Font("./font/consolas.ttf", 32);
m_player = new Player();
//m_player->Spawn();
//Load textures
m_headTex = new aie::Texture("");
m_bodyTex = new aie::Texture("");
m_tailTex = new aie::Texture("");
m_foodTex = new aie::Texture("");
m_backgroundTex = new aie::Texture("");
m_wallTex = new aie::Texture("");
}
//Deconstructor, destroys all data.
void Level::DeInitializer()
{
if (!m_initialized)
return;
m_initialized = false;
//Destroy player and food spawner objects.
delete m_player;
m_player = nullptr;
delete m_foodSpawner;
m_foodSpawner = nullptr;
//Destroy all actual objects
for (int i = 0; i < MAP_SIZE_X; i++)
for (int ii = 0; ii < MAP_SIZE_Y; ii++)
{
delete m_MapArray[i][ii];
m_MapArray[i][ii] = nullptr;
}
//Destroy all 2nd dimension arrays.
for (int i = 0; i < MAP_SIZE_X; i++)
{
delete[] m_MapArray[i];
m_MapArray[i] = nullptr;
}
//Destroy first dimension array.
delete[] m_MapArray;
m_MapArray = nullptr;
delete[] m_MapTiles;
m_MapTileCount = 0;
m_MapTiles = nullptr;
//Destroy font.
delete m_font;
m_font = nullptr;
delete m_headTex;
delete m_bodyTex;
delete m_tailTex;
delete m_foodTex;
delete m_backgroundTex;
delete m_wallTex;
m_headTex = nullptr;
m_bodyTex = nullptr;
m_tailTex = nullptr;
m_foodTex = nullptr;
m_backgroundTex = nullptr;
m_wallTex = nullptr;
}
E_LevelSlot Level::GetMap(int x, int y)
{
if (x < 0 || y < 0 || x >= MAP_SIZE_X || y >= MAP_SIZE_Y)
return E_LevelSlot_Wall;
return m_MapArray[x][y]->SlotType;
}
MapTile* Level::GetMapTile(int x, int y)
{
if (x < 0 || y < 0 || x >= MAP_SIZE_X || y >= MAP_SIZE_Y)
return nullptr;
return m_MapArray[x][y];
}
void Level::EatFood()
{
m_foodSpawner->SetFood();
}
bool Level::GetMapOccupied(int x, int y)
{
return m_MapArray[x][y]->SlotType != E_LevelSlot_Empty;
}
bool Level::IsInitialized()
{
return m_initialized;
}
void Level::Update(float dt)
{
m_player->Update(dt);
m_foodSpawner->Spawn();
}
void Level::Draw(aie::Renderer2D& renderer)
{
for (int i = 0; i < m_MapTileCount; i++)
{
switch (m_MapTiles[i]->SlotType)
{
case E_LevelSlot_Food: renderer.setRenderColour(204, 0, 0, 1); break;
case E_LevelSlot_SnakeBody: renderer.setRenderColour(1, 1, 1, 1); break;
case E_LevelSlot_SnakeHead: renderer.setRenderColour(1, 1, 1, 1); break;
case E_LevelSlot_SnakeTail: renderer.setRenderColour(1, 1, 1, 1); break;
}
//Draw from corner instead of center.
renderer.drawBox(m_MapTiles[i]->X * MAP_CELLSIZE_X + MAP_CELLSIZE_X / 2, m_MapTiles[i]->Y * MAP_CELLSIZE_Y + MAP_CELLSIZE_Y / 2, MAP_CELLSIZE_X, MAP_CELLSIZE_Y);
}
//Draw white score.
renderer.setRenderColour(255, 255, 0, 1);
char fps[32];
sprintf_s(fps, 32, "Score: %i", m_Score);
renderer.drawText(m_font, fps, 0, MAP_SIZE_X * MAP_CELLSIZE_X - 24);
}
void Level::AddScore()
{
m_Score++;
}
void Level::ResetScore()
{
m_Score++;
}
void Level::SetMap(int x, int y, E_LevelSlot slotType, E_BlockFacing facing)
{
m_MapArray[x][y]->SlotType = slotType;
m_MapArray[x][y]->Facing = facing;
//If not cached yet. Only add if not empty.
if (m_MapArray[x][y]->ArrayID == -1 && slotType != E_LevelSlot_Empty)
{
m_MapArray[x][y]->ArrayID = m_MapTileCount;
m_MapTiles[m_MapTileCount] = m_MapArray[x][y];
m_MapTileCount++;
}
else if(m_MapArray[x][y]->ArrayID != -1 && slotType == E_LevelSlot_Empty)//If now empty, but has an array ID assigned.
{
//Move end to removed node, as order doesn't matter, and this is the quickest way of removing.
//If there is only one value, or the value you are moving is the end, this should still work.
m_MapTiles[m_MapArray[x][y]->ArrayID] = m_MapTiles[m_MapTileCount - 1];
m_MapTiles[m_MapTileCount - 1]->ArrayID = m_MapArray[x][y]->ArrayID;//Update array ID for new position.
m_MapTiles[m_MapTileCount - 1] = nullptr;
m_MapTileCount--;
//Remove from cached tiles.
m_MapArray[x][y]->ArrayID = -1;
}
}<commit_msg>Whoops #3<commit_after>#include "Level.h"
#include "Player.h"
#include "FoodSpawner.h"
//Initialize all static variables.
bool Level::m_initialized = false;
Player* Level::m_player = nullptr;
FoodSpawner* Level::m_foodSpawner = nullptr;
MapTile*** Level::m_MapArray = nullptr;
MapTile** Level::m_MapTiles = nullptr;
int Level::m_MapTileCount = 0;
int Level::m_Score = 0;
aie::Font* Level::m_font = nullptr;
aie::Texture* Level::m_headTex = nullptr;
aie::Texture* Level::m_bodyTex = nullptr;
aie::Texture* Level::m_tailTex = nullptr;
aie::Texture* Level::m_foodTex = nullptr;
aie::Texture* Level::m_backgroundTex = nullptr;
aie::Texture* Level::m_wallTex = nullptr;
void Level::Initializer()
{
if (m_initialized)
return;
m_initialized = true;
m_MapArray = new MapTile**[MAP_SIZE_X];
for (int i = 0; i < MAP_SIZE_X; i++)
{
m_MapArray[i] = new MapTile*[MAP_SIZE_Y];
for (int ii = 0; ii < MAP_SIZE_Y; ii++)
{
m_MapArray[i][ii] = new MapTile(E_LevelSlot_Empty, i, ii);
}
}
m_foodSpawner = new FoodSpawner(0.0f);
//Setup map tiles with maximum number of tiles possible.
m_MapTiles = new MapTile*[MAP_SIZE_X * MAP_SIZE_Y];
for (int i = 0; i < MAP_SIZE_X * MAP_SIZE_Y; i++)
m_MapTiles[i] = nullptr;
m_MapTileCount = 0;
//Load font:
m_font = new aie::Font("./font/consolas.ttf", 32);
m_player = new Player();
//m_player->Spawn();
//Load textures
m_headTex = new aie::Texture("");
m_bodyTex = new aie::Texture("");
m_tailTex = new aie::Texture("");
m_foodTex = new aie::Texture("");
m_backgroundTex = new aie::Texture("");
m_wallTex = new aie::Texture("");
}
//Deconstructor, destroys all data.
void Level::DeInitializer()
{
if (!m_initialized)
return;
m_initialized = false;
//Destroy player and food spawner objects.
delete m_player;
m_player = nullptr;
delete m_foodSpawner;
m_foodSpawner = nullptr;
//Destroy all actual objects
for (int i = 0; i < MAP_SIZE_X; i++)
for (int ii = 0; ii < MAP_SIZE_Y; ii++)
{
delete m_MapArray[i][ii];
m_MapArray[i][ii] = nullptr;
}
//Destroy all 2nd dimension arrays.
for (int i = 0; i < MAP_SIZE_X; i++)
{
delete[] m_MapArray[i];
m_MapArray[i] = nullptr;
}
//Destroy first dimension array.
delete[] m_MapArray;
m_MapArray = nullptr;
delete[] m_MapTiles;
m_MapTileCount = 0;
m_MapTiles = nullptr;
//Destroy font.
delete m_font;
m_font = nullptr;
delete m_headTex;
delete m_bodyTex;
delete m_tailTex;
delete m_foodTex;
delete m_backgroundTex;
delete m_wallTex;
m_headTex = nullptr;
m_bodyTex = nullptr;
m_tailTex = nullptr;
m_foodTex = nullptr;
m_backgroundTex = nullptr;
m_wallTex = nullptr;
}
E_LevelSlot Level::GetMap(int x, int y)
{
if (x < 0 || y < 0 || x >= MAP_SIZE_X || y >= MAP_SIZE_Y)
return E_LevelSlot_Wall;
return m_MapArray[x][y]->SlotType;
}
MapTile* Level::GetMapTile(int x, int y)
{
if (x < 0 || y < 0 || x >= MAP_SIZE_X || y >= MAP_SIZE_Y)
return nullptr;
return m_MapArray[x][y];
}
void Level::EatFood()
{
m_foodSpawner->SetFood();
}
bool Level::GetMapOccupied(int x, int y)
{
return m_MapArray[x][y]->SlotType != E_LevelSlot_Empty;
}
bool Level::IsInitialized()
{
return m_initialized;
}
void Level::Update(float dt)
{
m_player->Update(dt);
m_foodSpawner->Spawn();
}
void Level::Draw(aie::Renderer2D& renderer)
{
for (int i = 0; i < m_MapTileCount; i++)
{
switch (m_MapTiles[i]->SlotType)
{
case E_LevelSlot_Food: renderer.setRenderColour(204, 0, 0, 1); break;
case E_LevelSlot_SnakeBody: renderer.setRenderColour(1, 1, 1, 1); break;
case E_LevelSlot_SnakeHead: renderer.setRenderColour(1, 1, 1, 1); break;
case E_LevelSlot_SnakeTail: renderer.setRenderColour(1, 1, 1, 1); break;
}
//Draw from corner instead of center.
renderer.drawBox(m_MapTiles[i]->X * MAP_CELLSIZE_X + MAP_CELLSIZE_X / 2, m_MapTiles[i]->Y * MAP_CELLSIZE_Y + MAP_CELLSIZE_Y / 2, MAP_CELLSIZE_X, MAP_CELLSIZE_Y);
}
//Draw white score.
renderer.setRenderColour(255, 255, 0, 1);
char fps[32];
sprintf_s(fps, 32, "Score: %i", m_Score);
renderer.drawText(m_font, fps, 0, MAP_SIZE_X * MAP_CELLSIZE_X - 24);
}
void Level::AddScore()
{
m_Score++;
}
void Level::ResetScore()
{
m_Score = 0;
}
void Level::SetMap(int x, int y, E_LevelSlot slotType, E_BlockFacing facing)
{
m_MapArray[x][y]->SlotType = slotType;
m_MapArray[x][y]->Facing = facing;
//If not cached yet. Only add if not empty.
if (m_MapArray[x][y]->ArrayID == -1 && slotType != E_LevelSlot_Empty)
{
m_MapArray[x][y]->ArrayID = m_MapTileCount;
m_MapTiles[m_MapTileCount] = m_MapArray[x][y];
m_MapTileCount++;
}
else if(m_MapArray[x][y]->ArrayID != -1 && slotType == E_LevelSlot_Empty)//If now empty, but has an array ID assigned.
{
//Move end to removed node, as order doesn't matter, and this is the quickest way of removing.
//If there is only one value, or the value you are moving is the end, this should still work.
m_MapTiles[m_MapArray[x][y]->ArrayID] = m_MapTiles[m_MapTileCount - 1];
m_MapTiles[m_MapTileCount - 1]->ArrayID = m_MapArray[x][y]->ArrayID;//Update array ID for new position.
m_MapTiles[m_MapTileCount - 1] = nullptr;
m_MapTileCount--;
//Remove from cached tiles.
m_MapArray[x][y]->ArrayID = -1;
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2021 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <numeric>
#include "DistributedBeadingStrategy.h"
namespace cura
{
DistributedBeadingStrategy::DistributedBeadingStrategy(const coord_t optimal_width,
const coord_t default_transition_length,
const AngleRadians transitioning_angle,
const Ratio wall_split_middle_threshold,
const Ratio wall_add_middle_threshold,
const int distribution_radius)
: BeadingStrategy(optimal_width, default_transition_length, transitioning_angle)
, wall_split_middle_threshold(wall_split_middle_threshold)
, wall_add_middle_threshold(wall_add_middle_threshold)
{
if(distribution_radius >= 1)
{
one_over_distribution_radius_squared = 1.0f / distribution_radius * 1.0f / distribution_radius;
}
else
{
one_over_distribution_radius_squared = 1.0f / 1 * 1.0f / 1;
}
name = "DistributedBeadingStrategy";
}
DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count > 2)
{
const coord_t to_be_divided = thickness - bead_count * optimal_width;
const float middle = static_cast<float>(bead_count - 1) / 2;
const auto getWeight = [middle, this](coord_t bead_idx)
{
const float dev_from_middle = bead_idx - middle;
return std::max(0.0f, 1.0f - one_over_distribution_radius_squared * dev_from_middle * dev_from_middle);
};
std::vector<float> weights;
weights.resize(bead_count);
for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
{
weights[bead_idx] = getWeight(bead_idx);
}
const float total_weight = std::accumulate(weights.cbegin(), weights.cend(), 0.f);
for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
{
const float weight_fraction = weights[bead_idx] / total_weight;
const coord_t splitup_left_over_weight = to_be_divided * weight_fraction;
const coord_t width = optimal_width + splitup_left_over_weight;
if (bead_idx == 0)
{
ret.toolpath_locations.emplace_back(width / 2);
}
else
{
ret.toolpath_locations.emplace_back(ret.toolpath_locations.back() + (ret.bead_widths.back() + width) / 2);
}
ret.bead_widths.emplace_back(width);
}
ret.left_over = 0;
}
else if (bead_count == 2)
{
const coord_t outer_width = thickness / 2;
ret.bead_widths.emplace_back(outer_width);
ret.bead_widths.emplace_back(outer_width);
ret.toolpath_locations.emplace_back(outer_width / 2);
ret.toolpath_locations.emplace_back(thickness - outer_width / 2);
ret.left_over = 0;
}
else if (bead_count == 1)
{
const coord_t outer_width = thickness;
ret.bead_widths.emplace_back(outer_width);
ret.toolpath_locations.emplace_back(outer_width / 2);
ret.left_over = 0;
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return bead_count * optimal_width;
}
coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
return lower_bead_count * optimal_width + optimal_width * (lower_bead_count % 2 == 1 ? wall_split_middle_threshold : wall_add_middle_threshold);
}
coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
return (thickness + optimal_width / 2) / optimal_width;
}
} // namespace cura
<commit_msg>Change distribution count to be the maximum diameter of distribution<commit_after>// Copyright (c) 2021 Ultimaker B.V.
// CuraEngine is released under the terms of the AGPLv3 or higher.
#include <numeric>
#include "DistributedBeadingStrategy.h"
namespace cura
{
DistributedBeadingStrategy::DistributedBeadingStrategy(const coord_t optimal_width,
const coord_t default_transition_length,
const AngleRadians transitioning_angle,
const Ratio wall_split_middle_threshold,
const Ratio wall_add_middle_threshold,
const int distribution_radius)
: BeadingStrategy(optimal_width, default_transition_length, transitioning_angle)
, wall_split_middle_threshold(wall_split_middle_threshold)
, wall_add_middle_threshold(wall_add_middle_threshold)
{
if(distribution_radius >= 2)
{
one_over_distribution_radius_squared = 1.0f / (distribution_radius - 1) * 1.0f / (distribution_radius - 1);
}
else
{
one_over_distribution_radius_squared = 1.0f / 1 * 1.0f / 1;
}
name = "DistributedBeadingStrategy";
}
DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count > 2)
{
const coord_t to_be_divided = thickness - bead_count * optimal_width;
const float middle = static_cast<float>(bead_count - 1) / 2;
const auto getWeight = [middle, this](coord_t bead_idx)
{
const float dev_from_middle = bead_idx - middle;
return std::max(0.0f, 1.0f - one_over_distribution_radius_squared * dev_from_middle * dev_from_middle);
};
std::vector<float> weights;
weights.resize(bead_count);
for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
{
weights[bead_idx] = getWeight(bead_idx);
}
const float total_weight = std::accumulate(weights.cbegin(), weights.cend(), 0.f);
for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++)
{
const float weight_fraction = weights[bead_idx] / total_weight;
const coord_t splitup_left_over_weight = to_be_divided * weight_fraction;
const coord_t width = optimal_width + splitup_left_over_weight;
if (bead_idx == 0)
{
ret.toolpath_locations.emplace_back(width / 2);
}
else
{
ret.toolpath_locations.emplace_back(ret.toolpath_locations.back() + (ret.bead_widths.back() + width) / 2);
}
ret.bead_widths.emplace_back(width);
}
ret.left_over = 0;
}
else if (bead_count == 2)
{
const coord_t outer_width = thickness / 2;
ret.bead_widths.emplace_back(outer_width);
ret.bead_widths.emplace_back(outer_width);
ret.toolpath_locations.emplace_back(outer_width / 2);
ret.toolpath_locations.emplace_back(thickness - outer_width / 2);
ret.left_over = 0;
}
else if (bead_count == 1)
{
const coord_t outer_width = thickness;
ret.bead_widths.emplace_back(outer_width);
ret.toolpath_locations.emplace_back(outer_width / 2);
ret.left_over = 0;
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return bead_count * optimal_width;
}
coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
return lower_bead_count * optimal_width + optimal_width * (lower_bead_count % 2 == 1 ? wall_split_middle_threshold : wall_add_middle_threshold);
}
coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
return (thickness + optimal_width / 2) / optimal_width;
}
} // namespace cura
<|endoftext|>
|
<commit_before>//
// CodeGenerator.cpp
// Emojicode
//
// Created by Theo Weidmann on 19/09/16.
// Copyright © 2016 Theo Weidmann. All rights reserved.
//
#include <cstring>
#include <vector>
#include "CodeGenerator.hpp"
#include "CallableParserAndGenerator.hpp"
#include "Protocol.hpp"
#include "CallableScoper.hpp"
#include "Class.hpp"
#include "EmojicodeCompiler.hpp"
#include "StringPool.hpp"
#include "ValueType.hpp"
#include "DiscardingCallableWriter.hpp"
template <typename T>
int writeUsed(const std::vector<T *> &functions, Writer &writer) {
int counter = 0;
for (auto function : functions) {
if (function->used()) {
writer.writeFunction(function);
counter++;
}
}
return counter;
}
template <typename T>
void compileUnused(const std::vector<T *> &functions) {
for (auto function : functions) {
if (!function->used() && !function->isNative()) {
DiscardingCallableWriter writer = DiscardingCallableWriter();
generateCodeForFunction(function, writer);
}
}
}
void generateCodeForFunction(Function *function, CallableWriter &w) {
CallableScoper scoper = CallableScoper();
if (CallableParserAndGenerator::hasInstanceScope(function->compilationMode())) {
scoper = CallableScoper(&function->owningType().typeDefinitionFunctional()->instanceScope());
}
CallableParserAndGenerator::writeAndAnalyzeFunction(function, w, function->owningType().disableSelfResolving(),
scoper, function->compilationMode());
}
void writeClass(Type classType, Writer &writer) {
auto eclass = classType.eclass();
writer.writeEmojicodeChar(eclass->name()[0]);
if (eclass->superclass()) {
writer.writeUInt16(eclass->superclass()->index);
}
else {
// If the class does not have a superclass the own index is written.
writer.writeUInt16(eclass->index);
}
writer.writeUInt16(eclass->size());
writer.writeUInt16(eclass->fullMethodCount());
writer.writeByte(eclass->inheritsInitializers() ? 1 : 0);
writer.writeUInt16(eclass->fullInitializerCount());
writer.writeUInt16(eclass->usedMethodCount());
writer.writeUInt16(eclass->usedInitializerCount());
writeUsed(eclass->methodList(), writer);
writeUsed(eclass->typeMethodList(), writer);
writeUsed(eclass->initializerList(), writer);
writer.writeUInt16(eclass->protocols().size());
if (eclass->protocols().size() > 0) {
auto biggestPlaceholder = writer.writePlaceholder<uint16_t>();
auto smallestPlaceholder = writer.writePlaceholder<uint16_t>();
uint_fast16_t smallestProtocolIndex = UINT_FAST16_MAX;
uint_fast16_t biggestProtocolIndex = 0;
for (Type protocol : eclass->protocols()) {
writer.writeUInt16(protocol.protocol()->index);
if (protocol.protocol()->index > biggestProtocolIndex) {
biggestProtocolIndex = protocol.protocol()->index;
}
if (protocol.protocol()->index < smallestProtocolIndex) {
smallestProtocolIndex = protocol.protocol()->index;
}
writer.writeUInt16(protocol.protocol()->methods().size());
for (auto method : protocol.protocol()->methods()) {
try {
Function *clm = eclass->lookupMethod(method->name());
if (clm == nullptr) {
auto className = classType.toString(Type::nothingness(), true);
auto protocolName = protocol.toString(Type::nothingness(), true);
throw CompilerError(eclass->position(),
"Class %s does not agree to protocol %s: Method %s is missing.",
className.c_str(), protocolName.c_str(),
method->name().utf8().c_str());
}
writer.writeUInt16(clm->vtiForUse());
clm->enforcePromises(method, classType, TypeContext(protocol));
}
catch (CompilerError &ce) {
printError(ce);
}
}
}
biggestPlaceholder.write(biggestProtocolIndex);
smallestPlaceholder.write(smallestProtocolIndex);
}
std::vector<ObjectVariableInformation> information;
for (auto variable : eclass->instanceScope().map()) {
variable.second.type().objectVariableRecords(variable.second.id(), information);
}
writer.writeUInt16(information.size());
for (auto information : information) {
writer.writeUInt16(information.index);
writer.writeUInt16(information.conditionIndex);
writer.writeUInt16(static_cast<uint16_t>(information.type));
}
}
void writePackageHeader(Package *pkg, Writer &writer) {
if (pkg->requiresBinary()) {
size_t l = pkg->name().size() + 1;
writer.writeByte(l);
writer.writeBytes(pkg->name().c_str(), l);
writer.writeUInt16(pkg->version().major);
writer.writeUInt16(pkg->version().minor);
}
else {
writer.writeByte(0);
}
writer.writeUInt16(pkg->classes().size());
}
void generateCode(Writer &writer) {
auto &theStringPool = StringPool::theStringPool();
theStringPool.poolString(EmojicodeString());
ValueTypeVTIProvider provider;
Function::start->setVtiProvider(&provider);
Function::start->vtiForUse();
for (auto vt : ValueType::valueTypes()) { // Must be processed first, different sizes
vt->finalize();
}
for (auto eclass : Class::classes()) { // Can be processed afterwards, all pointer are 1 word
eclass->finalize();
}
while (!Function::compilationQueue.empty()) {
Function *function = Function::compilationQueue.front();
generateCodeForFunction(function, function->writer_);
Function::compilationQueue.pop();
}
writer.writeByte(ByteCodeSpecificationVersion);
writer.writeUInt16(Class::classes().size());
writer.writeUInt16(Function::functionCount());
auto pkgCount = Package::packagesInOrder().size();
if (pkgCount > 256) {
throw CompilerError(Package::packagesInOrder().back()->position(),
"You exceeded the maximum of 256 packages.");
}
writer.writeByte(pkgCount);
for (auto pkg : Package::packagesInOrder()) {
writePackageHeader(pkg, writer);
for (auto cl : pkg->classes()) {
writeClass(Type(cl, false), writer);
}
auto placeholder = writer.writePlaceholder<uint16_t>();
placeholder.write(writeUsed(pkg->functions(), writer));
}
writer.writeUInt16(theStringPool.strings().size());
for (auto string : theStringPool.strings()) {
writer.writeUInt16(string.size());
for (auto c : string) {
writer.writeEmojicodeChar(c);
}
}
for (auto eclass : Class::classes()) {
compileUnused(eclass->methodList());
compileUnused(eclass->initializerList());
compileUnused(eclass->typeMethodList());
}
for (auto vt : ValueType::valueTypes()) {
compileUnused(vt->methodList());
compileUnused(vt->initializerList());
compileUnused(vt->typeMethodList());
}
}
<commit_msg>😡 Rename variable for GCC 5<commit_after>//
// CodeGenerator.cpp
// Emojicode
//
// Created by Theo Weidmann on 19/09/16.
// Copyright © 2016 Theo Weidmann. All rights reserved.
//
#include <cstring>
#include <vector>
#include "CodeGenerator.hpp"
#include "CallableParserAndGenerator.hpp"
#include "Protocol.hpp"
#include "CallableScoper.hpp"
#include "Class.hpp"
#include "EmojicodeCompiler.hpp"
#include "StringPool.hpp"
#include "ValueType.hpp"
#include "DiscardingCallableWriter.hpp"
template <typename T>
int writeUsed(const std::vector<T *> &functions, Writer &writer) {
int counter = 0;
for (auto function : functions) {
if (function->used()) {
writer.writeFunction(function);
counter++;
}
}
return counter;
}
template <typename T>
void compileUnused(const std::vector<T *> &functions) {
for (auto function : functions) {
if (!function->used() && !function->isNative()) {
DiscardingCallableWriter writer = DiscardingCallableWriter();
generateCodeForFunction(function, writer);
}
}
}
void generateCodeForFunction(Function *function, CallableWriter &w) {
CallableScoper scoper = CallableScoper();
if (CallableParserAndGenerator::hasInstanceScope(function->compilationMode())) {
scoper = CallableScoper(&function->owningType().typeDefinitionFunctional()->instanceScope());
}
CallableParserAndGenerator::writeAndAnalyzeFunction(function, w, function->owningType().disableSelfResolving(),
scoper, function->compilationMode());
}
void writeClass(Type classType, Writer &writer) {
auto eclass = classType.eclass();
writer.writeEmojicodeChar(eclass->name()[0]);
if (eclass->superclass()) {
writer.writeUInt16(eclass->superclass()->index);
}
else {
// If the class does not have a superclass the own index is written.
writer.writeUInt16(eclass->index);
}
writer.writeUInt16(eclass->size());
writer.writeUInt16(eclass->fullMethodCount());
writer.writeByte(eclass->inheritsInitializers() ? 1 : 0);
writer.writeUInt16(eclass->fullInitializerCount());
writer.writeUInt16(eclass->usedMethodCount());
writer.writeUInt16(eclass->usedInitializerCount());
writeUsed(eclass->methodList(), writer);
writeUsed(eclass->typeMethodList(), writer);
writeUsed(eclass->initializerList(), writer);
writer.writeUInt16(eclass->protocols().size());
if (eclass->protocols().size() > 0) {
auto biggestPlaceholder = writer.writePlaceholder<uint16_t>();
auto smallestPlaceholder = writer.writePlaceholder<uint16_t>();
uint_fast16_t smallestProtocolIndex = UINT_FAST16_MAX;
uint_fast16_t biggestProtocolIndex = 0;
for (Type protocol : eclass->protocols()) {
writer.writeUInt16(protocol.protocol()->index);
if (protocol.protocol()->index > biggestProtocolIndex) {
biggestProtocolIndex = protocol.protocol()->index;
}
if (protocol.protocol()->index < smallestProtocolIndex) {
smallestProtocolIndex = protocol.protocol()->index;
}
writer.writeUInt16(protocol.protocol()->methods().size());
for (auto method : protocol.protocol()->methods()) {
try {
Function *clm = eclass->lookupMethod(method->name());
if (clm == nullptr) {
auto className = classType.toString(Type::nothingness(), true);
auto protocolName = protocol.toString(Type::nothingness(), true);
throw CompilerError(eclass->position(),
"Class %s does not agree to protocol %s: Method %s is missing.",
className.c_str(), protocolName.c_str(),
method->name().utf8().c_str());
}
writer.writeUInt16(clm->vtiForUse());
clm->enforcePromises(method, classType, TypeContext(protocol));
}
catch (CompilerError &ce) {
printError(ce);
}
}
}
biggestPlaceholder.write(biggestProtocolIndex);
smallestPlaceholder.write(smallestProtocolIndex);
}
std::vector<ObjectVariableInformation> information;
for (auto variable : eclass->instanceScope().map()) {
variable.second.type().objectVariableRecords(variable.second.id(), information);
}
writer.writeUInt16(information.size());
for (auto info : information) {
writer.writeUInt16(info.index);
writer.writeUInt16(info.conditionIndex);
writer.writeUInt16(static_cast<uint16_t>(info.type));
}
}
void writePackageHeader(Package *pkg, Writer &writer) {
if (pkg->requiresBinary()) {
size_t l = pkg->name().size() + 1;
writer.writeByte(l);
writer.writeBytes(pkg->name().c_str(), l);
writer.writeUInt16(pkg->version().major);
writer.writeUInt16(pkg->version().minor);
}
else {
writer.writeByte(0);
}
writer.writeUInt16(pkg->classes().size());
}
void generateCode(Writer &writer) {
auto &theStringPool = StringPool::theStringPool();
theStringPool.poolString(EmojicodeString());
ValueTypeVTIProvider provider;
Function::start->setVtiProvider(&provider);
Function::start->vtiForUse();
for (auto vt : ValueType::valueTypes()) { // Must be processed first, different sizes
vt->finalize();
}
for (auto eclass : Class::classes()) { // Can be processed afterwards, all pointer are 1 word
eclass->finalize();
}
while (!Function::compilationQueue.empty()) {
Function *function = Function::compilationQueue.front();
generateCodeForFunction(function, function->writer_);
Function::compilationQueue.pop();
}
writer.writeByte(ByteCodeSpecificationVersion);
writer.writeUInt16(Class::classes().size());
writer.writeUInt16(Function::functionCount());
auto pkgCount = Package::packagesInOrder().size();
if (pkgCount > 256) {
throw CompilerError(Package::packagesInOrder().back()->position(),
"You exceeded the maximum of 256 packages.");
}
writer.writeByte(pkgCount);
for (auto pkg : Package::packagesInOrder()) {
writePackageHeader(pkg, writer);
for (auto cl : pkg->classes()) {
writeClass(Type(cl, false), writer);
}
auto placeholder = writer.writePlaceholder<uint16_t>();
placeholder.write(writeUsed(pkg->functions(), writer));
}
writer.writeUInt16(theStringPool.strings().size());
for (auto string : theStringPool.strings()) {
writer.writeUInt16(string.size());
for (auto c : string) {
writer.writeEmojicodeChar(c);
}
}
for (auto eclass : Class::classes()) {
compileUnused(eclass->methodList());
compileUnused(eclass->initializerList());
compileUnused(eclass->typeMethodList());
}
for (auto vt : ValueType::valueTypes()) {
compileUnused(vt->methodList());
compileUnused(vt->initializerList());
compileUnused(vt->typeMethodList());
}
}
<|endoftext|>
|
<commit_before>//
// Object.c
// Emojicode
//
// Created by Theo Weidmann on 01.03.15.
// Copyright (c) 2015 Theo Weidmann. All rights reserved.
//
#include "Memory.hpp"
#include "Class.hpp"
#include "Engine.hpp"
#include "Thread.hpp"
#include <algorithm>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <thread>
#include <atomic>
namespace Emojicode {
std::atomic_size_t memoryUse(0);
bool zeroingNeeded = false;
Byte *currentHeap;
Byte *otherHeap;
void gc(std::unique_lock<std::mutex> &garbageCollectionLock, size_t minSpace);
size_t gcThreshold = heapSize / 2;
unsigned int pausingThreadsCount = 0;
std::atomic_bool pauseThreads(false);
std::mutex pausingThreadsCountMutex;
std::mutex garbageCollectionMutex;
std::condition_variable pauseThreadsCondition;
std::condition_variable pausingThreadsCountCondition;
inline Object* allocateObject(size_t size, Object **keep = nullptr, Thread *thread = nullptr) {
RetainedObjectPointer rop(nullptr);
if (pauseThreads) {
if (keep != nullptr) {
rop = thread->retain(*keep);
}
performPauseForGC();
if (keep != nullptr) {
*keep = rop.unretainedPointer();
thread->release(1);
}
}
size_t index;
if ((index = memoryUse.fetch_add(size)) + size > gcThreshold) {
memoryUse -= size;
if (keep != nullptr) {
rop = thread->retain(*keep);
}
std::unique_lock<std::mutex> lock(garbageCollectionMutex, std::try_to_lock);
if (lock.owns_lock()) { // OK, this thread is now the garbage collector
gc(lock, size);
}
else { // This thread also detected it’s time for garbage collection but lost the race...
while (!pauseThreads);
performPauseForGC();
}
if (keep != nullptr) {
*keep = rop.unretainedPointer();
thread->release(1);
}
return allocateObject(size);
}
return reinterpret_cast<Object *>(currentHeap + index);
}
inline bool inCurrentHeap(Object *o) {
return currentHeap <= reinterpret_cast<Byte *>(o) && reinterpret_cast<Byte *>(o) < currentHeap + heapSize / 2;
}
Object* resizeObject(Object *ptr, size_t newSize, Thread *thread) {
// auto expectation = reinterpret_cast<size_t>(ptr) - reinterpret_cast<size_t>(currentHeap);
// size_t index = memoryUse;
// if (index + newSize <= gcThreshold && memoryUse.compare_exchange_weak(expectation, index + newSize)) {
// // memoryUse equaled the expectation, therefore no allocation has happend in the meantime, index still
// // represented the value of memory use and it was leigtimate to replace memoryUse’s value with index + newSize
// return ptr;
// }
Object *block = allocateObject(newSize, &ptr, thread);
std::memcpy(block, ptr, ptr->size);
return block;
}
Object* newObject(Class *klass) {
Object *object = allocateObject(klass->size);
object->size = klass->size;
object->klass = klass;
return object;
}
size_t sizeCalculationWithOverflowProtection(size_t items, size_t itemSize) {
size_t r = items * itemSize;
if (r / items != itemSize) {
error("Integer overflow while allocating memory. It’s not possible to allocate objects of this size due to "
"hardware limitations.");
}
return r;
}
Object* newArray(size_t size) {
size_t fullSize = alignSize(sizeof(Object) + size);
Object *object = allocateObject(fullSize);
object->size = fullSize;
object->klass = CL_ARRAY;
return object;
}
Object* resizeArray(Object *array, size_t size, Thread *thread) {
size_t fullSize = alignSize(sizeof(Object) + size);
Object *object = resizeObject(array, fullSize, thread);
object->size = fullSize;
return object;
}
void allocateHeap() {
currentHeap = static_cast<Byte *>(calloc(heapSize, 1));
if (!currentHeap) {
error("Cannot allocate heap!");
}
otherHeap = currentHeap + (heapSize / 2);
}
void mark(Object **oPointer) {
Object *oldObject = *oPointer;
if (inCurrentHeap(oldObject->newLocation)) {
*oPointer = oldObject->newLocation;
return;
}
auto *newObject = reinterpret_cast<Object *>(currentHeap + memoryUse);
memoryUse += oldObject->size;
std::memcpy(newObject, oldObject, oldObject->size);
oldObject->newLocation = newObject;
*oPointer = newObject;
}
inline bool inOldHeap(Value *o) {
return otherHeap <= reinterpret_cast<Byte *>(o) && reinterpret_cast<Byte *>(o) < otherHeap + heapSize / 2;
}
void markValueReference(Value **valuePointer) {
if (!inOldHeap(*valuePointer)) {
return;
}
auto b = reinterpret_cast<Byte *>(*valuePointer);
Byte *byte = otherHeap;
while (true) {
auto object = reinterpret_cast<Object *>(byte);
if (b < byte + object->size) {
auto offset = b - byte;
mark(&object);
*valuePointer = reinterpret_cast<Value *>(reinterpret_cast<Byte *>(object) + offset);
return;
}
byte += object->size;
}
}
void gc(std::unique_lock<std::mutex> &garbageCollectionLock, size_t minSpace) {
pauseThreads = true;
if (minSpace > gcThreshold) {
error("Allocation of %zu bytes is too big. Try to enlarge the heap. (Heap size: %zu)", minSpace, heapSize);
}
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.wait(pausingThreadsCountLock, []{
return pausingThreadsCount == ThreadsManager::threadsCount();
});
std::swap(currentHeap, otherHeap);
size_t oldMemoryUse = memoryUse;
memoryUse = 0;
std::lock_guard<std::mutex> threadListLock(ThreadsManager::threadListMutex);
for (Thread *thread = ThreadsManager::anyThread(); thread != nullptr; thread = ThreadsManager::nextThread(thread)) {
thread->markStack();
thread->markRetainList();
}
for (uint_fast16_t i = 0; i < stringPoolCount; i++) {
mark(stringPool + i);
}
for (Byte *byte = currentHeap; byte < currentHeap + memoryUse;) {
auto object = reinterpret_cast<Object *>(byte);
for (size_t i = 0; i < object->klass->instanceVariableRecordsCount; i++) {
auto record = object->klass->instanceVariableRecords[i];
markByObjectVariableRecord(record, object->variableDestination(0), i);
}
if (object->klass->mark != nullptr) {
object->klass->mark(object);
}
byte += object->size;
}
if (oldMemoryUse == memoryUse) {
error("Terminating program due to too high memory pressure.");
}
// std::memset(otherHeap, 0xAA, heapSize / 2);
if (zeroingNeeded) {
std::memset(currentHeap + memoryUse, 0, (heapSize / 2) - memoryUse);
}
else {
zeroingNeeded = true;
}
pausingThreadsCount--;
pausingThreadsCountLock.unlock();
pauseThreads = false;
garbageCollectionLock.unlock();
pauseThreadsCondition.notify_all();
}
void pauseForGC() {
if (pauseThreads) {
performPauseForGC();
}
}
inline void performPauseForGC() {
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.notify_one();
pauseThreadsCondition.wait(pausingThreadsCountLock, []{ return !pauseThreads; });
pausingThreadsCount--;
}
void allowGC() {
std::unique_lock<std::mutex> pausingThreadsCountLock(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.notify_one();
}
void disallowGCAndPauseIfNeeded() {
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pauseThreadsCondition.wait(pausingThreadsCountLock, []{ return !pauseThreads; });
pausingThreadsCount--;
pausingThreadsCountCondition.notify_one();
}
} // namespace Emojicode
<commit_msg>🔒 Proper lock order<commit_after>//
// Object.c
// Emojicode
//
// Created by Theo Weidmann on 01.03.15.
// Copyright (c) 2015 Theo Weidmann. All rights reserved.
//
#include "Memory.hpp"
#include "Class.hpp"
#include "Engine.hpp"
#include "Thread.hpp"
#include <algorithm>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <thread>
#include <atomic>
namespace Emojicode {
std::atomic_size_t memoryUse(0);
bool zeroingNeeded = false;
Byte *currentHeap;
Byte *otherHeap;
void gc(std::unique_lock<std::mutex> &garbageCollectionLock, size_t minSpace);
size_t gcThreshold = heapSize / 2;
unsigned int pausingThreadsCount = 0;
std::atomic_bool pauseThreads(false);
std::mutex pausingThreadsCountMutex;
std::mutex garbageCollectionMutex;
std::condition_variable pauseThreadsCondition;
std::condition_variable pausingThreadsCountCondition;
inline Object* allocateObject(size_t size, Object **keep = nullptr, Thread *thread = nullptr) {
RetainedObjectPointer rop(nullptr);
if (pauseThreads) {
if (keep != nullptr) {
rop = thread->retain(*keep);
}
performPauseForGC();
if (keep != nullptr) {
*keep = rop.unretainedPointer();
thread->release(1);
}
}
size_t index;
if ((index = memoryUse.fetch_add(size)) + size > gcThreshold) {
memoryUse -= size;
if (keep != nullptr) {
rop = thread->retain(*keep);
}
std::unique_lock<std::mutex> lock(garbageCollectionMutex, std::try_to_lock);
if (lock.owns_lock()) { // OK, this thread is now the garbage collector
gc(lock, size);
}
else { // This thread also detected it’s time for garbage collection but lost the race...
while (!pauseThreads);
performPauseForGC();
}
if (keep != nullptr) {
*keep = rop.unretainedPointer();
thread->release(1);
}
return allocateObject(size);
}
return reinterpret_cast<Object *>(currentHeap + index);
}
inline bool inCurrentHeap(Object *o) {
return currentHeap <= reinterpret_cast<Byte *>(o) && reinterpret_cast<Byte *>(o) < currentHeap + heapSize / 2;
}
Object* resizeObject(Object *ptr, size_t newSize, Thread *thread) {
// auto expectation = reinterpret_cast<size_t>(ptr) - reinterpret_cast<size_t>(currentHeap);
// size_t index = memoryUse;
// if (index + newSize <= gcThreshold && memoryUse.compare_exchange_weak(expectation, index + newSize)) {
// // memoryUse equaled the expectation, therefore no allocation has happend in the meantime, index still
// // represented the value of memory use and it was leigtimate to replace memoryUse’s value with index + newSize
// return ptr;
// }
Object *block = allocateObject(newSize, &ptr, thread);
std::memcpy(block, ptr, ptr->size);
return block;
}
Object* newObject(Class *klass) {
Object *object = allocateObject(klass->size);
object->size = klass->size;
object->klass = klass;
return object;
}
size_t sizeCalculationWithOverflowProtection(size_t items, size_t itemSize) {
size_t r = items * itemSize;
if (r / items != itemSize) {
error("Integer overflow while allocating memory. It’s not possible to allocate objects of this size due to "
"hardware limitations.");
}
return r;
}
Object* newArray(size_t size) {
size_t fullSize = alignSize(sizeof(Object) + size);
Object *object = allocateObject(fullSize);
object->size = fullSize;
object->klass = CL_ARRAY;
return object;
}
Object* resizeArray(Object *array, size_t size, Thread *thread) {
size_t fullSize = alignSize(sizeof(Object) + size);
Object *object = resizeObject(array, fullSize, thread);
object->size = fullSize;
return object;
}
void allocateHeap() {
currentHeap = static_cast<Byte *>(calloc(heapSize, 1));
if (!currentHeap) {
error("Cannot allocate heap!");
}
otherHeap = currentHeap + (heapSize / 2);
}
void mark(Object **oPointer) {
Object *oldObject = *oPointer;
if (inCurrentHeap(oldObject->newLocation)) {
*oPointer = oldObject->newLocation;
return;
}
auto *newObject = reinterpret_cast<Object *>(currentHeap + memoryUse);
memoryUse += oldObject->size;
std::memcpy(newObject, oldObject, oldObject->size);
oldObject->newLocation = newObject;
*oPointer = newObject;
}
inline bool inOldHeap(Value *o) {
return otherHeap <= reinterpret_cast<Byte *>(o) && reinterpret_cast<Byte *>(o) < otherHeap + heapSize / 2;
}
void markValueReference(Value **valuePointer) {
if (!inOldHeap(*valuePointer)) {
return;
}
auto b = reinterpret_cast<Byte *>(*valuePointer);
Byte *byte = otherHeap;
while (true) {
auto object = reinterpret_cast<Object *>(byte);
if (b < byte + object->size) {
auto offset = b - byte;
mark(&object);
*valuePointer = reinterpret_cast<Value *>(reinterpret_cast<Byte *>(object) + offset);
return;
}
byte += object->size;
}
}
void gc(std::unique_lock<std::mutex> &garbageCollectionLock, size_t minSpace) {
pauseThreads = true;
if (minSpace > gcThreshold) {
error("Allocation of %zu bytes is too big. Try to enlarge the heap. (Heap size: %zu)", minSpace, heapSize);
}
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.wait(pausingThreadsCountLock, []{
return pausingThreadsCount == ThreadsManager::threadsCount();
});
std::swap(currentHeap, otherHeap);
size_t oldMemoryUse = memoryUse;
memoryUse = 0;
std::lock_guard<std::mutex> threadListLock(ThreadsManager::threadListMutex);
for (Thread *thread = ThreadsManager::anyThread(); thread != nullptr; thread = ThreadsManager::nextThread(thread)) {
thread->markStack();
thread->markRetainList();
}
for (uint_fast16_t i = 0; i < stringPoolCount; i++) {
mark(stringPool + i);
}
for (Byte *byte = currentHeap; byte < currentHeap + memoryUse;) {
auto object = reinterpret_cast<Object *>(byte);
for (size_t i = 0; i < object->klass->instanceVariableRecordsCount; i++) {
auto record = object->klass->instanceVariableRecords[i];
markByObjectVariableRecord(record, object->variableDestination(0), i);
}
if (object->klass->mark != nullptr) {
object->klass->mark(object);
}
byte += object->size;
}
if (oldMemoryUse == memoryUse) {
error("Terminating program due to too high memory pressure.");
}
// std::memset(otherHeap, 0xAA, heapSize / 2);
if (zeroingNeeded) {
std::memset(currentHeap + memoryUse, 0, (heapSize / 2) - memoryUse);
}
else {
zeroingNeeded = true;
}
pausingThreadsCount--;
pauseThreads = false;
garbageCollectionLock.unlock();
pauseThreadsCondition.notify_all();
pausingThreadsCountLock.unlock();
}
void pauseForGC() {
if (pauseThreads) {
performPauseForGC();
}
}
inline void performPauseForGC() {
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.notify_one();
pauseThreadsCondition.wait(pausingThreadsCountLock, []{ return !pauseThreads; });
pausingThreadsCount--;
}
void allowGC() {
std::unique_lock<std::mutex> pausingThreadsCountLock(pausingThreadsCountMutex);
pausingThreadsCount++;
pausingThreadsCountCondition.notify_one();
}
void disallowGCAndPauseIfNeeded() {
auto pausingThreadsCountLock = std::unique_lock<std::mutex>(pausingThreadsCountMutex);
pauseThreadsCondition.wait(pausingThreadsCountLock, []{ return !pauseThreads; });
pausingThreadsCount--;
pausingThreadsCountCondition.notify_one();
}
} // namespace Emojicode
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: ClusterImageStatistics.cxx,v $
Language: C++
Date: $Date: 2008/12/15 16:35:13 $
Version: $Revision: 1.20 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkDiscreteGaussianImageFilter.h"
// RecursiveAverageImages img1 img2 weightonimg2 outputname
// We divide the 2nd input image by its mean and add it to the first
// input image with weight 1/n.
// The output overwrites the 1st img with the sum.
#include <list>
#include <vector>
#include <fstream>
#include "vnl/vnl_vector.h"
#include "itkMinimumMaximumImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkLabelStatisticsImageFilter.h"
#include "ReadWriteImage.h"
template <unsigned int ImageDimension>
int ClusterStatistics(unsigned int argc, char *argv[])
{
typedef float PixelType;
// const unsigned int ImageDimension = AvantsImageDimension;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> FieldType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::ImageFileReader<ImageType> readertype;
typedef itk::ImageFileWriter<ImageType> writertype;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef itk::AffineTransform<double, ImageDimension> AffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType1;
typedef itk::NearestNeighborInterpolateImageFunction<ImageType, double> InterpolatorType2;
// typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
typedef float InternalPixelType;
typedef unsigned long ULPixelType;
typedef itk::Image<ULPixelType, ImageDimension> labelimagetype;
typedef ImageType InternalImageType;
typedef ImageType OutputImageType;
typedef itk::ConnectedComponentImageFilter<ImageType, labelimagetype> FilterType;
typedef itk::RelabelComponentImageFilter<labelimagetype, labelimagetype> RelabelType;
// want the average value in each cluster as defined by the mask and the value thresh and the clust thresh
std::string roimaskfn = std::string(argv[2]);
std::string labelimagefn = std::string(argv[3]);
std::string outname = std::string(argv[4]);
float clusterthresh = atof(argv[5]);
float minSize = clusterthresh;
float valuethresh = atof(argv[6]);
std::cout << " Cth " << clusterthresh << " Vth " << valuethresh << std::endl;
typename ImageType::Pointer valimage = NULL;
typename ImageType::Pointer roiimage = NULL;
typename ImageType::Pointer labelimage = NULL;
ReadImage<ImageType>(roiimage, roimaskfn.c_str() );
ReadImage<ImageType>(labelimage, labelimagefn.c_str() );
typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType;
typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New();
minMaxFilter->SetInput( labelimage );
minMaxFilter->Update();
double min = minMaxFilter->GetMinimum();
double max = minMaxFilter->GetMaximum();
double range = max - min;
for( unsigned int filecount = 7; filecount < argc; filecount++ )
{
std::cout << " doing " << std::string(argv[filecount]) << std::endl;
ReadImage<ImageType>(valimage, argv[filecount]);
// first, threshold the value image then get the clusters of min size
typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> ThresholdFilterType;
typename ThresholdFilterType::Pointer threshold = ThresholdFilterType::New();
threshold->SetInput(valimage);
threshold->SetInsideValue(1);
threshold->SetOutsideValue(0);
threshold->SetLowerThreshold(valuethresh);
threshold->SetUpperThreshold(1.e9);
threshold->Update();
typename ImageType::Pointer thresh = threshold->GetOutput();
typedef itk::ImageRegionIteratorWithIndex<ImageType> fIterator;
typedef itk::ImageRegionIteratorWithIndex<labelimagetype> Iterator;
fIterator tIter( thresh, thresh->GetLargestPossibleRegion() );
for( tIter.GoToBegin(); !tIter.IsAtEnd(); ++tIter )
{
if( roiimage->GetPixel(tIter.GetIndex() ) < 0.5 )
{
tIter.Set(0);
}
}
// typename
typename FilterType::Pointer filter = FilterType::New();
// typename
typename RelabelType::Pointer relabel = RelabelType::New();
filter->SetInput( thresh );
int fullyConnected = 0; // atoi( argv[5] );
filter->SetFullyConnected( fullyConnected );
relabel->SetInput( filter->GetOutput() );
relabel->SetMinimumObjectSize( (unsigned int) minSize );
try
{
relabel->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Relabel: exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
typename ImageType::Pointer Clusters = MakeNewImage<ImageType>(valimage, 0);
typename ImageType::Pointer Values = MakeNewImage<ImageType>(valimage, 0);
typename ImageType::Pointer Labels = MakeNewImage<ImageType>(valimage, 0);
Iterator vfIter( relabel->GetOutput(), relabel->GetOutput()->GetLargestPossibleRegion() );
float maximum = relabel->GetNumberOfObjects();
std::cout << " #object " << maximum << std::endl;
// float maxtstat=0;
std::vector<unsigned long> histogram( (int)maximum + 1);
std::vector<long> maxlabel( (int)maximum + 1);
std::vector<float> suminlabel( (unsigned long) range + 1);
std::vector<unsigned long> countinlabel( (unsigned long) range + 1);
std::vector<float> sumofvalues( (int)maximum + 1);
std::vector<float> maxvalue( (int)maximum + 1);
for( int i = 0; i <= maximum; i++ )
{
histogram[i] = 0;
sumofvalues[i] = 0;
maxvalue[i] = 0;
maxlabel[i] = 0;
}
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( vfIter.Get() > 0 )
{
float vox = valimage->GetPixel(vfIter.GetIndex() );
if( vox >= valuethresh )
{
histogram[(unsigned long)vfIter.Get()] = histogram[(unsigned long)vfIter.Get()] + 1;
sumofvalues[(unsigned long)vfIter.Get()] = sumofvalues[(unsigned long)vfIter.Get()] + vox;
if( maxvalue[(unsigned long)vfIter.Get()] < vox )
{
maxvalue[(unsigned long)vfIter.Get()] = vox;
maxlabel[(unsigned long)vfIter.Get()] = (long int)labelimage->GetPixel(vfIter.GetIndex() );
}
suminlabel[(unsigned long)(labelimage->GetPixel(vfIter.GetIndex() ) - min)] += vox;
countinlabel[(unsigned long)(labelimage->GetPixel(vfIter.GetIndex() ) - min)] += 1;
}
}
}
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( vfIter.Get() > 0 )
{
Clusters->SetPixel( vfIter.GetIndex(), histogram[(unsigned long)vfIter.Get()] );
Values->SetPixel( vfIter.GetIndex(), sumofvalues[(unsigned long)vfIter.Get()]
/ (float)histogram[(unsigned int)vfIter.Get()] );
Labels->SetPixel( vfIter.GetIndex(), labelimage->GetPixel(vfIter.GetIndex() ) );
}
else
{
Clusters->SetPixel(vfIter.GetIndex(), 0);
Labels->SetPixel(vfIter.GetIndex(), 0);
Values->SetPixel(vfIter.GetIndex(), 0);
}
}
// WriteImage<ImageType>(Values,std::string("temp.nii.gz").c_str());
// WriteImage<ImageType>(Clusters,std::string("temp2.nii.gz").c_str());
float maximgval = 0;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( Clusters->GetPixel( vfIter.GetIndex() ) > maximgval )
{
maximgval = Clusters->GetPixel( vfIter.GetIndex() );
}
}
std::cout << " max size " << maximgval << std::endl;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( Clusters->GetPixel( vfIter.GetIndex() ) < minSize )
{
Clusters->SetPixel( vfIter.GetIndex(), 0);
Values->SetPixel( vfIter.GetIndex(), 0);
Labels->SetPixel( vfIter.GetIndex(), 0);
}
}
// WriteImage<ImageType>(Values,(outname+"values.nii.gz").c_str());
// WriteImage<ImageType>(Labels,(outname+"labels.nii.gz").c_str());
WriteImage<ImageType>(Clusters, (outname + "sizes.nii.gz").c_str() );
// now begin output
std::cout << " Writing Text File " << outname << std::endl;
std::ofstream outf( (outname).c_str(), std::ofstream::app);
if( outf.good() )
{
outf << std::string(argv[filecount]) << std::endl;
for( int i = 0; i < maximum + 1; i++ )
{
if( histogram[i] >= minSize )
{
outf << " Cluster " << i << " size " << histogram[i] << " average " << sumofvalues[i]
/ (float)histogram[i] << " max " << maxvalue[i] << " label " << maxlabel[i] << std::endl;
std::cout << " Cluster " << i << " size " << histogram[i] << " average " << sumofvalues[i]
/ (float)histogram[i] << " max " << maxvalue[i] << " label " << maxlabel[i] << std::endl;
}
}
for( unsigned int i = 0; i <= range; i++ )
{
if( countinlabel[i] > 0 )
{
outf << " Label " << i + min << " average " << suminlabel[i] / (float)countinlabel[i] << std::endl;
std::cout << " Label " << i + min << " average " << suminlabel[i] / (float)countinlabel[i] << std::endl;
}
}
}
else
{
std::cout << " File No Good! " << outname << std::endl;
}
outf.close();
}
return 0;
}
int main(int argc, char *argv[])
{
if( argc < 4 )
{
std::cout
<<
" Given an ROI and Label Image, find the max and average value \n in a value image where the value > some user-defined threshold \n and the cluster size is larger than some min size. \n "
<< std::endl;
std::cout << "Useage ex: \n " << std::endl;
std::cout << argv[0]
<<
" ImageDimension ROIMask.ext LabelImage.ext OutPrefix MinimumClusterSize ValueImageThreshold Image1WithValuesOfInterest.ext ... ImageNWithValuesOfInterest.ext \n \n "
<< std::endl;
std::cout
<<
" ROIMask.ext -- overall region of interest \n \n LabelImage.ext -- labels for the sub-regions, e.g. Brodmann or just unique labels (see LabelClustersUniquely ) \n \n OutputPrefix -- all output has this prefix \n \n MinimumClusterSize -- the minimum size of clusters of interest \n \n ValueImageThreshold -- minimum value of interest \n \n Image*WithValuesOfInterest.ext --- image(s) that define the values you want to measure \n ";
return 1;
}
switch( atoi(argv[1]) )
{
case 2:
{
ClusterStatistics<2>(argc, argv);
}
break;
case 3:
{
ClusterStatistics<3>(argc, argv);
}
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
return 0;
}
<commit_msg> ClusterImage ==> .csv file <commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: ClusterImageStatistics.cxx,v $
Language: C++
Date: $Date: 2008/12/15 16:35:13 $
Version: $Revision: 1.20 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkDiscreteGaussianImageFilter.h"
// RecursiveAverageImages img1 img2 weightonimg2 outputname
// We divide the 2nd input image by its mean and add it to the first
// input image with weight 1/n.
// The output overwrites the 1st img with the sum.
#include <list>
#include <vector>
#include <fstream>
#include "vnl/vnl_vector.h"
#include "itkMinimumMaximumImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkLabelStatisticsImageFilter.h"
#include "ReadWriteImage.h"
template <unsigned int ImageDimension>
int ClusterStatistics(unsigned int argc, char *argv[])
{
typedef float PixelType;
// const unsigned int ImageDimension = AvantsImageDimension;
typedef itk::Vector<float, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> FieldType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::ImageFileReader<ImageType> readertype;
typedef itk::ImageFileWriter<ImageType> writertype;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef itk::AffineTransform<double, ImageDimension> AffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType1;
typedef itk::NearestNeighborInterpolateImageFunction<ImageType, double> InterpolatorType2;
// typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
typedef float InternalPixelType;
typedef unsigned long ULPixelType;
typedef itk::Image<ULPixelType, ImageDimension> labelimagetype;
typedef ImageType InternalImageType;
typedef ImageType OutputImageType;
typedef itk::ConnectedComponentImageFilter<ImageType, labelimagetype> FilterType;
typedef itk::RelabelComponentImageFilter<labelimagetype, labelimagetype> RelabelType;
// want the average value in each cluster as defined by the mask and the value thresh and the clust thresh
std::string roimaskfn = std::string(argv[2]);
std::string labelimagefn = std::string(argv[3]);
std::string outname = std::string(argv[4]);
float clusterthresh = atof(argv[5]);
float minSize = clusterthresh;
float valuethresh = atof(argv[6]);
// std::cout << " Cth " << clusterthresh << " Vth " << valuethresh << std::endl;
typename ImageType::Pointer valimage = NULL;
typename ImageType::Pointer roiimage = NULL;
typename ImageType::Pointer labelimage = NULL;
ReadImage<ImageType>(roiimage, roimaskfn.c_str() );
ReadImage<ImageType>(labelimage, labelimagefn.c_str() );
typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType;
typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New();
minMaxFilter->SetInput( labelimage );
minMaxFilter->Update();
double min = minMaxFilter->GetMinimum();
double max = minMaxFilter->GetMaximum();
double range = max - min;
for( unsigned int filecount = 7; filecount < argc; filecount++ )
{
// std::cout <<" doing " << std::string(argv[filecount]) << std::endl;
ReadImage<ImageType>(valimage, argv[filecount]);
// first, threshold the value image then get the clusters of min size
typedef itk::BinaryThresholdImageFilter<ImageType, ImageType> ThresholdFilterType;
typename ThresholdFilterType::Pointer threshold = ThresholdFilterType::New();
threshold->SetInput(valimage);
threshold->SetInsideValue(1);
threshold->SetOutsideValue(0);
threshold->SetLowerThreshold(valuethresh);
threshold->SetUpperThreshold(1.e9);
threshold->Update();
typename ImageType::Pointer thresh = threshold->GetOutput();
typedef itk::ImageRegionIteratorWithIndex<ImageType> fIterator;
typedef itk::ImageRegionIteratorWithIndex<labelimagetype> Iterator;
fIterator tIter( thresh, thresh->GetLargestPossibleRegion() );
for( tIter.GoToBegin(); !tIter.IsAtEnd(); ++tIter )
{
if( roiimage->GetPixel(tIter.GetIndex() ) < 0.5 )
{
tIter.Set(0);
}
}
// typename
typename FilterType::Pointer filter = FilterType::New();
// typename
typename RelabelType::Pointer relabel = RelabelType::New();
filter->SetInput( thresh );
int fullyConnected = 0; // atoi( argv[5] );
filter->SetFullyConnected( fullyConnected );
relabel->SetInput( filter->GetOutput() );
relabel->SetMinimumObjectSize( (unsigned int) minSize );
try
{
relabel->Update();
}
catch( itk::ExceptionObject & excep )
{
std::cerr << "Relabel: exception caught !" << std::endl;
std::cerr << excep << std::endl;
}
typename ImageType::Pointer Clusters = MakeNewImage<ImageType>(valimage, 0);
typename ImageType::Pointer Values = MakeNewImage<ImageType>(valimage, 0);
typename ImageType::Pointer Labels = MakeNewImage<ImageType>(valimage, 0);
Iterator vfIter( relabel->GetOutput(), relabel->GetOutput()->GetLargestPossibleRegion() );
float maximum = relabel->GetNumberOfObjects();
// std::cout << " #object " << maximum << std::endl;
// float maxtstat=0;
std::vector<unsigned long> histogram( (int)maximum + 1);
std::vector<long> maxlabel( (int)maximum + 1);
std::vector<float> suminlabel( (unsigned long) range + 1);
std::vector<unsigned long> countinlabel( (unsigned long) range + 1);
std::vector<float> sumofvalues( (int)maximum + 1);
std::vector<float> maxvalue( (int)maximum + 1);
for( int i = 0; i <= maximum; i++ )
{
histogram[i] = 0;
sumofvalues[i] = 0;
maxvalue[i] = 0;
maxlabel[i] = 0;
}
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( vfIter.Get() > 0 )
{
float vox = valimage->GetPixel(vfIter.GetIndex() );
if( vox >= valuethresh )
{
histogram[(unsigned long)vfIter.Get()] = histogram[(unsigned long)vfIter.Get()] + 1;
sumofvalues[(unsigned long)vfIter.Get()] = sumofvalues[(unsigned long)vfIter.Get()] + vox;
if( maxvalue[(unsigned long)vfIter.Get()] < vox )
{
maxvalue[(unsigned long)vfIter.Get()] = vox;
maxlabel[(unsigned long)vfIter.Get()] = (long int)labelimage->GetPixel(vfIter.GetIndex() );
}
suminlabel[(unsigned long)(labelimage->GetPixel(vfIter.GetIndex() ) - min)] += vox;
countinlabel[(unsigned long)(labelimage->GetPixel(vfIter.GetIndex() ) - min)] += 1;
}
}
}
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( vfIter.Get() > 0 )
{
Clusters->SetPixel( vfIter.GetIndex(), histogram[(unsigned long)vfIter.Get()] );
Values->SetPixel( vfIter.GetIndex(), sumofvalues[(unsigned long)vfIter.Get()]
/ (float)histogram[(unsigned int)vfIter.Get()] );
Labels->SetPixel( vfIter.GetIndex(), labelimage->GetPixel(vfIter.GetIndex() ) );
}
else
{
Clusters->SetPixel(vfIter.GetIndex(), 0);
Labels->SetPixel(vfIter.GetIndex(), 0);
Values->SetPixel(vfIter.GetIndex(), 0);
}
}
// WriteImage<ImageType>(Values,std::string("temp.nii.gz").c_str());
// WriteImage<ImageType>(Clusters,std::string("temp2.nii.gz").c_str());
float maximgval = 0;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( Clusters->GetPixel( vfIter.GetIndex() ) > maximgval )
{
maximgval = Clusters->GetPixel( vfIter.GetIndex() );
}
}
// std::cout << " max size " << maximgval << std::endl;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
if( Clusters->GetPixel( vfIter.GetIndex() ) < minSize )
{
Clusters->SetPixel( vfIter.GetIndex(), 0);
Values->SetPixel( vfIter.GetIndex(), 0);
Labels->SetPixel( vfIter.GetIndex(), 0);
}
}
// WriteImage<ImageType>(Values,(outname+"values.nii.gz").c_str());
// WriteImage<ImageType>(Labels,(outname+"labels.nii.gz").c_str());
WriteImage<ImageType>(Clusters, (outname + "sizes.nii.gz").c_str() );
// now begin output
// std::cout << " Writing Text File " << outname << std::endl;
std::ofstream outf( (outname).c_str(), std::ofstream::app);
if( outf.good() )
{
// outf << std::string(argv[filecount]) << std::endl;
for( int i = 0; i < maximum + 1; i++ )
{
if( histogram[i] >= minSize )
{
// outf << " Cluster " << i << " size " << histogram[i] << " average " <<
// sumofvalues[i]/(float)histogram[i] << " max " << maxvalue[i] << " label " << maxlabel[i] << std::endl;
if( i >= 0 && i < maximum )
{
outf << sumofvalues[i] / (float)histogram[i] << ",";
}
else
{
outf << sumofvalues[i] / (float)histogram[i] << std::endl;
}
std::cout << " Cluster " << i << " size " << histogram[i] << " average " << sumofvalues[i]
/ (float)histogram[i] << " max " << maxvalue[i] << " label " << maxlabel[i] << std::endl;
}
}
for( unsigned int i = 0; i <= range; i++ )
{
if( countinlabel[i] > 0 )
{
// outf << " Label " << i+min << " average " << suminlabel[i]/(float)countinlabel[i] << std::endl;
std::cout << " Label " << i + min << " average " << suminlabel[i] / (float)countinlabel[i] << std::endl;
}
}
}
else
{
std::cout << " File No Good! " << outname << std::endl;
}
outf.close();
}
return 0;
}
int main(int argc, char *argv[])
{
if( argc < 4 )
{
std::cout
<<
" Given an ROI and Label Image, find the max and average value \n in a value image where the value > some user-defined threshold \n and the cluster size is larger than some min size. \n "
<< std::endl;
std::cout << "Useage ex: \n " << std::endl;
std::cout << argv[0]
<<
" ImageDimension ROIMask.ext LabelImage.ext OutPrefix MinimumClusterSize ValueImageThreshold Image1WithValuesOfInterest.ext ... ImageNWithValuesOfInterest.ext \n \n "
<< std::endl;
std::cout
<<
" ROIMask.ext -- overall region of interest \n \n LabelImage.ext -- labels for the sub-regions, e.g. Brodmann or just unique labels (see LabelClustersUniquely ) \n \n OutputPrefix -- all output has this prefix \n \n MinimumClusterSize -- the minimum size of clusters of interest \n \n ValueImageThreshold -- minimum value of interest \n \n Image*WithValuesOfInterest.ext --- image(s) that define the values you want to measure \n ";
return 1;
}
switch( atoi(argv[1]) )
{
case 2:
{
ClusterStatistics<2>(argc, argv);
}
break;
case 3:
{
ClusterStatistics<3>(argc, argv);
}
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "Exception.h"
#include "BackTrace.h"
#include "Demangling.h"
#include "StackAddressLoader.h"
#include "DebugSymbolLoader.h"
#include <algorithm>
#include <cstddef>
#include <exception>
#include <fstream>
#include <iterator>
#include <limits>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <typeinfo>
using namespace std;
static bool initialized = false;
#if __GNUC__
#include <cxxabi.h>
struct padding {
void* ptr;
};
static const int MAX_FRAMES = 16;
static const int INTERCEPT_SKIP = 1;
struct frames {
typedef void (*destructor)(void*);
int size;
Backtrace::StackFrame* frms;
destructor dtor;
union {
char buffer[sizeof(Backtrace::StackFrame)*MAX_FRAMES];
padding p;
};
};
static __thread frames localFrames = { 0 , 0, 0, {{0}}};
namespace {
void create_frames()
{
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms != addr) {
// só um acaso muito grande ia fazer o ponteiro apontar exatamente para o lugar certo.
localFrames.size = 0;
localFrames.frms = addr;
for (int i = 0; i < MAX_FRAMES; ++i) {
new(addr + i) Backtrace::StackFrame();
}
}
}
void destroy_frames(void *thrown_exception)
{
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms == addr) {
for (int i = 0; i < MAX_FRAMES; ++i) {
addr[i].~StackFrame();
}
localFrames.dtor(thrown_exception);
}
localFrames.size = -1;
localFrames.frms = NULL;
localFrames.dtor = NULL;
}
}
namespace ExceptionLib {
const Backtrace::StackFrame* getBT(const std::exception& ex, size_t* depth, bool loadDebugSyms)
{
const ExceptionBase* base = dynamic_cast<const ExceptionBase*>(&ex);
if (base) {
if (base->stacktrace()) {
if (loadDebugSyms) {
base->stacktrace()->loadDebug();
}
if (depth) *depth = base->stacktrace()->getFrames().size();
if (*depth > 0) {
return &base->stacktrace()->getFrames()[0];
}
}
} else {
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms != addr) {
if (depth) *depth = 0;
return NULL;
}
if (depth) *depth = localFrames.size - INTERCEPT_SKIP;
if (*depth > 0) {
if (loadDebugSyms) {
Backtrace::getPlatformDebugSymbolLoader().findDebugInfo(localFrames.frms, localFrames.size);
}
return localFrames.frms+INTERCEPT_SKIP;
}
}
return NULL;
}
}
extern "C" void * __cxa_allocate_exception(size_t size);
extern "C" void __cxa_free_exception(void *thrown_exception);
namespace {
bool find_base(const abi::__class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset);
bool recursive_find_base(const abi::__vmi_class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
for (size_t i = 0; i < actual->__base_count; ++i) {
const abi::__class_type_info* base = actual->__base_info[i].__base_type;
if (*base == *target) {
if (offset) *offset += actual->__base_info[i].__offset();
return true;
}
int _offset = 0;
if (find_base(base, target, offset)) {
if (offset) *offset += actual->__base_info[i].__offset() + _offset;
return true;
}
}
return false;
}
bool recursive_find_base(const abi::__si_class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
if (*actual->__base_type == *target) {
return true;
}
return find_base(actual->__base_type, target, offset);
}
bool find_base(const abi::__class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
if (offset) *offset = 0;
if (*actual == *target) {
return true;
}
const abi::__vmi_class_type_info* vmactual = dynamic_cast<const abi::__vmi_class_type_info*>(actual);
if (vmactual) {
return recursive_find_base(vmactual, target, offset);
}
const abi::__si_class_type_info* sactual = dynamic_cast<const abi::__si_class_type_info*>(actual);
if (sactual) {
return recursive_find_base(sactual, target, offset);
}
return false;
}
}
extern "C" void __real___cxa_throw( void* thrown_exception,
const std::type_info* tinfo, void ( *dest )( void* ) )
__attribute__(( noreturn ));
extern "C" void __wrap___cxa_throw( void* thrown_exception,
const std::type_info* tinfo, void ( *dest )( void* ) )
{
const abi::__class_type_info* cinfo = dynamic_cast<const abi::__class_type_info*>(tinfo);
if (cinfo != NULL) {
const abi::__class_type_info& exclass = dynamic_cast<const abi::__class_type_info&>(typeid(ExceptionLib::ExceptionBase));
if ( find_base(cinfo, &exclass, NULL)) {
__real___cxa_throw( thrown_exception, tinfo, dest );
return;
}
const abi::__class_type_info& stdexclass = dynamic_cast<const abi::__class_type_info&>(typeid(std::exception));
if ( find_base(cinfo, &stdexclass, NULL)) {
create_frames();
localFrames.size = Backtrace::getPlatformStackLoader().getStack(MAX_FRAMES, localFrames.frms);
localFrames.dtor = dest;
__real___cxa_throw( thrown_exception, tinfo, destroy_frames );
return;
}
}
__real___cxa_throw( thrown_exception, tinfo, dest );
}
#else
namespace ExceptionLib {
const Backtrace::StackFrame* getBT(const std::exception&, size_t* depth, bool)
{
if (depth) * depth = 0;
return NULL;
}
}
#endif
namespace ExceptionLib {
static const size_t SKIP_FRAMES = 4;
static bool stackEnabled = true;
void terminate_handler()
{
#ifdef __GNUC__
static bool tried_throw = false;
try {
if (!tried_throw) {
tried_throw = true;
throw;
}
cerr << "no active exception" << endl;
}
catch (const ExceptionLib::Exception& ex) {
cerr << "Caught an Exception: what: " << ex.what() << endl;
Backtrace::StackTrace* trace = ex.stacktrace();
if (trace) {
cerr << "stacktrace: " << endl << trace->asString() << endl;
} else {
cerr << "stacktrace: not available" << endl;
}
const ExceptionBase * eptr = &ex;
while(eptr->nested()) {
eptr = eptr->nested();
cerr << "Nested exception: what: " << eptr->what() << endl;
trace = eptr->stacktrace();
cerr << "stacktrace: " << endl << trace << endl;
}
}
catch (const std::exception &ex) {
cout << "Caught an std::exception. what(): " << ex.what() << endl;
}
catch (...) {
std::cout << "Caught unknown exception" << std::endl;
}
#else
cerr << "Caught unhandled exception" << endl;
#endif
}
void init(char *argv0)
{
::Backtrace::initialize(argv0);
set_terminate(terminate_handler);
initialized = true;
}
ExceptionBase::ExceptionBase(const ExceptionBase& that)
: BaseExceptionType()
, m_raiser(that.m_raiser)
, m_cloner(that.m_cloner)
, st(NULL)
, m_what(that.m_what)
, m_nested(NULL)
{
if (that.m_nested) {
m_nested = that.m_nested->clone();
}
if (that.st) {
st = that.st;
st->increaseCount();
}
}
ExceptionBase::~ExceptionBase() throw ()
{
try {
if (m_nested) {
delete m_nested;
}
if (st) st->decreaseCount();
st = NULL;
} catch (...) {}
}
void ExceptionBase::raise() const
{
m_raiser(this);
}
ExceptionBase* ExceptionBase::clone() const
{
return m_cloner(this);
}
const char* ExceptionBase::what() const throw()
{
return m_what.c_str();
}
const ExceptionBase* ExceptionBase::nested() const
{
return m_nested;
}
Backtrace::StackTrace* ExceptionBase::stacktrace() const
{
if (st) {
return st;
} else {
return NULL;
}
}
void NOINLINE ExceptionBase::setup(bool enableTrace, const ExceptionBase* nested)
{
if (nested) {
m_nested = nested->clone();
}
if (stackEnabled && enableTrace) {
st = ::Backtrace::trace();
if (st) {
std::vector<Backtrace::StackFrame>& frames = st->getFrames();
if (frames.size() > SKIP_FRAMES) {
rotate(frames.begin(), frames.begin()+SKIP_FRAMES, frames.end());
frames.resize(frames.size()-SKIP_FRAMES);
} else {
frames.resize(0);
}
}
}
}
Exception::Exception(const Exception& that) :
ExceptionBase(that)
{ }
void stacktraceEnabled(bool enable) {
stackEnabled = enable;
}
}
<commit_msg>Aqui não compilava<commit_after>#include "Exception.h"
#include "BackTrace.h"
#include "Demangling.h"
#include "StackAddressLoader.h"
#include "DebugSymbolLoader.h"
#include <algorithm>
#include <cstddef>
#include <exception>
#include <fstream>
#include <iterator>
#include <limits>
#include <memory>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <typeinfo>
using namespace std;
static bool initialized = false;
#if __GNUC__
#include <cxxabi.h>
struct padding {
void* ptr;
};
static const int MAX_FRAMES = 16;
static const int INTERCEPT_SKIP = 1;
struct frames {
typedef void (*destructor)(void*);
int size;
Backtrace::StackFrame* frms;
destructor dtor;
union {
char buffer[sizeof(Backtrace::StackFrame)*MAX_FRAMES];
padding p;
};
};
static __thread frames localFrames = { 0 , 0, 0, {{0}}};
namespace {
void create_frames()
{
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms != addr) {
// só um acaso muito grande ia fazer o ponteiro apontar exatamente para o lugar certo.
localFrames.size = 0;
localFrames.frms = addr;
for (int i = 0; i < MAX_FRAMES; ++i) {
new(addr + i) Backtrace::StackFrame();
}
}
}
void destroy_frames(void *thrown_exception)
{
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms == addr) {
for (int i = 0; i < MAX_FRAMES; ++i) {
addr[i].~StackFrame();
}
localFrames.dtor(thrown_exception);
}
localFrames.size = -1;
localFrames.frms = NULL;
localFrames.dtor = NULL;
}
}
namespace ExceptionLib {
const Backtrace::StackFrame* getBT(const std::exception& ex, size_t* depth, bool loadDebugSyms)
{
const ExceptionBase* base = dynamic_cast<const ExceptionBase*>(&ex);
if (base) {
if (base->stacktrace()) {
if (loadDebugSyms) {
base->stacktrace()->loadDebug();
}
if (depth) *depth = base->stacktrace()->getFrames().size();
if (*depth > 0) {
return &base->stacktrace()->getFrames()[0];
}
}
} else {
Backtrace::StackFrame* addr = reinterpret_cast<Backtrace::StackFrame*>(localFrames.buffer);
if (localFrames.frms != addr) {
if (depth) *depth = 0;
return NULL;
}
if (depth) *depth = localFrames.size - INTERCEPT_SKIP;
if (*depth > 0) {
if (loadDebugSyms) {
Backtrace::getPlatformDebugSymbolLoader().findDebugInfo(localFrames.frms, localFrames.size);
}
return localFrames.frms+INTERCEPT_SKIP;
}
}
return NULL;
}
}
extern "C" void * __cxa_allocate_exception(size_t size);
extern "C" void __cxa_free_exception(void *thrown_exception);
namespace {
bool find_base(const abi::__class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset);
bool recursive_find_base(const abi::__vmi_class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
for (size_t i = 0; i < actual->__base_count; ++i) {
const abi::__class_type_info* base = actual->__base_info[i].__base_type;
if (*base == *target) {
if (offset) *offset += actual->__base_info[i].__offset();
return true;
}
int _offset = 0;
if (find_base(base, target, offset)) {
if (offset) *offset += actual->__base_info[i].__offset() + _offset;
return true;
}
}
return false;
}
bool recursive_find_base(const abi::__si_class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
if (*actual->__base_type == *target) {
return true;
}
return find_base(actual->__base_type, target, offset);
}
bool find_base(const abi::__class_type_info* actual, const abi::__class_type_info* target, ptrdiff_t* offset)
{
if (offset) *offset = 0;
if (*actual == *target) {
return true;
}
const abi::__vmi_class_type_info* vmactual = dynamic_cast<const abi::__vmi_class_type_info*>(actual);
if (vmactual) {
return recursive_find_base(vmactual, target, offset);
}
const abi::__si_class_type_info* sactual = dynamic_cast<const abi::__si_class_type_info*>(actual);
if (sactual) {
return recursive_find_base(sactual, target, offset);
}
return false;
}
}
extern "C" void __real___cxa_throw( void* thrown_exception,
const std::type_info* tinfo, void ( *dest )( void* ) )
__attribute__(( noreturn ));
extern "C" void __wrap___cxa_throw( void* thrown_exception,
const std::type_info* tinfo, void ( *dest )( void* ) )
{
const abi::__class_type_info* cinfo = dynamic_cast<const abi::__class_type_info*>(tinfo);
if (cinfo != NULL) {
const abi::__class_type_info& exclass = dynamic_cast<const abi::__class_type_info&>(typeid(ExceptionLib::ExceptionBase));
if ( find_base(cinfo, &exclass, NULL)) {
__real___cxa_throw( thrown_exception, tinfo, dest );
return;
}
const abi::__class_type_info& stdexclass = dynamic_cast<const abi::__class_type_info&>(typeid(std::exception));
if ( find_base(cinfo, &stdexclass, NULL)) {
create_frames();
localFrames.size = Backtrace::getPlatformStackLoader().getStack(MAX_FRAMES, localFrames.frms);
localFrames.dtor = dest;
__real___cxa_throw( thrown_exception, tinfo, destroy_frames );
return;
}
}
__real___cxa_throw( thrown_exception, tinfo, dest );
}
#else
namespace ExceptionLib {
const Backtrace::StackFrame* getBT(const std::exception&, size_t* depth, bool)
{
if (depth) * depth = 0;
return NULL;
}
}
#endif
namespace ExceptionLib {
static const size_t SKIP_FRAMES = 4;
static bool stackEnabled = true;
void terminate_handler()
{
#ifdef __GNUC__
static bool tried_throw = false;
try {
if (!tried_throw) {
tried_throw = true;
throw;
}
cerr << "no active exception" << endl;
}
catch (const ExceptionLib::Exception& ex) {
cerr << "Caught an Exception: what: " << ex.what() << endl;
Backtrace::StackTrace* trace = ex.stacktrace();
if (trace) {
cerr << "stacktrace: " << endl << trace->asString() << endl;
} else {
cerr << "stacktrace: not available" << endl;
}
const ExceptionBase * eptr = &ex;
while(eptr->nested()) {
eptr = eptr->nested();
cerr << "Nested exception: what: " << eptr->what() << endl;
trace = eptr->stacktrace();
cerr << "stacktrace: " << endl << trace << endl;
}
}
catch (const std::exception &ex) {
cout << "Caught an std::exception. what(): " << ex.what() << endl;
}
catch (...) {
std::cout << "Caught unknown exception" << std::endl;
}
#else
cerr << "Caught unhandled exception" << endl;
#endif
}
void init(char *argv0)
{
::Backtrace::initialize(argv0);
set_terminate(terminate_handler);
initialized = true;
}
ExceptionBase::ExceptionBase(const ExceptionBase& that)
: BaseExceptionType()
, m_raiser(that.m_raiser)
, m_cloner(that.m_cloner)
, st(NULL)
, m_what(that.m_what)
, m_nested(NULL)
{
if (that.m_nested) {
m_nested = that.m_nested->clone();
}
if (that.st) {
st = that.st;
st->increaseCount();
}
}
ExceptionBase::~ExceptionBase() throw ()
{
try {
if (m_nested) {
delete m_nested;
}
if (st) st->decreaseCount();
st = NULL;
} catch (...) {}
}
void ExceptionBase::raise() const
{
m_raiser(this);
}
ExceptionBase* ExceptionBase::clone() const
{
return m_cloner(this);
}
const char* ExceptionBase::what() const throw()
{
return m_what.c_str();
}
const ExceptionBase* ExceptionBase::nested() const
{
return m_nested;
}
Backtrace::StackTrace* ExceptionBase::stacktrace() const
{
if (st) {
return st;
} else {
return NULL;
}
}
void NOINLINE ExceptionBase::setup(bool enableTrace, const ExceptionBase* nested)
{
if (nested) {
m_nested = nested->clone();
}
if (stackEnabled && enableTrace) {
st = ::Backtrace::trace();
if (st) {
std::vector<Backtrace::StackFrame>& frames = st->getFrames();
if (frames.size() > SKIP_FRAMES) {
rotate(frames.begin(), frames.begin()+SKIP_FRAMES, frames.end());
frames.resize(frames.size()-SKIP_FRAMES);
} else {
frames.resize(0);
}
}
}
}
Exception::Exception(const Exception& that) :
ExceptionBase(that)
{ }
void stacktraceEnabled(bool enable) {
stackEnabled = enable;
}
}
<|endoftext|>
|
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Warsaw.hh"
#include <iomanip>
/*
* sorry, quick hack...
* we need to set up libraries correctly...
*/
#include "../Berlin/Math.hh"
ostream &operator << (ostream &os, Graphic::Requirement &r)
{
if (!r.defined) os << "undef";
else
{
double tol = 1e-2;
os << setiosflags(ios::fixed);
if (Math::equal(r.natural, r.minimum, tol))
{
if (Math::equal(r.natural, r.maximum, tol))
os << setprecision(2) << r.natural;
else
os << '(' << setprecision(2) << r.natural
<< ',' << setprecision(2) << r.maximum << ')';
}
else if (Math::equal(r.natural, r.maximum, tol))
os << '(' << setprecision(2) << r.minimum
<< ',' << setprecision(2) << r.natural << ')';
else
os << '(' << setprecision(2) << r.minimum
<< ',' << setprecision(2) << r.natural
<< ',' << setprecision(2) << r.maximum << ')';
if (!Math::equal(r.align, 0., tol))
os << " @ " << setprecision(1) << r.align;
}
return os;
};
ostream &operator << (ostream &os, const Graphic::Requisition &r)
{
return os << r.x << ", " << r.y << ", " << r.z;
}
ostream &operator << (ostream &os, const Region::Allotment &a)
{
os << setiosflags(ios::fixed) << setprecision(2) << a.begin << ',' << setprecision(2) << a.end;
if (!Math::equal(a.align, 0., 1e-2)) cout << " @ " << setprecision(1) << a.align;
return os;
}
ostream &operator << (ostream &os, Region_ptr r)
{
Region::Allotment a;
os << "X(";
r->span(xaxis, a);
os << a << "), Y(";
r->span(yaxis, a);
os << a << "), Z(";
r->span(zaxis, a);
os << a << ')';
return os;
}
<commit_msg>*** empty log message ***<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Warsaw.hh"
#include <iomanip>
/*
* sorry, quick hack...
* we need to set up libraries correctly...
*/
#include "../Berlin/Math.hh"
ostream &operator << (ostream &os, const Graphic::Requirement &r)
{
if (!r.defined) os << "undef";
else
{
double tol = 1e-2;
os << setiosflags(ios::fixed);
if (Math::equal(r.natural, r.minimum, tol))
{
if (Math::equal(r.natural, r.maximum, tol))
os << setprecision(2) << r.natural;
else
os << '(' << setprecision(2) << r.natural
<< ',' << setprecision(2) << r.maximum << ')';
}
else if (Math::equal(r.natural, r.maximum, tol))
os << '(' << setprecision(2) << r.minimum
<< ',' << setprecision(2) << r.natural << ')';
else
os << '(' << setprecision(2) << r.minimum
<< ',' << setprecision(2) << r.natural
<< ',' << setprecision(2) << r.maximum << ')';
if (!Math::equal(r.align, 0., tol))
os << " @ " << setprecision(1) << r.align;
}
return os;
};
ostream &operator << (ostream &os, const Graphic::Requisition &r)
{
return os << r.x << ", " << r.y << ", " << r.z;
}
ostream &operator << (ostream &os, const Region::Allotment &a)
{
os << setiosflags(ios::fixed) << setprecision(2) << a.begin << ',' << setprecision(2) << a.end;
if (!Math::equal(a.align, 0., 1e-2)) cout << " @ " << setprecision(1) << a.align;
return os;
}
ostream &operator << (ostream &os, Region_ptr r)
{
Region::Allotment a;
os << "X(";
r->span(xaxis, a);
os << a << "), Y(";
r->span(yaxis, a);
os << a << "), Z(";
r->span(zaxis, a);
os << a << ')';
return os;
}
<|endoftext|>
|
<commit_before>#ifndef CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#define CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#include "arch/timing.hpp"
#include "clustering/generic/multi_throttling_metadata.hpp"
#include "clustering/generic/registrar.hpp"
#include "rpc/mailbox/typed.hpp"
template <class request_type, class inner_client_business_card_type, class user_data_type, class registrant_type>
class multi_throttling_server_t :
private repeating_timer_callback_t {
private:
typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::server_business_card_t server_business_card_t;
typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::client_business_card_t client_business_card_t;
public:
multi_throttling_server_t(
mailbox_manager_t *mm,
user_data_type ud,
int capacity) :
mailbox_manager(mm),
user_data(ud),
total_tickets(capacity), free_tickets(capacity),
reallocate_timer(reallocate_interval_ms, this),
registrar(mailbox_manager, this)
{ }
multi_throttling_business_card_t<request_type, inner_client_business_card_type> get_business_card() {
return multi_throttling_business_card_t<request_type, inner_client_business_card_type>(
registrar.get_business_card()
);
}
private:
static const int reallocate_interval_ms = 1000;
class client_t :
public intrusive_list_node_t<client_t>,
private repeating_timer_callback_t {
public:
client_t(multi_throttling_server_t *p,
const client_business_card_t &client_bc) :
parent(p),
target_tickets(0), held_tickets(0), in_use_tickets(0),
time_of_last_qps_sample(get_ticks()),
requests_since_last_qps_sample(0),
running_qps_estimate(0),
qps_sample_timer(reallocate_interval_ms, this),
give_tickets_addr(client_bc.give_tickets_addr),
reclaim_tickets_addr(client_bc.reclaim_tickets_addr),
registrant(p->user_data, client_bc.inner_client_business_card),
drainer(new auto_drainer_t),
request_mailbox(new mailbox_t<void(request_type)>(parent->mailbox_manager,
boost::bind(&client_t::on_request, this, _1),
mailbox_callback_mode_inline)),
relinquish_tickets_mailbox(new mailbox_t<void(int)>(parent->mailbox_manager,
boost::bind(&client_t::on_relinquish_tickets, this, _1),
mailbox_callback_mode_inline))
{
send(parent->mailbox_manager, client_bc.intro_addr,
server_business_card_t(
request_mailbox->get_address(),
relinquish_tickets_mailbox->get_address()
)
);
parent->clients.push_back(this);
parent->recompute_allocations();
}
~client_t() {
request_mailbox.reset();
relinquish_tickets_mailbox.reset();
drainer.reset();
parent->clients.remove(this);
rassert(in_use_tickets == 0);
parent->return_tickets(held_tickets);
parent->recompute_allocations();
}
void give_tickets(int tickets) {
ASSERT_FINITE_CORO_WAITING;
held_tickets += tickets;
coro_t::spawn_sometime(boost::bind(
&client_t::give_tickets_blocking, this,
tickets,
auto_drainer_t::lock_t(drainer.get())
));
}
void set_target_tickets(int new_target) {
if (target_tickets > new_target) {
coro_t::spawn_sometime(boost::bind(
&client_t::reclaim_tickets_blocking, this,
target_tickets - new_target,
auto_drainer_t::lock_t(drainer.get())
));
}
target_tickets = new_target;
}
int get_target_tickets() {
return target_tickets;
}
int get_current_tickets() {
return held_tickets + in_use_tickets;
}
int estimate_qps() {
ticks_t time_span = get_ticks() - time_of_last_qps_sample;
return running_qps_estimate / 2 +
requests_since_last_qps_sample * secs_to_ticks(1) / time_span;
}
private:
void on_request(const request_type &request) {
rassert(held_tickets > 0);
held_tickets--;
in_use_tickets++;
coro_t::spawn_sometime(boost::bind(
&client_t::perform_request, this,
request,
auto_drainer_t::lock_t(drainer.get())
));
}
void perform_request(const request_type &request, auto_drainer_t::lock_t keepalive) {
requests_since_last_qps_sample++;
try {
registrant.perform_request(request, keepalive.get_drain_signal());
} catch (interrupted_exc_t) {
/* ignore */
}
in_use_tickets--;
parent->return_tickets(1);
}
void on_relinquish_tickets(int tickets) {
held_tickets -= tickets;
parent->return_tickets(tickets);
}
void give_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
send(parent->mailbox_manager, give_tickets_addr, tickets);
}
void reclaim_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
send(parent->mailbox_manager, reclaim_tickets_addr, tickets);
}
void on_ring() {
/* Take a sample of the recent average QPS */
running_qps_estimate = estimate_qps();
time_of_last_qps_sample = get_ticks();
requests_since_last_qps_sample = 0;
}
multi_throttling_server_t *parent;
int target_tickets, held_tickets, in_use_tickets;
ticks_t time_of_last_qps_sample;
int requests_since_last_qps_sample;
int running_qps_estimate;
repeating_timer_t qps_sample_timer;
mailbox_addr_t<void(int)> give_tickets_addr;
mailbox_addr_t<void(int)> reclaim_tickets_addr;
registrant_type registrant;
scoped_ptr_t<auto_drainer_t> drainer;
scoped_ptr_t<mailbox_t<void(request_type)> > request_mailbox;
scoped_ptr_t<mailbox_t<void(int)> > relinquish_tickets_mailbox;
};
void on_ring() {
recompute_allocations();
}
void recompute_allocations() {
/* We divide the total number of tickets into two pools. The first pool
is distributed evenly among all the clients. The second pool is
distributed in proportion to the clients' QPS. */
static const float fair_fraction = 0.1;
int fair_tickets = total_tickets * fair_fraction;
int qps_tickets = total_tickets - fair_tickets;
int total_qps = 0;
for (client_t *c = clients.head(); c; c = clients.next(c)) {
total_qps += c->estimate_qps();
}
if (clients.size() == 0) {
rassert(total_tickets == free_tickets);
return;
}
if (total_qps == 0) {
/* None of the clients did any queries recently. Not all of the
tickets will be distributed, but that's OK. */
total_qps = 1;
}
for (client_t *c = clients.head(); c; c = clients.next(c)) {
/* This math isn't exact, but it's OK if the target tickets of all
the clients don't add up to `total_tickets`. */
c->set_target_tickets(
fair_tickets / clients.size() +
qps_tickets * c->estimate_qps() / total_qps
);
}
redistribute_tickets();
}
void return_tickets(int tickets) {
free_tickets += tickets;
rassert(free_tickets <= total_tickets);
redistribute_tickets();
}
void redistribute_tickets() {
static const int chunk_size = 100;
static const int min_reasonable_tickets = 10;
while (free_tickets > 0) {
client_t *neediest = NULL;
int gift_size;
/* First, look for a client with a critically low number of tickets.
They get priority in tickets. This prevents starvation. */
for (client_t *c = clients.head(); c; c = clients.next(c)) {
if (c->get_current_tickets() < min_reasonable_tickets && c->get_current_tickets() < c->get_target_tickets()) {
if (!neediest || c->get_current_tickets() < neediest->get_current_tickets()) {
neediest = c;
gift_size = std::min(c->get_target_tickets() - c->get_current_tickets(), free_tickets);
}
}
}
if (!neediest && free_tickets > chunk_size) {
/* No clients are starving, so look for clients with a large
difference between their target number of tickets and their
current number of tickets. But if the difference is less than
`chunk_size`, don't send any tickets at all to avoid flooding
the network with many small ticket updates. */
for (client_t *c = clients.head(); c; c = clients.next(c)) {
int need_size = c->get_target_tickets() - c->get_current_tickets();
if (need_size > chunk_size && (!neediest || need_size > neediest->get_target_tickets() - neediest->get_current_tickets())) {
neediest = c;
gift_size = chunk_size;
}
}
}
if (!neediest) {
break;
}
free_tickets -= gift_size;
neediest->give_tickets(gift_size);
}
}
mailbox_manager_t *mailbox_manager;
user_data_type user_data;
intrusive_list_t<client_t> clients;
int total_tickets, free_tickets;
repeating_timer_t reallocate_timer;
registrar_t<client_business_card_t, multi_throttling_server_t *, client_t> registrar;
};
#endif /* CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_ */
<commit_msg>Fix race condition in multi_throttling_server_t.<commit_after>#ifndef CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#define CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_
#include "arch/timing.hpp"
#include "clustering/generic/multi_throttling_metadata.hpp"
#include "clustering/generic/registrar.hpp"
#include "rpc/mailbox/typed.hpp"
template <class request_type, class inner_client_business_card_type, class user_data_type, class registrant_type>
class multi_throttling_server_t :
private repeating_timer_callback_t {
private:
typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::server_business_card_t server_business_card_t;
typedef typename multi_throttling_business_card_t<request_type, inner_client_business_card_type>::client_business_card_t client_business_card_t;
public:
multi_throttling_server_t(
mailbox_manager_t *mm,
user_data_type ud,
int capacity) :
mailbox_manager(mm),
user_data(ud),
total_tickets(capacity), free_tickets(capacity),
reallocate_timer(reallocate_interval_ms, this),
registrar(mailbox_manager, this)
{ }
multi_throttling_business_card_t<request_type, inner_client_business_card_type> get_business_card() {
return multi_throttling_business_card_t<request_type, inner_client_business_card_type>(
registrar.get_business_card()
);
}
private:
static const int reallocate_interval_ms = 1000;
class client_t :
public intrusive_list_node_t<client_t>,
private repeating_timer_callback_t {
public:
client_t(multi_throttling_server_t *p,
const client_business_card_t &client_bc) :
parent(p),
target_tickets(0), held_tickets(0), in_use_tickets(0),
time_of_last_qps_sample(get_ticks()),
requests_since_last_qps_sample(0),
running_qps_estimate(0),
qps_sample_timer(reallocate_interval_ms, this),
give_tickets_addr(client_bc.give_tickets_addr),
reclaim_tickets_addr(client_bc.reclaim_tickets_addr),
registrant(p->user_data, client_bc.inner_client_business_card),
drainer(new auto_drainer_t),
request_mailbox(new mailbox_t<void(request_type)>(parent->mailbox_manager,
boost::bind(&client_t::on_request, this, _1),
mailbox_callback_mode_inline)),
relinquish_tickets_mailbox(new mailbox_t<void(int)>(parent->mailbox_manager,
boost::bind(&client_t::on_relinquish_tickets, this, _1),
mailbox_callback_mode_inline))
{
send(parent->mailbox_manager, client_bc.intro_addr,
server_business_card_t(
request_mailbox->get_address(),
relinquish_tickets_mailbox->get_address()
)
);
parent->clients.push_back(this);
parent->recompute_allocations();
}
~client_t() {
parent->clients.remove(this);
parent->recompute_allocations();
request_mailbox.reset();
relinquish_tickets_mailbox.reset();
drainer.reset();
rassert(in_use_tickets == 0);
parent->return_tickets(held_tickets);
}
void give_tickets(int tickets) {
ASSERT_FINITE_CORO_WAITING;
held_tickets += tickets;
coro_t::spawn_sometime(boost::bind(
&client_t::give_tickets_blocking, this,
tickets,
auto_drainer_t::lock_t(drainer.get())
));
}
void set_target_tickets(int new_target) {
if (target_tickets > new_target) {
coro_t::spawn_sometime(boost::bind(
&client_t::reclaim_tickets_blocking, this,
target_tickets - new_target,
auto_drainer_t::lock_t(drainer.get())
));
}
target_tickets = new_target;
}
int get_target_tickets() {
return target_tickets;
}
int get_current_tickets() {
return held_tickets + in_use_tickets;
}
int estimate_qps() {
ticks_t time_span = get_ticks() - time_of_last_qps_sample;
return running_qps_estimate / 2 +
requests_since_last_qps_sample * secs_to_ticks(1) / time_span;
}
private:
void on_request(const request_type &request) {
rassert(held_tickets > 0);
held_tickets--;
in_use_tickets++;
coro_t::spawn_sometime(boost::bind(
&client_t::perform_request, this,
request,
auto_drainer_t::lock_t(drainer.get())
));
}
void perform_request(const request_type &request, auto_drainer_t::lock_t keepalive) {
requests_since_last_qps_sample++;
try {
registrant.perform_request(request, keepalive.get_drain_signal());
} catch (interrupted_exc_t) {
/* ignore */
}
in_use_tickets--;
parent->return_tickets(1);
}
void on_relinquish_tickets(int tickets) {
held_tickets -= tickets;
parent->return_tickets(tickets);
}
void give_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
send(parent->mailbox_manager, give_tickets_addr, tickets);
}
void reclaim_tickets_blocking(int tickets, auto_drainer_t::lock_t) {
send(parent->mailbox_manager, reclaim_tickets_addr, tickets);
}
void on_ring() {
/* Take a sample of the recent average QPS */
running_qps_estimate = estimate_qps();
time_of_last_qps_sample = get_ticks();
requests_since_last_qps_sample = 0;
}
multi_throttling_server_t *parent;
int target_tickets, held_tickets, in_use_tickets;
ticks_t time_of_last_qps_sample;
int requests_since_last_qps_sample;
int running_qps_estimate;
repeating_timer_t qps_sample_timer;
mailbox_addr_t<void(int)> give_tickets_addr;
mailbox_addr_t<void(int)> reclaim_tickets_addr;
registrant_type registrant;
scoped_ptr_t<auto_drainer_t> drainer;
scoped_ptr_t<mailbox_t<void(request_type)> > request_mailbox;
scoped_ptr_t<mailbox_t<void(int)> > relinquish_tickets_mailbox;
};
void on_ring() {
recompute_allocations();
}
void recompute_allocations() {
/* We divide the total number of tickets into two pools. The first pool
is distributed evenly among all the clients. The second pool is
distributed in proportion to the clients' QPS. */
static const float fair_fraction = 0.1;
int fair_tickets = total_tickets * fair_fraction;
int qps_tickets = total_tickets - fair_tickets;
int total_qps = 0;
for (client_t *c = clients.head(); c; c = clients.next(c)) {
total_qps += c->estimate_qps();
}
if (clients.size() == 0) {
return;
}
if (total_qps == 0) {
/* None of the clients did any queries recently. Not all of the
tickets will be distributed, but that's OK. */
total_qps = 1;
}
for (client_t *c = clients.head(); c; c = clients.next(c)) {
/* This math isn't exact, but it's OK if the target tickets of all
the clients don't add up to `total_tickets`. */
c->set_target_tickets(
fair_tickets / clients.size() +
qps_tickets * c->estimate_qps() / total_qps
);
}
redistribute_tickets();
}
void return_tickets(int tickets) {
free_tickets += tickets;
rassert(free_tickets <= total_tickets);
redistribute_tickets();
}
void redistribute_tickets() {
static const int chunk_size = 100;
static const int min_reasonable_tickets = 10;
while (free_tickets > 0) {
client_t *neediest = NULL;
int gift_size;
/* First, look for a client with a critically low number of tickets.
They get priority in tickets. This prevents starvation. */
for (client_t *c = clients.head(); c; c = clients.next(c)) {
if (c->get_current_tickets() < min_reasonable_tickets && c->get_current_tickets() < c->get_target_tickets()) {
if (!neediest || c->get_current_tickets() < neediest->get_current_tickets()) {
neediest = c;
gift_size = std::min(c->get_target_tickets() - c->get_current_tickets(), free_tickets);
}
}
}
if (!neediest && free_tickets > chunk_size) {
/* No clients are starving, so look for clients with a large
difference between their target number of tickets and their
current number of tickets. But if the difference is less than
`chunk_size`, don't send any tickets at all to avoid flooding
the network with many small ticket updates. */
for (client_t *c = clients.head(); c; c = clients.next(c)) {
int need_size = c->get_target_tickets() - c->get_current_tickets();
if (need_size > chunk_size && (!neediest || need_size > neediest->get_target_tickets() - neediest->get_current_tickets())) {
neediest = c;
gift_size = chunk_size;
}
}
}
if (!neediest) {
break;
}
free_tickets -= gift_size;
neediest->give_tickets(gift_size);
}
}
mailbox_manager_t *mailbox_manager;
user_data_type user_data;
intrusive_list_t<client_t> clients;
int total_tickets, free_tickets;
repeating_timer_t reallocate_timer;
registrar_t<client_business_card_t, multi_throttling_server_t *, client_t> registrar;
};
#endif /* CLUSTERING_GENERIC_MULTI_THROTTLING_SERVER_HPP_ */
<|endoftext|>
|
<commit_before>/*
The MIT License(MIT)
Copyright(c) 2016 Joss Whittle
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#define MEL_IMPLEMENTATION
#include "MEL_omp.hpp"
#include <iomanip>
//-----------------------------------------------------------------//
// Example Usage: mpirun --pernode --hostfile [path] ./ompExample //
//-----------------------------------------------------------------//
int main(int argc, char *argv []) {
MEL::Init(argc, argv);
// Who are we?
MEL::Comm comm = MEL::Comm::WORLD;
const int rank = MEL::CommRank(comm),
size = MEL::CommSize(comm);
double start, end;
// Allocate buffers
const int LEN = 1e8;
int *src = MEL::MemAlloc<int>(LEN, 1), // Initilize to 1
*dst = (rank == 0) ? MEL::MemAlloc<int>(LEN) : nullptr;
// Perform the Reduction on 1 thread with MPI_SUM
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, MEL::Op::SUM, 0, comm); // Equivalent to standard MPI_Reduce call
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 1 thread with MEL::Op::SUM == MPI_SUM." << std::endl;
// Create a MEL User Defined Operation using a functor wrapped in a map function
auto SUM = MEL::OpCreate<int, MEL::Functor::SUM>();
// Perform the Reduction on 1 thread
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, SUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 1 thread with mapped MEL::FUNCTOR::SUM." << std::endl;
// Create a MEL User Defined Operation using a functor wrapped in a parallel map function
auto ompSUM = MEL::OMP::OpCreate<int, MEL::Functor::SUM>();
omp_set_num_threads(2);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 4 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 2 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(4);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 8 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 4 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(8);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 8 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 8 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(16);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 16 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 16 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
// Clean up the operations when we are done with them
MEL::OpFree(SUM, ompSUM);
// Clean up buffers
MEL::MemFree(src, dst);
MEL::Finalize();
return 0;
}<commit_msg>formatting<commit_after>/*
The MIT License(MIT)
Copyright(c) 2016 Joss Whittle
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#define MEL_IMPLEMENTATION
#include "MEL_omp.hpp"
#include <iomanip>
//-----------------------------------------------------------------//
// Example Usage: mpirun --pernode --hostfile [path] ./ompExample //
//-----------------------------------------------------------------//
int main(int argc, char *argv []) {
MEL::Init(argc, argv);
// Who are we?
MEL::Comm comm = MEL::Comm::WORLD;
const int rank = MEL::CommRank(comm),
size = MEL::CommSize(comm);
double start, end;
// Allocate buffers
const int LEN = 1e8;
int *src = MEL::MemAlloc<int>(LEN, 1), // Initilize to 1
*dst = (rank == 0) ? MEL::MemAlloc<int>(LEN) : nullptr;
// Perform the Reduction on 1 thread with MPI_SUM
start = MEL::Wtime();
//MPI_Reduce(src, dst, LEN, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
MEL::Reduce(src, dst, LEN, MEL::Op::SUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 1 thread with MEL::Op::SUM == MPI_SUM." << std::endl;
// Create a MEL User Defined Operation using a functor wrapped in a map function
auto SUM = MEL::OpCreate<int, MEL::Functor::SUM>();
// Perform the Reduction on 1 thread
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, SUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 1 thread with mapped MEL::FUNCTOR::SUM." << std::endl;
// Create a MEL User Defined Operation using a functor wrapped in a parallel map function
auto ompSUM = MEL::OMP::OpCreate<int, MEL::Functor::SUM>();
omp_set_num_threads(2);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 4 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 2 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(4);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 8 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 4 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(8);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 8 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 8 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
omp_set_num_threads(16);
omp_set_schedule(omp_sched_static, 0);
// Perform the Reduction on 16 threads
start = MEL::Wtime();
MEL::Reduce(src, dst, LEN, ompSUM, 0, comm);
end = MEL::Wtime();
if (rank == 0)
std::cout << "Reduced " << LEN << " elements in " << std::setw(10) << (end - start)
<< " seconds on 16 threads with parallel mapped MEL::FUNCTOR::SUM." << std::endl;
// Clean up the operations when we are done with them
MEL::OpFree(SUM, ompSUM);
// Clean up buffers
MEL::MemFree(src, dst);
MEL::Finalize();
return 0;
}<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2012 Razor team
* 2014 LXQt team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QTimeZone>
#include "lxqtworldclockconfigurationtimezones.h"
#include "ui_lxqtworldclockconfigurationtimezones.h"
LXQtWorldClockConfigurationTimeZones::LXQtWorldClockConfigurationTimeZones(QWidget *parent) :
QDialog(parent),
ui(new Ui::LXQtWorldClockConfigurationTimeZones)
{
setObjectName(QStringLiteral("WorldClockConfigurationTimeZonesWindow"));
setWindowModality(Qt::WindowModal);
ui->setupUi(this);
connect(ui->timeZonesTW, SIGNAL(itemSelectionChanged()), SLOT(itemSelectionChanged()));
connect(ui->timeZonesTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), SLOT(itemDoubleClicked(QTreeWidgetItem*,int)));
}
LXQtWorldClockConfigurationTimeZones::~LXQtWorldClockConfigurationTimeZones()
{
delete ui;
}
QString LXQtWorldClockConfigurationTimeZones::timeZone()
{
return mTimeZone;
}
void LXQtWorldClockConfigurationTimeZones::itemSelectionChanged()
{
QList<QTreeWidgetItem*> items = ui->timeZonesTW->selectedItems();
if (!items.empty())
mTimeZone = items[0]->data(0, Qt::UserRole).toString();
else
mTimeZone.clear();
}
void LXQtWorldClockConfigurationTimeZones::itemDoubleClicked(QTreeWidgetItem* /*item*/, int /*column*/)
{
if (!mTimeZone.isEmpty())
accept();
}
QTreeWidgetItem* LXQtWorldClockConfigurationTimeZones::makeSureParentsExist(const QStringList &parts, QMap<QString, QTreeWidgetItem*> &parentItems)
{
if (parts.length() == 1)
return 0;
QStringList parentParts = parts.mid(0, parts.length() - 1);
QString parentPath = parentParts.join(QLatin1String("/"));
QMap<QString, QTreeWidgetItem*>::Iterator I = parentItems.find(parentPath);
if (I != parentItems.end())
return I.value();
QTreeWidgetItem* newItem = new QTreeWidgetItem(QStringList() << parts[parts.length() - 2]);
QTreeWidgetItem* parentItem = makeSureParentsExist(parentParts, parentItems);
if (!parentItem)
ui->timeZonesTW->addTopLevelItem(newItem);
else
parentItem->addChild(newItem);
parentItems[parentPath] = newItem;
return newItem;
}
int LXQtWorldClockConfigurationTimeZones::updateAndExec()
{
QDateTime now = QDateTime::currentDateTime();
ui->timeZonesTW->clear();
QMap<QString, QTreeWidgetItem*> parentItems;
const auto timeZones = QTimeZone::availableTimeZoneIds();
for(const QByteArray &ba : timeZones)
{
QTimeZone timeZone(ba);
QString ianaId(ba);
QStringList qStrings(QString(ba).split(QLatin1Char('/')));
if ((qStrings.size() == 1) && (qStrings[0].startsWith(QLatin1String("UTC"))))
qStrings.prepend(tr("UTC"));
if (qStrings.size() == 1)
qStrings.prepend(tr("Other"));
QTreeWidgetItem *tzItem = new QTreeWidgetItem(QStringList() << qStrings[qStrings.length() - 1] << timeZone.displayName(now) << timeZone.comment() << QLocale::countryToString(timeZone.country()));
tzItem->setData(0, Qt::UserRole, ianaId);
makeSureParentsExist(qStrings, parentItems)->addChild(tzItem);
}
QStringList qStrings = QStringList() << tr("Other") << QLatin1String("local");
QTreeWidgetItem *tzItem = new QTreeWidgetItem(QStringList() << qStrings[qStrings.length() - 1] << QString() << tr("Local timezone") << QString());
tzItem->setData(0, Qt::UserRole, qStrings[qStrings.length() - 1]);
makeSureParentsExist(qStrings, parentItems)->addChild(tzItem);
ui->timeZonesTW->sortByColumn(0, Qt::AscendingOrder);
return exec();
}
<commit_msg>plugin-worldclock: Don't use automatic string conversion<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2012 Razor team
* 2014 LXQt team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QTimeZone>
#include "lxqtworldclockconfigurationtimezones.h"
#include "ui_lxqtworldclockconfigurationtimezones.h"
LXQtWorldClockConfigurationTimeZones::LXQtWorldClockConfigurationTimeZones(QWidget *parent) :
QDialog(parent),
ui(new Ui::LXQtWorldClockConfigurationTimeZones)
{
setObjectName(QStringLiteral("WorldClockConfigurationTimeZonesWindow"));
setWindowModality(Qt::WindowModal);
ui->setupUi(this);
connect(ui->timeZonesTW, SIGNAL(itemSelectionChanged()), SLOT(itemSelectionChanged()));
connect(ui->timeZonesTW, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), SLOT(itemDoubleClicked(QTreeWidgetItem*,int)));
}
LXQtWorldClockConfigurationTimeZones::~LXQtWorldClockConfigurationTimeZones()
{
delete ui;
}
QString LXQtWorldClockConfigurationTimeZones::timeZone()
{
return mTimeZone;
}
void LXQtWorldClockConfigurationTimeZones::itemSelectionChanged()
{
QList<QTreeWidgetItem*> items = ui->timeZonesTW->selectedItems();
if (!items.empty())
mTimeZone = items[0]->data(0, Qt::UserRole).toString();
else
mTimeZone.clear();
}
void LXQtWorldClockConfigurationTimeZones::itemDoubleClicked(QTreeWidgetItem* /*item*/, int /*column*/)
{
if (!mTimeZone.isEmpty())
accept();
}
QTreeWidgetItem* LXQtWorldClockConfigurationTimeZones::makeSureParentsExist(const QStringList &parts, QMap<QString, QTreeWidgetItem*> &parentItems)
{
if (parts.length() == 1)
return 0;
QStringList parentParts = parts.mid(0, parts.length() - 1);
QString parentPath = parentParts.join(QLatin1String("/"));
QMap<QString, QTreeWidgetItem*>::Iterator I = parentItems.find(parentPath);
if (I != parentItems.end())
return I.value();
QTreeWidgetItem* newItem = new QTreeWidgetItem(QStringList() << parts[parts.length() - 2]);
QTreeWidgetItem* parentItem = makeSureParentsExist(parentParts, parentItems);
if (!parentItem)
ui->timeZonesTW->addTopLevelItem(newItem);
else
parentItem->addChild(newItem);
parentItems[parentPath] = newItem;
return newItem;
}
int LXQtWorldClockConfigurationTimeZones::updateAndExec()
{
QDateTime now = QDateTime::currentDateTime();
ui->timeZonesTW->clear();
QMap<QString, QTreeWidgetItem*> parentItems;
const auto timeZones = QTimeZone::availableTimeZoneIds();
for(const QByteArray &ba : timeZones)
{
QTimeZone timeZone(ba);
QString ianaId(QString::fromUtf8(ba));
QStringList qStrings(QString::fromUtf8((ba)).split(QLatin1Char('/')));
if ((qStrings.size() == 1) && (qStrings[0].startsWith(QLatin1String("UTC"))))
qStrings.prepend(tr("UTC"));
if (qStrings.size() == 1)
qStrings.prepend(tr("Other"));
QTreeWidgetItem *tzItem = new QTreeWidgetItem(QStringList() << qStrings[qStrings.length() - 1] << timeZone.displayName(now) << timeZone.comment() << QLocale::countryToString(timeZone.country()));
tzItem->setData(0, Qt::UserRole, ianaId);
makeSureParentsExist(qStrings, parentItems)->addChild(tzItem);
}
QStringList qStrings = QStringList() << tr("Other") << QLatin1String("local");
QTreeWidgetItem *tzItem = new QTreeWidgetItem(QStringList() << qStrings[qStrings.length() - 1] << QString() << tr("Local timezone") << QString());
tzItem->setData(0, Qt::UserRole, qStrings[qStrings.length() - 1]);
makeSureParentsExist(qStrings, parentItems)->addChild(tzItem);
ui->timeZonesTW->sortByColumn(0, Qt::AscendingOrder);
return exec();
}
<|endoftext|>
|
<commit_before>
#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#include "math.h"
/*
IMPLEMENTATION OF THE NMR2 FUNCTION IN TIRAMISU
out =
where :
A : is a NxM matrix
x : is a size N vector
y : is a size M vector ( y**T : transpose of y)
a : scalar
THE C CODE OF THIS FUNCTION IS AS FOLLOW :
for(int i=0; i<N:i++){
for(int j=0; j<M; j++){
A[i,j] += a*x[i]*y[j];
}
}
*/
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("nrm2");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant NN("N", expr(N));
var i("i", 0, NN);
input x("x", {"i"}, {NN},p_float64);
computation S_init("S_init", {}, expr(cast(p_float64,0)));
computation S("S", {i},p_float64);
S.set_expression( S(i-1) + x(i)*x(i));
computation result("result", {},p_float64);
result.set_expression(cast(p_float64,expr(o_sqrt,S(NN),p_float64)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
S.after(S_init,{}); //
result.after(S,computation::root); //
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_x("b_x", {expr(NN)}, p_float64, a_input);
buffer b_result("b_result", {expr(1)}, p_float64, a_output);
x.store_in(&b_x);
S_init.store_in(&b_result,{});
S.store_in(&b_result,{});
result.store_in(&b_result,{});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_x,&b_result}, "generated_nrm2.o");
return 0;
}
<commit_msg>Update nrm2_generator.cpp<commit_after>
#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#include "math.h"
/*
IMPLEMENTATION OF THE NMR2 FUNCTION IN TIRAMISU
out = sqrt(x*'x)
where :
x : is a size N vector and 'x is the transpose of x
*/
using namespace tiramisu;
int main(int argc, char **argv)
{
tiramisu::init("nrm2");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
constant NN("N", expr(N));
var i("i", 0, NN);
input x("x", {"i"}, {NN},p_float64);
computation S_init("S_init", {}, expr(cast(p_float64,0)));
computation S("S", {i},p_float64);
S.set_expression( S(i-1) + x(i)*x(i));
computation result("result", {},p_float64);
result.set_expression(cast(p_float64,expr(o_sqrt,S(NN),p_float64)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
S.after(S_init,{}); //
result.after(S,computation::root); //
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
buffer b_x("b_x", {expr(NN)}, p_float64, a_input);
buffer b_result("b_result", {expr(1)}, p_float64, a_output);
x.store_in(&b_x);
S_init.store_in(&b_result,{});
S.store_in(&b_result,{});
result.store_in(&b_result,{});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
tiramisu::codegen({&b_x,&b_result}, "generated_nrm2.o");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "tonicindianartmusic.h"
#include "essentiamath.h"
using namespace std;
namespace essentia {
namespace standard {
const char* TonicIndianArtMusic::name = "TonicIndianArtMusic";
const char* TonicIndianArtMusic::category = "Tonal";
const char* TonicIndianArtMusic::description = DOC("This algorithm estimates the tonic frequency of the lead artist in Indian art music. It uses multipitch representation of the audio signal (pitch salience) to compute a histogram using which the tonic is identified as one of its peak. The decision is made based on the distance between the prominent peaks, the classification is done using a decision tree.\n"
"\n"
"References:\n"
" [1] J. Salamon, S. Gulati, and X. Serra, \"A Multipitch Approach to Tonic\n"
" Identification in Indian Classical Music,\" in International Society for\n"
" Music Information Retrieval Conference (ISMIR’12), 2012.");
void TonicIndianArtMusic::configure() {
Real sampleRate = parameter("sampleRate").toReal();
int frameSize = parameter("frameSize").toInt();
int hopSize = parameter("hopSize").toInt();
string windowType = "hann";
int zeroPaddingFactor = 4;
int maxSpectralPeaks = 100;
int numberHarmonics = parameter("numberHarmonics").toInt();
Real harmonicWeight = parameter("harmonicWeight").toReal();
Real magnitudeThreshold = parameter("magnitudeThreshold").toReal();
Real magnitudeCompression = parameter("magnitudeCompression").toReal();
_minTonicFrequency = parameter("minTonicFrequency").toReal();
_maxTonicFrequency = parameter("maxTonicFrequency").toReal();
_referenceFrequency = parameter("referenceFrequency").toReal();
_binResolution = parameter("binResolution").toReal();
_numberSaliencePeaks = parameter("numberSaliencePeaks").toReal();
_numberBins = floor(6000.0 / _binResolution) - 1;
// Pre-processing
_frameCutter->configure("frameSize", frameSize,
"hopSize", hopSize);
_windowing->configure("size", frameSize,
"zeroPadding", (zeroPaddingFactor-1) * frameSize,
"type", windowType);
// Spectral peaks
_spectrum->configure("size", frameSize * zeroPaddingFactor);
// TODO which value to select for maxFrequency? frequencies up to 1.76kHz * numHarmonics will
// theoretically affect the salience function computation
_spectralPeaks->configure(
"minFrequency", 55, // to avoid zero frequencies
"maxFrequency", 7200,
"maxPeaks", maxSpectralPeaks,
"sampleRate", sampleRate,
"magnitudeThreshold", .001,
"orderBy", "magnitude");
// Pitch salience contours
_pitchSalienceFunction->configure("binResolution", _binResolution,
"referenceFrequency", _referenceFrequency,
"magnitudeThreshold", magnitudeThreshold,
"magnitudeCompression", magnitudeCompression,
"numberHarmonics", numberHarmonics,
"harmonicWeight", harmonicWeight);
_pitchSalienceFunctionPeaks->configure("binResolution", _binResolution,
"minFrequency", _referenceFrequency*1.4909,
"maxFrequency", _referenceFrequency*10.0909,
"referenceFrequency", _referenceFrequency);
}
void TonicIndianArtMusic::compute() {
const vector<Real>& signal = _signal.get();
Real& tonic = _tonic.get();
// Pre-processing
vector<Real> frame;
_frameCutter->input("signal").set(signal);
_frameCutter->output("frame").set(frame);
vector<Real> frameWindowed;
_windowing->input("frame").set(frame);
_windowing->output("frame").set(frameWindowed);
// Spectral peaks
vector<Real> frameSpectrum;
_spectrum->input("frame").set(frameWindowed);
_spectrum->output("spectrum").set(frameSpectrum);
vector<Real> frameFrequencies;
vector<Real> frameMagnitudes;
_spectralPeaks->input("spectrum").set(frameSpectrum);
_spectralPeaks->output("frequencies").set(frameFrequencies);
_spectralPeaks->output("magnitudes").set(frameMagnitudes);
// Pitch salience contours
vector<Real> frameSalience;
_pitchSalienceFunction->input("frequencies").set(frameFrequencies);
_pitchSalienceFunction->input("magnitudes").set(frameMagnitudes);
_pitchSalienceFunction->output("salienceFunction").set(frameSalience);
vector<Real> frameSalienceBins;
vector<Real> frameSalienceValues;
_pitchSalienceFunctionPeaks->input("salienceFunction").set(frameSalience);
_pitchSalienceFunctionPeaks->output("salienceBins").set(frameSalienceBins);
_pitchSalienceFunctionPeaks->output("salienceValues").set(frameSalienceValues);
// histogram computation
vector<Real> histogram;
histogram.resize(_numberBins);
while (true) {
// get a frame
_frameCutter->compute();
if (!frame.size()) {
break;
}
_windowing->compute();
// calculate spectrum
_spectrum->compute();
// calculate spectral peaks
_spectralPeaks->compute();
// calculate salience function
_pitchSalienceFunction->compute();
// calculate peaks of salience function
_pitchSalienceFunctionPeaks->compute();
// consider only those frames where the number of peaks detected are more than minimum peaks needed for histogram
if(frameSalienceBins.size()>=_numberSaliencePeaks){
for (size_t i=0; i<_numberSaliencePeaks; i++) {
histogram[frameSalienceBins[i]]+=1;
}
}
}
// computing the peaks of the histogram function
vector <Real> peak_locs;
vector <Real> peak_amps;
Real tonic_loc;
Real binsInOctave = 1200.0 / _binResolution;
Real minBin = max(0.0, floor(binsInOctave * log2(_minTonicFrequency/_referenceFrequency) + 0.5));
Real maxBin = max(0.0, floor(binsInOctave * log2(_maxTonicFrequency/_referenceFrequency) + 0.5));
// configure algorithms [#5 peaks]
_peakDetection->configure("interpolate", false);
_peakDetection->configure("range", _numberBins);
_peakDetection->configure("maxPosition", maxBin);
_peakDetection->configure("minPosition",minBin);
_peakDetection->configure("maxPeaks", 5);
_peakDetection->configure("orderBy", "amplitude");
// find salience function peaks
_peakDetection->input("array").set(histogram);
_peakDetection->output("positions").set(peak_locs);
_peakDetection->output("amplitudes").set(peak_amps);
_peakDetection->compute();
// this is the decision tree hardcoded to choose the peak in the histogram which corresponds o the tonic
/*implementing the decision tree*/
Real highest_peak_loc = peak_locs[0];
Real f2 =peak_locs[1] - highest_peak_loc;
Real f3 =peak_locs[2] - highest_peak_loc;
Real f5 =peak_locs[4] - highest_peak_loc;
if (f2>50){
tonic_loc = peak_locs[0];
}
else{
if(f2<=-70){
if(f3<=50){
tonic_loc = peak_locs[1];
}
else{
tonic_loc = peak_locs[0];
}
}
else{
if(f3<=-60){
tonic_loc = peak_locs[2];
}
else{
if(f5<=-80){
tonic_loc = peak_locs[4];
}
else{
if(f5<=30){
if(f2<=20){
tonic_loc = peak_locs[1];
}
else{
tonic_loc = peak_locs[3];
}
}
else{
tonic_loc = peak_locs[0];
}
}
}
}
}
//converting value of the tonic in cent to Hz scale
Real _centToHertzBase = pow(2, _binResolution / 1200.0);
tonic = _referenceFrequency * pow(_centToHertzBase, tonic_loc);
}
TonicIndianArtMusic::~TonicIndianArtMusic() {
// Pre-processing
delete _frameCutter;
delete _windowing;
// Spectral peaks
delete _spectrum;
delete _spectralPeaks;
// Pitch salience contours
delete _pitchSalienceFunction;
delete _pitchSalienceFunctionPeaks;
}
} // namespace standard
} // namespace essentia
<commit_msg>minoxr fix in CPP file<commit_after>/*
* Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), 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 Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "tonicindianartmusic.h"
#include "essentiamath.h"
using namespace std;
namespace essentia {
namespace standard {
const char* TonicIndianArtMusic::name = "TonicIndianArtMusic";
const char* TonicIndianArtMusic::category = "Tonal";
const char* TonicIndianArtMusic::description = DOC("This algorithm estimates the tonic frequency of the lead artist in Indian art music. It uses multipitch representation of the audio signal (pitch salience) to compute a histogram using which the tonic is identified as one of its peak. The decision is made based on the distance between the prominent peaks, the classification is done using a decision tree.\n"
"\n"
"References:\n"
" [1] J. Salamon, S. Gulati, and X. Serra, \"A Multipitch Approach to Tonic\n"
" Identification in Indian Classical Music,\" in International Society for\n"
" Music Information Retrieval Conference (ISMIR’12), 2012.");
void TonicIndianArtMusic::configure() {
Real sampleRate = parameter("sampleRate").toReal();
int frameSize = parameter("frameSize").toInt();
int hopSize = parameter("hopSize").toInt();
string windowType = "hann";
int zeroPaddingFactor = 4;
int maxSpectralPeaks = 100;
int numberHarmonics = parameter("numberHarmonics").toInt();
Real harmonicWeight = parameter("harmonicWeight").toReal();
Real magnitudeThreshold = parameter("magnitudeThreshold").toReal();
Real magnitudeCompression = parameter("magnitudeCompression").toReal();
_minTonicFrequency = parameter("minTonicFrequency").toReal();
_maxTonicFrequency = parameter("maxTonicFrequency").toReal();
_referenceFrequency = parameter("referenceFrequency").toReal();
_binResolution = parameter("binResolution").toReal();
_numberSaliencePeaks = parameter("numberSaliencePeaks").toReal();
_numberBins = floor(6000.0 / _binResolution) - 1;
// Pre-processing
_frameCutter->configure("frameSize", frameSize,
"hopSize", hopSize);
_windowing->configure("size", frameSize,
"zeroPadding", (zeroPaddingFactor-1) * frameSize,
"type", windowType);
// Spectral peaks
_spectrum->configure("size", frameSize * zeroPaddingFactor);
// TODO which value to select for maxFrequency? frequencies up to 1.76kHz * numHarmonics will
// theoretically affect the salience function computation
_spectralPeaks->configure(
"minFrequency", 55, // to avoid zero frequencies
"maxFrequency", 7200,
"maxPeaks", maxSpectralPeaks,
"sampleRate", sampleRate,
"magnitudeThreshold", .001,
"orderBy", "magnitude");
// Pitch salience contours
_pitchSalienceFunction->configure("binResolution", _binResolution,
"referenceFrequency", _referenceFrequency,
"magnitudeThreshold", magnitudeThreshold,
"magnitudeCompression", magnitudeCompression,
"numberHarmonics", numberHarmonics,
"harmonicWeight", harmonicWeight);
_pitchSalienceFunctionPeaks->configure("binResolution", _binResolution,
"minFrequency", _referenceFrequency*1.4909,
"maxFrequency", _referenceFrequency*10.0909,
"referenceFrequency", _referenceFrequency);
}
void TonicIndianArtMusic::compute() {
printf("DBG0");
std::cout<< "DEBUGGING"<< std::endl;
const vector<Real>& signal = _signal.get();
Real& tonic = _tonic.get();
printf("DBG1");
// Prevent segmentation fault
if (signal.size() == 0) {
throw EssentiaException("TonicIndianArtMusic: Empty Audio passed");
}
printf("DBG2");
// Pre-processing
vector<Real> frame;
_frameCutter->input("signal").set(signal);
_frameCutter->output("frame").set(frame);
vector<Real> frameWindowed;
_windowing->input("frame").set(frame);
_windowing->output("frame").set(frameWindowed);
// Spectral peaks
vector<Real> frameSpectrum;
_spectrum->input("frame").set(frameWindowed);
_spectrum->output("spectrum").set(frameSpectrum);
vector<Real> frameFrequencies;
vector<Real> frameMagnitudes;
_spectralPeaks->input("spectrum").set(frameSpectrum);
_spectralPeaks->output("frequencies").set(frameFrequencies);
_spectralPeaks->output("magnitudes").set(frameMagnitudes);
// Pitch salience contours
vector<Real> frameSalience;
_pitchSalienceFunction->input("frequencies").set(frameFrequencies);
_pitchSalienceFunction->input("magnitudes").set(frameMagnitudes);
_pitchSalienceFunction->output("salienceFunction").set(frameSalience);
vector<Real> frameSalienceBins;
vector<Real> frameSalienceValues;
_pitchSalienceFunctionPeaks->input("salienceFunction").set(frameSalience);
_pitchSalienceFunctionPeaks->output("salienceBins").set(frameSalienceBins);
_pitchSalienceFunctionPeaks->output("salienceValues").set(frameSalienceValues);
// histogram computation
vector<Real> histogram;
histogram.resize(_numberBins);
while (true) {
// get a frame
_frameCutter->compute();
if (!frame.size()) {
break;
}
_windowing->compute();
// calculate spectrum
_spectrum->compute();
// calculate spectral peaks
_spectralPeaks->compute();
// calculate salience function
_pitchSalienceFunction->compute();
// calculate peaks of salience function
_pitchSalienceFunctionPeaks->compute();
// consider only those frames where the number of peaks detected are more than minimum peaks needed for histogram
if(frameSalienceBins.size()>=_numberSaliencePeaks){
for (size_t i=0; i<_numberSaliencePeaks; i++) {
histogram[frameSalienceBins[i]]+=1;
}
}
}
// computing the peaks of the histogram function
vector <Real> peak_locs;
vector <Real> peak_amps;
Real tonic_loc;
Real binsInOctave = 1200.0 / _binResolution;
Real minBin = max(0.0, floor(binsInOctave * log2(_minTonicFrequency/_referenceFrequency) + 0.5));
Real maxBin = max(0.0, floor(binsInOctave * log2(_maxTonicFrequency/_referenceFrequency) + 0.5));
// configure algorithms [#5 peaks]
_peakDetection->configure("interpolate", false);
_peakDetection->configure("range", _numberBins);
_peakDetection->configure("maxPosition", maxBin);
_peakDetection->configure("minPosition",minBin);
_peakDetection->configure("maxPeaks", 5);
_peakDetection->configure("orderBy", "amplitude");
// find salience function peaks
_peakDetection->input("array").set(histogram);
_peakDetection->output("positions").set(peak_locs);
_peakDetection->output("amplitudes").set(peak_amps);
_peakDetection->compute();
// this is the decision tree hardcoded to choose the peak in the histogram which corresponds o the tonic
/*implementing the decision tree*/
Real highest_peak_loc = peak_locs[0];
Real f2 =peak_locs[1] - highest_peak_loc;
Real f3 =peak_locs[2] - highest_peak_loc;
Real f5 =peak_locs[4] - highest_peak_loc;
if (f2>50){
tonic_loc = peak_locs[0];
}
else{
if(f2<=-70){
if(f3<=50){
tonic_loc = peak_locs[1];
}
else{
tonic_loc = peak_locs[0];
}
}
else{
if(f3<=-60){
tonic_loc = peak_locs[2];
}
else{
if(f5<=-80){
tonic_loc = peak_locs[4];
}
else{
if(f5<=30){
if(f2<=20){
tonic_loc = peak_locs[1];
}
else{
tonic_loc = peak_locs[3];
}
}
else{
tonic_loc = peak_locs[0];
}
}
}
}
}
//converting value of the tonic in cent to Hz scale
Real _centToHertzBase = pow(2, _binResolution / 1200.0);
tonic = _referenceFrequency * pow(_centToHertzBase, tonic_loc);
}
TonicIndianArtMusic::~TonicIndianArtMusic() {
// Pre-processing
delete _frameCutter;
delete _windowing;
// Spectral peaks
delete _spectrum;
delete _spectralPeaks;
// Pitch salience contours
delete _pitchSalienceFunction;
delete _pitchSalienceFunctionPeaks;
}
} // namespace standard
} // namespace essentia
<|endoftext|>
|
<commit_before>// @(#) $Id$
// Original: AliHLTTrackMerger.cxx,v 1.12 2005/06/14 10:55:21 cvetan
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Uli Frankenfeld, maintained by *
* Matthias Richter <Matthias.Richter@ift.uib.no> *
* for The ALICE HLT Project. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/** @file AliHLTTPCTrackMerger.cxx
@author Uli Frankenfeld, maintained by Matthias Richter
@date
@brief The HLT TPC track segment merger
*/
#include "AliHLTTPCLogging.h"
#include "AliHLTTPCTrackMerger.h"
#include "AliHLTTPCTrack.h"
#include "AliHLTTPCTrackSegmentData.h"
#include "AliHLTTPCTransform.h"
#include "AliHLTTPCTrackArray.h"
#if __GNUC__ >= 3
using namespace std;
#endif
ClassImp(AliHLTTPCTrackMerger)
AliHLTTPCTrackMerger::AliHLTTPCTrackMerger()
:
AliHLTTPCMerger(),
fSubSector(0),
fNSubSector(0),
fRowMin(NULL),
fRowMax(NULL),
fSlow(0)
{
//Default constructor
Is2Global(kFALSE);
SetParameter();
}
AliHLTTPCTrackMerger::AliHLTTPCTrackMerger(Int_t nsubsectors)
:
AliHLTTPCMerger(),
fSubSector(0),
fNSubSector(nsubsectors),
fRowMin(new Int_t[nsubsectors]),
fRowMax(new Int_t[nsubsectors]),
fSlow(0)
{
//Constructor.
InitMerger(nsubsectors);
Is2Global(kFALSE);
fSlow = kFALSE;
SetParameter();
}
AliHLTTPCTrackMerger::~AliHLTTPCTrackMerger(){
//Destructor
}
void AliHLTTPCTrackMerger::SetRows(Int_t *row){
//Set the indeces of the first and last
//TPC padrows
//
for(Int_t i=0;i<fNSubSector;i++){
fRowMin[i]=*(row+(2*i));
fRowMax[i]=*(row+(2*i+1));
}
}
void AliHLTTPCTrackMerger::InitSector(Int_t slice,Int_t subsector){
//
// Select Sector and subsector. The following FillTracks call will
// fill this subsector
//
fSlice = slice;
fSubSector = subsector;
fCurrentTracks = fSubSector;
}
void AliHLTTPCTrackMerger::SlowMerge(AliHLTTPCTrackArray *mergedtrack,AliHLTTPCTrackArray *tracksin,AliHLTTPCTrackArray *tracksout,Double_t xval){
//
// Slow merging of two AliHLTTPCTrackArrays
// at reference plane x=xval
//
void *ntuple=GetNtuple();
const Int_t kNOut=tracksout->GetNTracks();
const Int_t kNIn =tracksin->GetNTracks();
const Int_t kNMerged =mergedtrack->GetNTracks();
AliHLTTPCTrack *tracks[2];
Bool_t merge = kTRUE;
while(merge){
Int_t inmin=-1,outmin=-1;
Double_t min=10;
for(Int_t out=0;out<kNOut;out++){
AliHLTTPCTrack *outertrack=tracksout->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in=0;in<kNIn;in++){
AliHLTTPCTrack *innertrack=tracksin->GetCheckedTrack(in);
if(!innertrack) continue;
Double_t diff = TrackDiff(innertrack,outertrack);
if(diff>=0&&diff<min){
min=diff;
inmin=in;
outmin=out;
}
}
}
if(inmin>=0&&outmin>=0){
AliHLTTPCTrack *outertrack=tracksout->GetTrack(outmin);
AliHLTTPCTrack *innertrack=tracksin->GetTrack(inmin);
tracks[0]=innertrack;
tracks[1]=outertrack;
SortTracks(tracks,2);
MultiMerge(mergedtrack,tracks,2);
outertrack->CalculatePoint(xval);
innertrack->CalculatePoint(xval);
PrintDiff(innertrack,outertrack);
//FillNtuple(ntuple,innertrack,outertrack);
tracksout->Remove(outmin);
tracksin->Remove(inmin);
// tracksout->Compress();
// tracksin->Compress();
}
else merge = kFALSE;
}
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::SlowMerge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "
<<mergedtrack->GetNTracks()-kNMerged<<ENDLOG;
char name[256] = "ntuple_t.root";
for(Int_t i=0;i<4;i++)
if(tracksin==GetInTracks(i))
sprintf(name,"ntuple_t_%d.root",i);
WriteNtuple(name,ntuple);
}
void AliHLTTPCTrackMerger::SlowMerge(){
fSlow = kTRUE;
Merge();
}
void AliHLTTPCTrackMerger::InterMerge(){
//
// Merging of the tracks
// between readout patches
//
for(Int_t patch=0;patch< GetNIn();patch++){
AliHLTTPCTrackArray * tracks = GetInTracks(patch);
Double_t xval = AliHLTTPCTransform::Row2X((fRowMax[patch]+fRowMin[patch])/2);
Int_t nrow= fRowMax[patch]-fRowMin[patch]+1;
const Int_t kNIn =tracks->GetNTracks();
AliHLTTPCTrack *tr[2];
for(Int_t in=0;in<kNIn;in++){
AliHLTTPCTrack *t = tracks->GetCheckedTrack(in);
if(t){
t->CalculateHelix();
t->CalculatePoint(xval);
}
}
for(Int_t out=0;out<kNIn;out++){
AliHLTTPCTrack *outertrack=tracks->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in=0;in<kNIn;in++){
if(in==out) continue;
AliHLTTPCTrack *innertrack=tracks->GetCheckedTrack(in);
if(!innertrack) continue;
if(outertrack->GetNHits()+innertrack->GetNHits()>nrow) continue;
if(IsTrack(innertrack,outertrack)){
tr[0]=innertrack;
tr[1]=outertrack;
SortTracks(tr,2);
if(tr[0]->GetLastPointX()<tr[1]->GetFirstPointX()){
MultiMerge(tracks,tr,2);
tracks->Remove(out);
tracks->Remove(in);
break;
}
}
}
}
Int_t nmerged = tracks->GetNTracks()-kNIn;
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::InterMerge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "<<nmerged<<ENDLOG;
}
}
void AliHLTTPCTrackMerger::Merge(){
//Loop over tracks and pass them to the track merger.
Double_t edge0 = AliHLTTPCTransform::Pi()/18;
Double_t edge1 = AliHLTTPCTransform::TwoPi() - edge0;
AliHLTTPCTrackArray *ttt = GetOutTracks();
if(fNSubSector==1) {
GetOutTracks()->AddTracks(GetInTracks(0));
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Total Copied Tracks: "<<GetOutTracks()->GetNPresent()
<<ENDLOG;
return;
}
Int_t subsec = fNSubSector -2;
for(Int_t i=subsec;i>=0;i--){
AliHLTTPCTrackArray *tout = GetOutTracks();
if(i==subsec) tout = GetInTracks(subsec+1);
AliHLTTPCTrackArray *tin = GetInTracks(i);
Double_t xval = AliHLTTPCTransform::Row2X(fRowMax[i]);
Double_t xmax = AliHLTTPCTransform::Row2X(fRowMax[i+1]);
Double_t ymax = xval*tan(edge0);
for(Int_t out=0;out<tout->GetNTracks();out++){
AliHLTTPCTrack *outtrack=tout->GetCheckedTrack(out);
if(!outtrack) continue;
outtrack->CalculateHelix();
outtrack->CalculatePoint(xval);
if(outtrack->IsPoint()&&fabs(outtrack->GetPointY())>ymax){
if(outtrack->GetNHits()<10)
tout->Remove(out);
}
}
// tout->Compress();
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetTrack(in);
intrack->CalculateHelix();
intrack->CalculatePoint(xval);
}
tin->QSort();
tout->QSort();
if(fSlow) SlowMerge(ttt,tin,tout,xval);
else Merge(ttt,tin,tout);
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetCheckedTrack(in);
if(!intrack) continue;
if(intrack->CalculateEdgePoint(edge0)){
if(intrack->GetPointX()<xmax ){
AddTrack(ttt,intrack);
tin->Remove(in);
}
}
else if(intrack->CalculateEdgePoint(edge1)){
if(intrack->GetPointX()<xmax ){
AddTrack(ttt,intrack);
tin->Remove(in);
}
}
}
/*
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetCheckedTrack(in);
if(!intrack) continue;
if(intrack->GetNHits()<10) continue;
AddTrack(ttt,intrack);
tin->Remove(in);
}
*/
} // end subsector loop
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Total Merged Tracks: "<<GetOutTracks()->GetNPresent()
<<ENDLOG;
}
Int_t AliHLTTPCTrackMerger::Merge(AliHLTTPCTrackArray* mergedtrack,AliHLTTPCTrackArray *tracksin,AliHLTTPCTrackArray *tracksout){
//Loop over tracks and pass them to the track merger.
AliHLTTPCTrack *tracks[2];
const Int_t kNOut=tracksout->GetNTracks();
const Int_t kNIn =tracksin->GetNTracks();
const Int_t kNMerged =mergedtrack->GetNTracks();
Bool_t *ismatchedin = new Bool_t[kNIn];
for(Int_t in =0;in<kNIn;in++)
ismatchedin[in]=kFALSE;
Bool_t *ismatchedout = new Bool_t[kNOut];
for(Int_t out =0;out<kNOut;out++)
ismatchedout[out] = kFALSE;
for(Int_t out =0;out<kNOut;out++){
AliHLTTPCTrack *outertrack=(AliHLTTPCTrack*)tracksout->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in =0;in<kNIn;in++){
if(ismatchedin[in]) continue;
AliHLTTPCTrack *innertrack=(AliHLTTPCTrack*)tracksin->GetCheckedTrack(in);
if(!innertrack) continue;
if(outertrack==innertrack) continue;
if(outertrack->GetCharge()!=innertrack->GetCharge()) continue;
if(IsTrack(innertrack,outertrack)){
tracks[0]=innertrack; tracks[1]=outertrack;
SortTracks(tracks,2);
if(tracks[0]->GetLastPointX()<tracks[1]->GetFirstPointX()){
MultiMerge(mergedtrack,tracks,2);
tracksout->Remove(out);
tracksin->Remove(in);
ismatchedin[in]=kTRUE;
ismatchedout[out]=kTRUE;
break;
}
}
}
}
Int_t nmerged = mergedtrack->GetNTracks()-kNMerged;
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "<<nmerged<<ENDLOG;
delete[] ismatchedin;
delete[] ismatchedout;
return nmerged;
}
<commit_msg>memory leak elimiated, minor format of comments<commit_after>// $Id$
// Original: AliHLTTrackMerger.cxx,v 1.12 2005/06/14 10:55:21 cvetan
//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Uli Frankenfeld, maintained by *
//* Matthias Richter <Matthias.Richter@ift.uib.no> *
//* for The ALICE HLT Project. *
//* *
//* Permission to use, copy, modify and distribute this software and its *
//* documentation strictly for non-commercial purposes is hereby granted *
//* without fee, provided that the above copyright notice appears in all *
//* copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************
/// @file AliHLTTPCTrackMerger.cxx
/// @author Uli Frankenfeld, maintained by Matthias Richter
/// @date
/// @brief The HLT TPC track segment merger
///
#include "AliHLTTPCLogging.h"
#include "AliHLTTPCTrackMerger.h"
#include "AliHLTTPCTrack.h"
#include "AliHLTTPCTrackSegmentData.h"
#include "AliHLTTPCTransform.h"
#include "AliHLTTPCTrackArray.h"
#if __GNUC__ >= 3
using namespace std;
#endif
ClassImp(AliHLTTPCTrackMerger)
AliHLTTPCTrackMerger::AliHLTTPCTrackMerger()
:
AliHLTTPCMerger(),
fSubSector(0),
fNSubSector(0),
fRowMin(NULL),
fRowMax(NULL),
fSlow(0)
{
//Default constructor
Is2Global(kFALSE);
SetParameter();
}
AliHLTTPCTrackMerger::AliHLTTPCTrackMerger(Int_t nsubsectors)
:
AliHLTTPCMerger(),
fSubSector(0),
fNSubSector(nsubsectors),
fRowMin(new Int_t[nsubsectors]),
fRowMax(new Int_t[nsubsectors]),
fSlow(0)
{
//Constructor.
InitMerger(nsubsectors);
Is2Global(kFALSE);
fSlow = kFALSE;
SetParameter();
}
AliHLTTPCTrackMerger::~AliHLTTPCTrackMerger()
{
//Destructor
if (fRowMin) delete[] fRowMin;
if (fRowMax) delete[] fRowMax;
}
void AliHLTTPCTrackMerger::SetRows(Int_t *row){
//Set the indeces of the first and last
//TPC padrows
//
for(Int_t i=0;i<fNSubSector;i++){
fRowMin[i]=*(row+(2*i));
fRowMax[i]=*(row+(2*i+1));
}
}
void AliHLTTPCTrackMerger::InitSector(Int_t slice,Int_t subsector){
//
// Select Sector and subsector. The following FillTracks call will
// fill this subsector
//
fSlice = slice;
fSubSector = subsector;
fCurrentTracks = fSubSector;
}
void AliHLTTPCTrackMerger::SlowMerge(AliHLTTPCTrackArray *mergedtrack,AliHLTTPCTrackArray *tracksin,AliHLTTPCTrackArray *tracksout,Double_t xval){
//
// Slow merging of two AliHLTTPCTrackArrays
// at reference plane x=xval
//
void *ntuple=GetNtuple();
const Int_t kNOut=tracksout->GetNTracks();
const Int_t kNIn =tracksin->GetNTracks();
const Int_t kNMerged =mergedtrack->GetNTracks();
AliHLTTPCTrack *tracks[2];
Bool_t merge = kTRUE;
while(merge){
Int_t inmin=-1,outmin=-1;
Double_t min=10;
for(Int_t out=0;out<kNOut;out++){
AliHLTTPCTrack *outertrack=tracksout->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in=0;in<kNIn;in++){
AliHLTTPCTrack *innertrack=tracksin->GetCheckedTrack(in);
if(!innertrack) continue;
Double_t diff = TrackDiff(innertrack,outertrack);
if(diff>=0&&diff<min){
min=diff;
inmin=in;
outmin=out;
}
}
}
if(inmin>=0&&outmin>=0){
AliHLTTPCTrack *outertrack=tracksout->GetTrack(outmin);
AliHLTTPCTrack *innertrack=tracksin->GetTrack(inmin);
tracks[0]=innertrack;
tracks[1]=outertrack;
SortTracks(tracks,2);
MultiMerge(mergedtrack,tracks,2);
outertrack->CalculatePoint(xval);
innertrack->CalculatePoint(xval);
PrintDiff(innertrack,outertrack);
//FillNtuple(ntuple,innertrack,outertrack);
tracksout->Remove(outmin);
tracksin->Remove(inmin);
// tracksout->Compress();
// tracksin->Compress();
}
else merge = kFALSE;
}
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::SlowMerge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "
<<mergedtrack->GetNTracks()-kNMerged<<ENDLOG;
char name[256] = "ntuple_t.root";
for(Int_t i=0;i<4;i++)
if(tracksin==GetInTracks(i))
sprintf(name,"ntuple_t_%d.root",i);
WriteNtuple(name,ntuple);
}
void AliHLTTPCTrackMerger::SlowMerge(){
fSlow = kTRUE;
Merge();
}
void AliHLTTPCTrackMerger::InterMerge(){
//
// Merging of the tracks
// between readout patches
//
for(Int_t patch=0;patch< GetNIn();patch++){
AliHLTTPCTrackArray * tracks = GetInTracks(patch);
Double_t xval = AliHLTTPCTransform::Row2X((fRowMax[patch]+fRowMin[patch])/2);
Int_t nrow= fRowMax[patch]-fRowMin[patch]+1;
const Int_t kNIn =tracks->GetNTracks();
AliHLTTPCTrack *tr[2];
for(Int_t in=0;in<kNIn;in++){
AliHLTTPCTrack *t = tracks->GetCheckedTrack(in);
if(t){
t->CalculateHelix();
t->CalculatePoint(xval);
}
}
for(Int_t out=0;out<kNIn;out++){
AliHLTTPCTrack *outertrack=tracks->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in=0;in<kNIn;in++){
if(in==out) continue;
AliHLTTPCTrack *innertrack=tracks->GetCheckedTrack(in);
if(!innertrack) continue;
if(outertrack->GetNHits()+innertrack->GetNHits()>nrow) continue;
if(IsTrack(innertrack,outertrack)){
tr[0]=innertrack;
tr[1]=outertrack;
SortTracks(tr,2);
if(tr[0]->GetLastPointX()<tr[1]->GetFirstPointX()){
MultiMerge(tracks,tr,2);
tracks->Remove(out);
tracks->Remove(in);
break;
}
}
}
}
Int_t nmerged = tracks->GetNTracks()-kNIn;
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::InterMerge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "<<nmerged<<ENDLOG;
}
}
void AliHLTTPCTrackMerger::Merge(){
//Loop over tracks and pass them to the track merger.
Double_t edge0 = AliHLTTPCTransform::Pi()/18;
Double_t edge1 = AliHLTTPCTransform::TwoPi() - edge0;
AliHLTTPCTrackArray *ttt = GetOutTracks();
if(fNSubSector==1) {
GetOutTracks()->AddTracks(GetInTracks(0));
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Total Copied Tracks: "<<GetOutTracks()->GetNPresent()
<<ENDLOG;
return;
}
Int_t subsec = fNSubSector -2;
for(Int_t i=subsec;i>=0;i--){
AliHLTTPCTrackArray *tout = GetOutTracks();
if(i==subsec) tout = GetInTracks(subsec+1);
AliHLTTPCTrackArray *tin = GetInTracks(i);
Double_t xval = AliHLTTPCTransform::Row2X(fRowMax[i]);
Double_t xmax = AliHLTTPCTransform::Row2X(fRowMax[i+1]);
Double_t ymax = xval*tan(edge0);
for(Int_t out=0;out<tout->GetNTracks();out++){
AliHLTTPCTrack *outtrack=tout->GetCheckedTrack(out);
if(!outtrack) continue;
outtrack->CalculateHelix();
outtrack->CalculatePoint(xval);
if(outtrack->IsPoint()&&fabs(outtrack->GetPointY())>ymax){
if(outtrack->GetNHits()<10)
tout->Remove(out);
}
}
// tout->Compress();
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetTrack(in);
intrack->CalculateHelix();
intrack->CalculatePoint(xval);
}
tin->QSort();
tout->QSort();
if(fSlow) SlowMerge(ttt,tin,tout,xval);
else Merge(ttt,tin,tout);
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetCheckedTrack(in);
if(!intrack) continue;
if(intrack->CalculateEdgePoint(edge0)){
if(intrack->GetPointX()<xmax ){
AddTrack(ttt,intrack);
tin->Remove(in);
}
}
else if(intrack->CalculateEdgePoint(edge1)){
if(intrack->GetPointX()<xmax ){
AddTrack(ttt,intrack);
tin->Remove(in);
}
}
}
/*
for(Int_t in=0;in<tin->GetNTracks();in++){
AliHLTTPCTrack *intrack=(AliHLTTPCTrack*)tin->GetCheckedTrack(in);
if(!intrack) continue;
if(intrack->GetNHits()<10) continue;
AddTrack(ttt,intrack);
tin->Remove(in);
}
*/
} // end subsector loop
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Total Merged Tracks: "<<GetOutTracks()->GetNPresent()
<<ENDLOG;
}
Int_t AliHLTTPCTrackMerger::Merge(AliHLTTPCTrackArray* mergedtrack,AliHLTTPCTrackArray *tracksin,AliHLTTPCTrackArray *tracksout){
//Loop over tracks and pass them to the track merger.
AliHLTTPCTrack *tracks[2];
const Int_t kNOut=tracksout->GetNTracks();
const Int_t kNIn =tracksin->GetNTracks();
const Int_t kNMerged =mergedtrack->GetNTracks();
Bool_t *ismatchedin = new Bool_t[kNIn];
for(Int_t in =0;in<kNIn;in++)
ismatchedin[in]=kFALSE;
Bool_t *ismatchedout = new Bool_t[kNOut];
for(Int_t out =0;out<kNOut;out++)
ismatchedout[out] = kFALSE;
for(Int_t out =0;out<kNOut;out++){
AliHLTTPCTrack *outertrack=(AliHLTTPCTrack*)tracksout->GetCheckedTrack(out);
if(!outertrack) continue;
for(Int_t in =0;in<kNIn;in++){
if(ismatchedin[in]) continue;
AliHLTTPCTrack *innertrack=(AliHLTTPCTrack*)tracksin->GetCheckedTrack(in);
if(!innertrack) continue;
if(outertrack==innertrack) continue;
if(outertrack->GetCharge()!=innertrack->GetCharge()) continue;
if(IsTrack(innertrack,outertrack)){
tracks[0]=innertrack; tracks[1]=outertrack;
SortTracks(tracks,2);
if(tracks[0]->GetLastPointX()<tracks[1]->GetFirstPointX()){
MultiMerge(mergedtrack,tracks,2);
tracksout->Remove(out);
tracksin->Remove(in);
ismatchedin[in]=kTRUE;
ismatchedout[out]=kTRUE;
break;
}
}
}
}
Int_t nmerged = mergedtrack->GetNTracks()-kNMerged;
LOG(AliHLTTPCLog::kInformational,"AliHLTTPCTrackMerger::Merge","Result")
<<AliHLTTPCLog::kDec<<"Merged Tracks: "<<nmerged<<ENDLOG;
delete[] ismatchedin;
delete[] ismatchedout;
return nmerged;
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
* Copyright (c) 2010-2011, Elliott Cooper-Balis
* Paul Rosenfeld
* Bruce Jacob
* University of Maryland
* dramninjas [at] gmail [dot] com
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
#include "SystemConfiguration.h"
#include "AddressMapping.h"
namespace DRAMSim
{
void addressMapping(uint64_t physicalAddress, unsigned &newTransactionChan, unsigned &newTransactionRank, unsigned &newTransactionBank, unsigned &newTransactionRow, unsigned &newTransactionColumn)
{
uint64_t tempA, tempB;
unsigned transactionSize = (JEDEC_DATA_BUS_BITS/8)*BL;
uint64_t transactionMask = transactionSize - 1; //ex: (64 bit bus width) x (8 Burst Length) - 1 = 64 bytes - 1 = 63 = 0x3f mask
unsigned channelBitWidth = dramsim_log2(NUM_CHANS);
unsigned rankBitWidth = dramsim_log2(NUM_RANKS);
unsigned bankBitWidth = dramsim_log2(NUM_BANKS);
unsigned rowBitWidth = dramsim_log2(NUM_ROWS);
unsigned colBitWidth = dramsim_log2(NUM_COLS);
// this forces the alignment to the width of a single burst (64 bits = 8 bytes = 3 address bits for DDR parts)
unsigned byteOffsetWidth = dramsim_log2((JEDEC_DATA_BUS_BITS/8));
// Since we're assuming that a request is for BL*BUS_WIDTH, the bottom bits
// of this address *should* be all zeros if it's not, issue a warning
if ((physicalAddress & transactionMask) != 0)
{
DEBUG("WARNING: address 0x"<<std::hex<<physicalAddress<<std::dec<<" is not aligned to the request size of "<<transactionSize);
}
// each burst will contain JEDEC_DATA_BUS_BITS/8 bytes of data, so the bottom bits (3 bits for a single channel DDR system) are
// thrown away before mapping the other bits
physicalAddress >>= byteOffsetWidth;
// The next thing we have to consider is that when a request is made for a
// we've taken into account the granulaity of a single burst by shifting
// off the bottom 3 bits, but a transaction has to take into account the
// burst length (i.e. the requests will be aligned to cache line sizes which
// should be equal to transactionSize above).
//
// Since the column address increments internally on bursts, the bottom n
// bits of the column (colLow) have to be zero in order to account for the
// total size of the transaction. These n bits should be shifted off the
// address and also subtracted from the total column width.
//
// I am having a hard time explaining the reasoning here, but it comes down
// this: for a 64 byte transaction, the bottom 6 bits of the address must be
// zero. These zero bits must be made up of the byte offset (3 bits) and also
// from the bottom bits of the column
//
// For example: cowLowBits = log2(64bytes) - 3 bits = 3 bits
unsigned colLowBitWidth = dramsim_log2(transactionSize) - byteOffsetWidth;
physicalAddress >>= colLowBitWidth;
unsigned colHighBitWidth = colBitWidth - colLowBitWidth;
if (DEBUG_ADDR_MAP)
{
DEBUG("Bit widths: ch:"<<channelBitWidth<<" r:"<<rankBitWidth<<" b:"<<bankBitWidth
<<" row:"<<rowBitWidth<<" colLow:"<<colLowBitWidth
<< " colHigh:"<<colHighBitWidth<<" off:"<<byteOffsetWidth
<< " Total:"<< (channelBitWidth + rankBitWidth + bankBitWidth + rowBitWidth + colLowBitWidth + colHighBitWidth + byteOffsetWidth));
}
//perform various address mapping schemes
if (addressMappingScheme == Scheme1)
{
//chan:rank:row:col:bank
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme2)
{
//chan:row:col:bank:rank
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme8)
{
//chan:bank[msb]:row:col:bank[msb-1:0]:rank
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> (bankBitWidth-1);
tempB = physicalAddress << (bankBitWidth-1);
newTransactionBank = tempA ^ tempB;
if( physicalAddress > (0x20000000 >> (rankBitWidth + bankBitWidth - 1)) )
newTransactionBank += 1 << (bankBitWidth - 1);
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme3)
{
//chan:rank:bank:col:row
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme4)
{
//chan:rank:bank:row:col
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme5)
{
//chan:row:col:rank:bank
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme6)
{
//chan:row:bank:rank:col
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
// clone of scheme 5, but channel moved to lower bits
else if (addressMappingScheme == Scheme7)
{
//row:col:rank:bank:chan
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
}
else
{
ERROR("== Error - Unknown Address Mapping Scheme");
exit(-1);
}
if (DEBUG_ADDR_MAP)
{
DEBUG("Mapped Ch="<<newTransactionChan<<" Rank="<<newTransactionRank
<<" Bank="<<newTransactionBank<<" Row="<<newTransactionRow
<<" Col="<<newTransactionColumn<<"\n");
}
}
};
<commit_msg>fix FA scheme<commit_after>/*********************************************************************************
* Copyright (c) 2010-2011, Elliott Cooper-Balis
* Paul Rosenfeld
* Bruce Jacob
* University of Maryland
* dramninjas [at] gmail [dot] com
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
#include "SystemConfiguration.h"
#include "AddressMapping.h"
namespace DRAMSim
{
void addressMapping(uint64_t physicalAddress, unsigned &newTransactionChan, unsigned &newTransactionRank, unsigned &newTransactionBank, unsigned &newTransactionRow, unsigned &newTransactionColumn)
{
uint64_t tempA, tempB;
unsigned transactionSize = (JEDEC_DATA_BUS_BITS/8)*BL;
uint64_t transactionMask = transactionSize - 1; //ex: (64 bit bus width) x (8 Burst Length) - 1 = 64 bytes - 1 = 63 = 0x3f mask
unsigned channelBitWidth = dramsim_log2(NUM_CHANS);
unsigned rankBitWidth = dramsim_log2(NUM_RANKS);
unsigned bankBitWidth = dramsim_log2(NUM_BANKS);
unsigned rowBitWidth = dramsim_log2(NUM_ROWS);
unsigned colBitWidth = dramsim_log2(NUM_COLS);
// this forces the alignment to the width of a single burst (64 bits = 8 bytes = 3 address bits for DDR parts)
unsigned byteOffsetWidth = dramsim_log2((JEDEC_DATA_BUS_BITS/8));
// Since we're assuming that a request is for BL*BUS_WIDTH, the bottom bits
// of this address *should* be all zeros if it's not, issue a warning
if ((physicalAddress & transactionMask) != 0)
{
DEBUG("WARNING: address 0x"<<std::hex<<physicalAddress<<std::dec<<" is not aligned to the request size of "<<transactionSize);
}
// each burst will contain JEDEC_DATA_BUS_BITS/8 bytes of data, so the bottom bits (3 bits for a single channel DDR system) are
// thrown away before mapping the other bits
physicalAddress >>= byteOffsetWidth;
// The next thing we have to consider is that when a request is made for a
// we've taken into account the granulaity of a single burst by shifting
// off the bottom 3 bits, but a transaction has to take into account the
// burst length (i.e. the requests will be aligned to cache line sizes which
// should be equal to transactionSize above).
//
// Since the column address increments internally on bursts, the bottom n
// bits of the column (colLow) have to be zero in order to account for the
// total size of the transaction. These n bits should be shifted off the
// address and also subtracted from the total column width.
//
// I am having a hard time explaining the reasoning here, but it comes down
// this: for a 64 byte transaction, the bottom 6 bits of the address must be
// zero. These zero bits must be made up of the byte offset (3 bits) and also
// from the bottom bits of the column
//
// For example: cowLowBits = log2(64bytes) - 3 bits = 3 bits
unsigned colLowBitWidth = dramsim_log2(transactionSize) - byteOffsetWidth;
physicalAddress >>= colLowBitWidth;
unsigned colHighBitWidth = colBitWidth - colLowBitWidth;
if (DEBUG_ADDR_MAP)
{
DEBUG("Bit widths: ch:"<<channelBitWidth<<" r:"<<rankBitWidth<<" b:"<<bankBitWidth
<<" row:"<<rowBitWidth<<" colLow:"<<colLowBitWidth
<< " colHigh:"<<colHighBitWidth<<" off:"<<byteOffsetWidth
<< " Total:"<< (channelBitWidth + rankBitWidth + bankBitWidth + rowBitWidth + colLowBitWidth + colHighBitWidth + byteOffsetWidth));
}
//perform various address mapping schemes
if (addressMappingScheme == Scheme1)
{
//chan:rank:row:col:bank
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme2)
{
//chan:row:col:bank:rank
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme8)
{
//chan:bank[msb]:row:col:bank[msb-1:0]:rank
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> (bankBitWidth-1);
tempB = physicalAddress << (bankBitWidth-1);
newTransactionBank = tempA ^ tempB;
if( physicalAddress > (0x20000000 >> (colLowBitWidth + byteOffsetWidth + rankBitWidth + bankBitWidth - 1)) )
newTransactionBank += 1 << (bankBitWidth - 1);
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme3)
{
//chan:rank:bank:col:row
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme4)
{
//chan:rank:bank:row:col
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme5)
{
//chan:row:col:rank:bank
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
else if (addressMappingScheme == Scheme6)
{
//chan:row:bank:rank:col
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
}
// clone of scheme 5, but channel moved to lower bits
else if (addressMappingScheme == Scheme7)
{
//row:col:rank:bank:chan
tempA = physicalAddress;
physicalAddress = physicalAddress >> channelBitWidth;
tempB = physicalAddress << channelBitWidth;
newTransactionChan = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> bankBitWidth;
tempB = physicalAddress << bankBitWidth;
newTransactionBank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rankBitWidth;
tempB = physicalAddress << rankBitWidth;
newTransactionRank = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> colHighBitWidth;
tempB = physicalAddress << colHighBitWidth;
newTransactionColumn = tempA ^ tempB;
tempA = physicalAddress;
physicalAddress = physicalAddress >> rowBitWidth;
tempB = physicalAddress << rowBitWidth;
newTransactionRow = tempA ^ tempB;
}
else
{
ERROR("== Error - Unknown Address Mapping Scheme");
exit(-1);
}
if (DEBUG_ADDR_MAP)
{
DEBUG("Mapped Ch="<<newTransactionChan<<" Rank="<<newTransactionRank
<<" Bank="<<newTransactionBank<<" Row="<<newTransactionRow
<<" Col="<<newTransactionColumn<<"\n");
}
}
};
<|endoftext|>
|
<commit_before>#include "rice/Array.hpp"
#include "rice/Constructor.hpp"
#include "rice/Object.hpp"
#include "config.h"
#include "generator.h"
#include "question.h"
#include "topic.h"
using namespace ailab;
template<>
question_t from_ruby<question_t>(Rice::Object obj) {
size_t qid = from_ruby<size_t>(obj.call("question_id"));
size_t tid = from_ruby<size_t>(obj.call("topic_id"));
size_t d = from_ruby<size_t>(obj.call("difficulty"));
std::string t = from_ruby<std::string>(obj.call("text"));
return question_t(qid, tid, d, t);
}
template<>
Rice::Object to_ruby(question_t const &q) {
return Rice::Data_Object<question_t>(new question_t(q));
}
template<>
std::vector<question_t> from_ruby<std::vector<question_t>>(Rice::Object obj) {
Rice::Array arr(obj);
std::vector<question_t> res;
res.reserve(arr.size());
for (Rice::Object o : arr)
res.push_back(from_ruby<question_t>(o));
return res;
}
template<>
Rice::Object to_ruby(std::vector<question_t> const &questions) {
Rice::Array arr;
for (question_t const &q : questions)
arr.push(to_ruby(q));
return arr;
}
template<>
topic_t from_ruby<topic_t>(Rice::Object obj) {
size_t id = from_ruby<size_t>(obj.call("topic_id"));
size_t pid = from_ruby<size_t>(obj.call("parent_id"));
std::string text = from_ruby<std::string>(obj.call("text"));
return topic_t(id, pid, text);
}
template<>
Rice::Object to_ruby<topic_t>(topic_t const &th) {
return Rice::Data_Object<topic_t>(new topic_t(th));
}
template<>
std::vector<topic_t> from_ruby<std::vector<topic_t>>(Rice::Object obj) {
Rice::Array arr(obj);
std::vector<topic_t> topics;
topics.reserve(arr.size());
for (Rice::Object obj : arr)
topics.push_back(from_ruby<topic_t>(obj));
return topics;
}
void set_life_time(Rice::Object obj, size_t life_time) {
Rice::Data_Object<config_t>(obj)->life_time = life_time;
}
size_t get_life_time(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->life_time;
}
void set_mutation_chance(Rice::Object obj, double mutation_chance) {
Rice::Data_Object<config_t>(obj)->mutation_chance = mutation_chance;
}
double get_mutation_chance(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->mutation_chance;
}
void set_population_size(Rice::Object obj, size_t population_size) {
Rice::Data_Object<config_t>(obj)->population_size = population_size;
}
size_t get_population_size(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->population_size;
}
void set_variants_count(Rice::Object obj, size_t variants_count) {
Rice::Data_Object<config_t>(obj)->variants_count = variants_count;
}
size_t get_variants_count(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->variants_count;
}
void set_questions_count(Rice::Object obj, size_t questions_count) {
Rice::Data_Object<config_t>(obj)->questions_count = questions_count;
}
size_t get_questions_count(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->questions_count;
}
void set_topics(Rice::Object obj, Rice::Array topics) {
std::vector<size_t> th = from_ruby<std::vector<size_t>>(topics);
Rice::Data_Object<config_t>(obj)->topics = std::move(th);
}
Rice::Array get_topics(Rice::Object obj) {
std::vector<size_t> const &topics = Rice::Data_Object<config_t>(obj)->topics;
Rice::Array arr;
for (size_t t : topics)
arr.push(to_ruby<size_t>(t));
return arr;
}
template<>
config_t from_ruby<config_t>(Rice::Object obj) {
config_t result;
result.life_time = from_ruby<size_t>(obj.call("life_time"));
result.mutation_chance = from_ruby<double>(obj.call("mutation_chance"));
result.population_size = from_ruby<size_t>(obj.call("population_size"));
result.variants_count = from_ruby<size_t>(obj.call("variants_count"));
result.questions_count = from_ruby<size_t>(obj.call("questions_count"));
result.topics = from_ruby<std::vector<size_t>>(obj.call("topics"));
return result;
}
template<>
Rice::Object to_ruby<config_t>(config_t const &cnf) {
return Rice::Data_Object<config_t>(new config_t(cnf));
}
template<>
generator_t from_ruby<generator_t>(Rice::Object obj) {
config_t config = from_ruby<config_t>(obj.call("config"));
std::vector<topic_t> topics = from_ruby<std::vector<topic_t>>(obj.call("topics"));
std::vector<question_t> questions = from_ruby<std::vector<question_t>>(obj.call("questions"));
return generator_t(std::move(config), std::move(topics), std::move(questions));
}
template<>
Rice::Object to_ruby(generator_t const &t) {
return Rice::Data_Object<generator_t>(new generator_t(t));
}
template<>
Rice::Object to_ruby<variants_t>(variants_t const &ans) {
std::vector<std::vector<question_t>> const &questions = ans.get_questions();
Rice::Array result;
for (std::vector<question_t> const &arr : questions) {
Rice::Array buffer;
for (question_t const &q : arr)
buffer.push(to_ruby<question_t>(q));
result.push(buffer);
}
return result;
}
extern "C" void Init_tasks_generator() {
Rice::Module rb_mTasksGenerator = Rice::define_module("TasksGenerator");
Rice::Data_Type<config_t> rb_cConfig = Rice::define_class_under<config_t>(rb_mTasksGenerator, "Config")
.define_constructor(Rice::Constructor<config_t, size_t, size_t>(), (Rice::Arg("variants_count") = 8, Rice::Arg("questions_count") = 8))
.define_method("life_time=", &set_life_time)
.define_method("mutation_chance=", &set_mutation_chance)
.define_method("population_size=", &set_population_size)
.define_method("variants_count=", &set_variants_count)
.define_method("questions_count=", &set_questions_count)
.define_method("life_time", &get_life_time)
.define_method("mutation_chance", &get_mutation_chance)
.define_method("population_size", &get_population_size)
.define_method("variants_count", &get_variants_count)
.define_method("questions_count", &get_questions_count)
.define_method("topics", &get_topics)
.define_method("topics=", &set_topics);
Rice::Data_Type<topic_t> rb_ctopic = Rice::define_class_under<topic_t>(rb_mTasksGenerator, "Topic")
.define_constructor(Rice::Constructor<topic_t, size_t, size_t, std::string>(),
(Rice::Arg("id"), Rice::Arg("pid"), Rice::Arg("text")))
.define_method("topic_id", &topic_t::get_topic_id)
.define_method("parent_id", &topic_t::get_parent_id)
.define_method("text", &topic_t::get_text);
Rice::Data_Type<question_t> rb_cQuestion = Rice::define_class_under<question_t>(rb_mTasksGenerator, "Question")
.define_constructor(Rice::Constructor<question_t, size_t, size_t, size_t, std::string>(),
(Rice::Arg("id"), Rice::Arg("tid"), Rice::Arg("difficulty"), Rice::Arg("text")))
.define_method("question_id", &question_t::get_question_id)
.define_method("topic_id", &question_t::get_topic_id)
.define_method("difficulty", &question_t::get_difficulty)
.define_method("text", &question_t::get_text);
Rice::Data_Type<generator_t> rb_cGenerator = Rice::define_class_under<generator_t>(rb_mTasksGenerator, "Generator")
.define_constructor(Rice::Constructor<generator_t, config_t, std::vector<topic_t>, std::vector<question_t>>(),
(Rice::Arg("cnf"), Rice::Arg("topics"), Rice::Arg("questions")))
.define_method("generate", &generator_t::generate);
}
<commit_msg>fix binding bug<commit_after>#include "rice/Array.hpp"
#include "rice/Constructor.hpp"
#include "rice/Object.hpp"
#include "config.h"
#include "generator.h"
#include "question.h"
#include "topic.h"
using namespace ailab;
template<>
question_t from_ruby<question_t>(Rice::Object obj) {
size_t qid = from_ruby<size_t>(obj.call("question_id"));
size_t tid = from_ruby<size_t>(obj.call("topic_id"));
size_t d = from_ruby<size_t>(obj.call("difficulty"));
std::string t = from_ruby<std::string>(obj.call("text"));
return question_t(qid, tid, d, t);
}
template<>
Rice::Object to_ruby(question_t const &q) {
return Rice::Data_Object<question_t>(new question_t(q));
}
template<>
std::vector<question_t> from_ruby<std::vector<question_t>>(Rice::Object obj) {
Rice::Array arr(obj);
std::vector<question_t> res;
res.reserve(arr.size());
for (Rice::Object o : arr)
res.push_back(from_ruby<question_t>(o));
return res;
}
template<>
Rice::Object to_ruby(std::vector<question_t> const &questions) {
Rice::Array arr;
for (question_t const &q : questions)
arr.push(to_ruby(q));
return arr;
}
template<>
topic_t from_ruby<topic_t>(Rice::Object obj) {
size_t id = from_ruby<size_t>(obj.call("topic_id"));
size_t pid = from_ruby<size_t>(obj.call("parent_id"));
std::string text = from_ruby<std::string>(obj.call("text"));
return topic_t(id, pid, text);
}
template<>
Rice::Object to_ruby<topic_t>(topic_t const &th) {
return Rice::Data_Object<topic_t>(new topic_t(th));
}
template<>
std::vector<topic_t> from_ruby<std::vector<topic_t>>(Rice::Object obj) {
Rice::Array arr(obj);
std::vector<topic_t> topics;
topics.reserve(arr.size());
for (Rice::Object obj : arr)
topics.push_back(from_ruby<topic_t>(obj));
return topics;
}
void set_life_time(Rice::Object obj, size_t life_time) {
Rice::Data_Object<config_t>(obj)->life_time = life_time;
}
size_t get_life_time(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->life_time;
}
void set_mutation_chance(Rice::Object obj, double mutation_chance) {
Rice::Data_Object<config_t>(obj)->mutation_chance = mutation_chance;
}
double get_mutation_chance(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->mutation_chance;
}
void set_population_size(Rice::Object obj, size_t population_size) {
Rice::Data_Object<config_t>(obj)->population_size = population_size;
}
size_t get_population_size(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->population_size;
}
void set_variants_count(Rice::Object obj, size_t variants_count) {
Rice::Data_Object<config_t>(obj)->variants_count = variants_count;
}
size_t get_variants_count(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->variants_count;
}
void set_questions_count(Rice::Object obj, size_t questions_count) {
Rice::Data_Object<config_t>(obj)->questions_count = questions_count;
}
size_t get_questions_count(Rice::Object obj) {
return Rice::Data_Object<config_t>(obj)->questions_count;
}
void set_topics(Rice::Object obj, Rice::Array topics) {
std::vector<size_t> th = from_ruby<std::vector<size_t>>(topics);
Rice::Data_Object<config_t>(obj)->topics = std::move(th);
}
Rice::Array get_topics(Rice::Object obj) {
std::vector<size_t> const &topics = Rice::Data_Object<config_t>(obj)->topics;
Rice::Array arr;
for (size_t t : topics)
arr.push(to_ruby<size_t>(t));
return arr;
}
template<>
config_t from_ruby<config_t>(Rice::Object obj) {
config_t result;
result.life_time = from_ruby<size_t>(obj.call("life_time"));
result.mutation_chance = from_ruby<double>(obj.call("mutation_chance"));
result.population_size = from_ruby<size_t>(obj.call("population_size"));
result.variants_count = from_ruby<size_t>(obj.call("variants_count"));
result.questions_count = from_ruby<size_t>(obj.call("questions_count"));
result.topics = from_ruby<std::vector<size_t>>(obj.call("topics"));
return result;
}
template<>
Rice::Object to_ruby<config_t>(config_t const &cnf) {
return Rice::Data_Object<config_t>(new config_t(cnf));
}
template<>
generator_t from_ruby<generator_t>(Rice::Object obj) {
config_t config = from_ruby<config_t>(obj.call("config"));
std::vector<topic_t> topics = from_ruby<std::vector<topic_t>>(obj.call("topics"));
std::vector<question_t> questions = from_ruby<std::vector<question_t>>(obj.call("questions"));
return generator_t(std::move(config), std::move(topics), std::move(questions));
}
template<>
Rice::Object to_ruby(generator_t const &t) {
return Rice::Data_Object<generator_t>(new generator_t(t));
}
template<>
Rice::Object to_ruby<variants_t>(variants_t const &ans) {
std::vector<std::vector<question_t>> const &questions = ans.get_questions();
Rice::Array result;
for (std::vector<question_t> const &arr : questions) {
Rice::Array buffer;
for (question_t const &q : arr)
buffer.push(to_ruby<question_t>(q));
result.push(buffer);
}
return result;
}
extern "C" void Init_tasks_generator() {
Rice::Module rb_mTasksGenerator = Rice::define_module("TasksGenerator");
Rice::Data_Type<config_t> rb_cConfig = Rice::define_class_under<config_t>(rb_mTasksGenerator, "Config")
.define_constructor(Rice::Constructor<config_t, size_t, size_t>(),
(Rice::Arg("variants_count") = 8, Rice::Arg("questions_count") = 8))
.define_method("life_time=", &set_life_time)
.define_method("mutation_chance=", &set_mutation_chance)
.define_method("population_size=", &set_population_size)
.define_method("variants_count=", &set_variants_count)
.define_method("questions_count=", &set_questions_count)
.define_method("life_time", &get_life_time)
.define_method("mutation_chance", &get_mutation_chance)
.define_method("population_size", &get_population_size)
.define_method("variants_count", &get_variants_count)
.define_method("questions_count", &get_questions_count)
.define_method("topics", &get_topics)
.define_method("topics=", &set_topics);
Rice::Data_Type<topic_t> rb_ctopic = Rice::define_class_under<topic_t>(rb_mTasksGenerator, "Topic")
.define_constructor(Rice::Constructor<topic_t, size_t, size_t, std::string>(),
(Rice::Arg("id"), Rice::Arg("pid"), Rice::Arg("text")))
.define_method("topic_id", &topic_t::get_topic_id)
.define_method("parent_id", &topic_t::get_parent_id)
.define_method("text", &topic_t::get_text);
Rice::Data_Type<question_t> rb_cQuestion = Rice::define_class_under<question_t>(rb_mTasksGenerator, "Question")
.define_constructor(Rice::Constructor<question_t, size_t, size_t, size_t, std::string>(),
(Rice::Arg("id"), Rice::Arg("tid"), Rice::Arg("difficulty"), Rice::Arg("text")))
.define_method("question_id", &question_t::get_question_id)
.define_method("topic_id", &question_t::get_topic_id)
.define_method("difficulty", &question_t::get_difficulty)
.define_method("text", &question_t::get_text);
Rice::Data_Type<generator_t> rb_cGenerator = Rice::define_class_under<generator_t>(rb_mTasksGenerator, "Generator")
.define_constructor(Rice::Constructor<generator_t, config_t, std::vector<topic_t>, std::vector<question_t>>(),
(Rice::Arg("cnf"), Rice::Arg("topics"), Rice::Arg("questions")))
.define_method("generate", &generator_t::generate);
}
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include "ImageSources/ImageSourceFactories.h"
#include "ImageSources/ImageSource.h"
// Library/third-party includes
#include <opencv2/highgui/highgui.hpp>
// Standard includes
#include <memory>
#include <iostream>
#include <chrono>
#include <sstream>
/// @brief OpenCV's simple highgui module refers to windows by their name, so we
/// make this global for a simpler demo.
static const std::string windowNameAndInstructions(
"OSVR tracking camera preview | q or esc to quit");
static const auto FPS_MEASUREMENT_PERIOD = std::chrono::seconds(3);
class FrameCounter {
public:
FrameCounter() { reset(); }
void gotFrame() {
++m_frames;
auto now = clock::now();
if (now >= m_end) {
auto duration =
std::chrono::duration_cast<std::chrono::duration<double>>(
now - m_begin);
std::cout << m_frames / duration.count() << " FPS read from camera"
<< std::endl;
reset();
}
}
void reset() {
m_begin = clock::now();
m_end = m_begin + FPS_MEASUREMENT_PERIOD;
m_frames = 0;
}
private:
using clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<clock>;
time_point m_begin;
time_point m_end;
std::size_t m_frames = 0;
};
int main(int argc, char *argv[]) {
#ifdef _WIN32
auto cam = osvr::vbtracker::openHDKCameraDirectShow();
#else
std::cerr << "Warning: Just using OpenCV to open Camera #0, which may not "
"be the tracker camera."
<< std::endl;
auto cam = osvr::vbtracker::openOpenCVCamera(0);
#endif
if (!cam || !cam->ok()) {
std::cerr << "Couldn't find, open, or read from the OSVR HDK tracking "
"camera.\n"
<< "Press enter to exit." << std::endl;
std::cin.ignore();
return -1;
}
auto FRAME_DISPLAY_STRIDE = 3u;
if (argc > 1) {
auto is = std::istringstream{argv[1]};
if (is >> FRAME_DISPLAY_STRIDE) {
std::cout << "Custom display stride passed: "
<< FRAME_DISPLAY_STRIDE << std::endl;
} else {
std::cout << "Could not parse first command-line argument as a "
"display stride : '"
<< argv[1] << "' (will use default)" << std::endl;
}
}
cam->grab();
std::cout << "Will display 1 out of every " << FRAME_DISPLAY_STRIDE
<< " frames captured." << std::endl;
std::cout << "\nPress q or esc to quit, c to capture a frame to file.\n"
<< std::endl;
auto frame = cv::Mat{};
auto grayFrame = cv::Mat{};
auto savedFrame = false;
static const auto FILENAME = "capture.png";
static const auto FILENAME_STEM = "image";
static const auto EXTENSION = ".png";
auto captures = std::size_t{0};
FrameCounter counter;
cv::namedWindow(windowNameAndInstructions);
auto frameCount = std::size_t{0};
do {
cam->retrieve(frame, grayFrame);
counter.gotFrame();
++frameCount;
if (frameCount % FRAME_DISPLAY_STRIDE == 0) {
frameCount = 0;
cv::imshow(windowNameAndInstructions, frame);
if (!savedFrame) {
savedFrame = true;
cv::imwrite(FILENAME, frame);
std::cout << "Wrote a captured frame to " << FILENAME
<< std::endl;
}
char key = static_cast<char>(cv::waitKey(1)); // wait 1 ms for a key
if ('q' == key || 'Q' == key || 27 /*esc*/ == key) {
break;
} else if ('c' == key) {
// capture
std::ostringstream os;
os << FILENAME_STEM << captures << EXTENSION;
cv::imwrite(os.str(), frame);
std::cout << "Captured frame to " << os.str() << std::endl;
captures++;
}
}
} while (cam->grab());
return 0;
}
<commit_msg>Fix a build error caught on Linux.<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include "ImageSources/ImageSourceFactories.h"
#include "ImageSources/ImageSource.h"
// Library/third-party includes
#include <opencv2/highgui/highgui.hpp>
// Standard includes
#include <memory>
#include <iostream>
#include <chrono>
#include <sstream>
/// @brief OpenCV's simple highgui module refers to windows by their name, so we
/// make this global for a simpler demo.
static const std::string windowNameAndInstructions(
"OSVR tracking camera preview | q or esc to quit");
static const auto FPS_MEASUREMENT_PERIOD = std::chrono::seconds(3);
class FrameCounter {
public:
FrameCounter() { reset(); }
void gotFrame() {
++m_frames;
auto now = clock::now();
if (now >= m_end) {
auto duration =
std::chrono::duration_cast<std::chrono::duration<double>>(
now - m_begin);
std::cout << m_frames / duration.count() << " FPS read from camera"
<< std::endl;
reset();
}
}
void reset() {
m_begin = clock::now();
m_end = m_begin + FPS_MEASUREMENT_PERIOD;
m_frames = 0;
}
private:
using clock = std::chrono::system_clock;
using time_point = std::chrono::time_point<clock>;
time_point m_begin;
time_point m_end;
std::size_t m_frames = 0;
};
int main(int argc, char *argv[]) {
#ifdef _WIN32
auto cam = osvr::vbtracker::openHDKCameraDirectShow();
#else
std::cerr << "Warning: Just using OpenCV to open Camera #0, which may not "
"be the tracker camera."
<< std::endl;
auto cam = osvr::vbtracker::openOpenCVCamera(0);
#endif
if (!cam || !cam->ok()) {
std::cerr << "Couldn't find, open, or read from the OSVR HDK tracking "
"camera.\n"
<< "Press enter to exit." << std::endl;
std::cin.ignore();
return -1;
}
auto FRAME_DISPLAY_STRIDE = 3u;
if (argc > 1) {
std::stringstream ss;
ss << argv[1];
if (ss >> FRAME_DISPLAY_STRIDE) {
std::cout << "Custom display stride passed: "
<< FRAME_DISPLAY_STRIDE << std::endl;
} else {
std::cout << "Could not parse first command-line argument as a "
"display stride : '"
<< argv[1] << "' (will use default)" << std::endl;
}
}
cam->grab();
std::cout << "Will display 1 out of every " << FRAME_DISPLAY_STRIDE
<< " frames captured." << std::endl;
std::cout << "\nPress q or esc to quit, c to capture a frame to file.\n"
<< std::endl;
auto frame = cv::Mat{};
auto grayFrame = cv::Mat{};
auto savedFrame = false;
static const auto FILENAME = "capture.png";
static const auto FILENAME_STEM = "image";
static const auto EXTENSION = ".png";
auto captures = std::size_t{0};
FrameCounter counter;
cv::namedWindow(windowNameAndInstructions);
auto frameCount = std::size_t{0};
do {
cam->retrieve(frame, grayFrame);
counter.gotFrame();
++frameCount;
if (frameCount % FRAME_DISPLAY_STRIDE == 0) {
frameCount = 0;
cv::imshow(windowNameAndInstructions, frame);
if (!savedFrame) {
savedFrame = true;
cv::imwrite(FILENAME, frame);
std::cout << "Wrote a captured frame to " << FILENAME
<< std::endl;
}
char key = static_cast<char>(cv::waitKey(1)); // wait 1 ms for a key
if ('q' == key || 'Q' == key || 27 /*esc*/ == key) {
break;
} else if ('c' == key) {
// capture
std::ostringstream os;
os << FILENAME_STEM << captures << EXTENSION;
cv::imwrite(os.str(), frame);
std::cout << "Captured frame to " << os.str() << std::endl;
captures++;
}
}
} while (cam->grab());
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef _HASHTABLE_HPP_
#define _HASHTABLE_HPP_
#include <iostream>
using namespace std;
template <typename Key>
class Hashtable {
private:
struct Hash_node {
Key _k;
Hash_node *_next;
Hash_node(const Key &k, Hash_node *next = NULL);
};
Hash_node **_table;
unsigned int _table_size;
unsigned int _count;
int _hash(const Key &key) const;
void _delete();
void _copy(Hash_node **p_table);
public:
/*
@Init()
@params
@discussion Create a new hashtable with a default table size;
@return
*/
Hashtable();
/*
@Init(h : Hashtable)
@params h : Hashtable
@discussion Create a copy from h
@return
*/
Hashtable(const Hashtable &h);
/*
@Operator=(h : Hashtable)
@params h : Hashtable
@discussion Create a copy from h if anything goes wrong. If it's, restore the hashtable.
@return Pointer to the hashtable with values copied.
*/
Hashtable& operator=(const Hashtable &h);
/*
@Destructor
@params
@discussion Destroy the hashtable and free the dynamic memory
@return
*/
~Hashtable();
/*
@contains
@params
@discussion find in hashtable the element where key = k
@return The value if element exists, NULL otherwise.
*/
bool contains(const Key &k) const;
/*
@insert
@params
@discussion Insert a new element where elem._k = k
@return void
*/
void insert(const Key &k);
/*
@remove
@params
@discussion Remove the element if exists where key = k, otherwise nothing happens
@return void
*/
void remove(const Key &k);
/*
@print
@params
@discussion Print the hashtable
@return void
*/
void print_hash(std::ostream &os) const;
/*
@count
@params
@discussion
@return the number of elements in hashtable
*/
int count() const;
};
#include "Hashtable.t"
#endif
<commit_msg>Remove std from hashtable<commit_after>#ifndef _HASHTABLE_HPP_
#define _HASHTABLE_HPP_
template <typename Key>
class Hashtable {
private:
struct Hash_node {
Key _k;
Hash_node *_next;
Hash_node(const Key &k, Hash_node *next = NULL);
};
Hash_node **_table;
unsigned int _table_size;
unsigned int _count;
int _hash(const Key &key) const;
void _delete();
void _copy(Hash_node **p_table);
public:
/*
@Init()
@params
@discussion Create a new hashtable with a default table size;
@return
*/
Hashtable();
/*
@Init(h : Hashtable)
@params h : Hashtable
@discussion Create a copy from h
@return
*/
Hashtable(const Hashtable &h);
/*
@Operator=(h : Hashtable)
@params h : Hashtable
@discussion Create a copy from h if anything goes wrong. If it's, restore the hashtable.
@return Pointer to the hashtable with values copied.
*/
Hashtable& operator=(const Hashtable &h);
/*
@Destructor
@params
@discussion Destroy the hashtable and free the dynamic memory
@return
*/
~Hashtable();
/*
@contains
@params
@discussion find in hashtable the element where key = k
@return The value if element exists, NULL otherwise.
*/
bool contains(const Key &k) const;
/*
@insert
@params
@discussion Insert a new element where elem._k = k
@return void
*/
void insert(const Key &k);
/*
@remove
@params
@discussion Remove the element if exists where key = k, otherwise nothing happens
@return void
*/
void remove(const Key &k);
/*
@print
@params
@discussion Print the hashtable
@return void
*/
void print_hash(std::ostream &os) const;
/*
@count
@params
@discussion
@return the number of elements in hashtable
*/
int count() const;
};
#include "Hashtable.t"
#endif
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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/>.
The full license is available in the file GPLv3.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
//$Id$
#include "LicenseDialog.h"
#include <QVBoxLayout>
#include <QFont>
#include <QCheckBox>
#include <QPushButton>
#include "Utilities/GUIUtilities.h"
#include "HelpDialog.h"
#include "Configuration.h"
#include "DesktopHandler.h"
#include "global.h"
LicenseDialog::LicenseDialog(QWidget *pParent) :
QDialog(pParent)
{
setObjectName("LicenseDialog");
resize(640,480);
setWindowTitle(tr("Hopsan License"));
setAttribute(Qt::WA_DeleteOnClose, true);
setPalette(QPalette(QColor("gray"), QColor("whitesmoke")));
QVBoxLayout *pLayout = new QVBoxLayout(this);
QLabel *pGUIText = new QLabel(this);
QLabel *pGPLv3Header = new QLabel(this);
QLabel *pGPLv3Notice = new QLabel(this);
QLabel *pALv2Notice = new QLabel(this);
QLabel *pALv2Header = new QLabel(this);
QLabel *pCoreText = new QLabel(this);
QLabel *pDepHeader = new QLabel(this);
QLabel *pDepText = new QLabel(this);
QString gplv3_notice;
QFile gplv3_notice_file(":/license/licenseNoticeGPLv3");
if (gplv3_notice_file.exists()) {
gplv3_notice_file.open(QIODevice::ReadOnly);
QTextStream ts(&gplv3_notice_file);
gplv3_notice = ts.readAll();
gplv3_notice_file.close();
}
QString alv2_notice;
QFile al2_notice_file(":/license/licenseNoticeALv2");
if (al2_notice_file.exists()) {
al2_notice_file.open(QIODevice::ReadOnly);
QTextStream ts(&al2_notice_file);
alv2_notice = ts.readAll();
al2_notice_file.close();
}
QFont bigFont = pGUIText->font();
QFont mediumFont = pGUIText->font();
mediumFont.setPointSizeF(mediumFont.pointSizeF()*1.2);
bigFont.setPointSizeF(bigFont.pointSizeF()*2.0);
pGUIText->setText("This application, HopsanGUI, is released under the GPL version 3 license.");
pCoreText->setText("The HopsanCore simulation library, default component library and utility function libraries are released under the\nApache License version 2.0.");
pGUIText->setFont(mediumFont);
pCoreText->setFont(mediumFont);
QWidget *pNoticeBox = new QWidget(this);
QGridLayout *pNoticeLayout = new QGridLayout(pNoticeBox);
pNoticeLayout->setColumnMinimumWidth(1,30);
pGPLv3Header->setText("GPL version 3");
pGPLv3Header->setFont(bigFont);
pGPLv3Notice->setText(gplv3_notice);
pNoticeLayout->addWidget(pGPLv3Header,0,0,1,1);
pNoticeLayout->addWidget(pGPLv3Notice,1,0,1,1);
pALv2Header->setText("Apache License version 2.0");
pALv2Header->setFont(bigFont);
pALv2Notice->setText(alv2_notice);
pNoticeLayout->addWidget(pALv2Header,0,2,1,1);
pNoticeLayout->addWidget(pALv2Notice,1,2,1,1);
pDepHeader->setText("Dependencies:");
pDepHeader->setFont(bigFont);
QString deps;
deps.append("Hopsan uses third-party dependencies released under various licenses such as:\n");
deps.append("LGPL v2.1, LGPL v3.0, BSD, MIT and Apache License 2.0\n\n");
deps.append("For details on third-party dependencies and their respective licenses, see the documentation!");
pDepText->setText(deps);
pLayout->addWidget(pGUIText, 1);
pLayout->addWidget(pCoreText, 1);
pLayout->addWidget(pNoticeBox);
pLayout->addWidget(pDepHeader, 1);
pLayout->addWidget(pDepText, 1);
pLayout->addWidget(new QLabel(this), 4);
QPushButton *pDocsButton = new QPushButton("Show license documentation", this);
connect(pDocsButton, SIGNAL(clicked(bool)), this, SLOT(showLicenseDocs()));
pLayout->addWidget(pDocsButton, 1);
QCheckBox *pAlwaysShow = new QCheckBox("Always show on startup", this);
pAlwaysShow->setChecked(gpConfig->getBoolSetting(CFG_SHOWLICENSEONSTARTUP));
connect(pAlwaysShow, SIGNAL(clicked(bool)), this, SLOT(toggleAlwaysShow(bool)));
QPushButton *pCloseButton = new QPushButton("Close", this);
pCloseButton->setDefault(true);
connect(pCloseButton, SIGNAL(clicked(bool)), this, SLOT(close()));
QHBoxLayout *pBottomHLayout = new QHBoxLayout();
pBottomHLayout->addWidget(pAlwaysShow, 2);
pBottomHLayout->addWidget(pCloseButton, 1);
pLayout->addLayout(pBottomHLayout, 1);
setLayout(pLayout);
}
void LicenseDialog::toggleAlwaysShow(bool tf)
{
gpConfig->setBoolSetting(CFG_SHOWLICENSEONSTARTUP, tf);
}
void LicenseDialog::showLicenseDocs()
{
gpHelpDialog->open("page_hopsandependencies.html");
}
<commit_msg>Remove hard-coded style that make the dialog buttons look strange<commit_after>/*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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/>.
The full license is available in the file GPLv3.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
//$Id$
#include "LicenseDialog.h"
#include <QVBoxLayout>
#include <QFont>
#include <QCheckBox>
#include <QPushButton>
#include "Utilities/GUIUtilities.h"
#include "HelpDialog.h"
#include "Configuration.h"
#include "DesktopHandler.h"
#include "global.h"
LicenseDialog::LicenseDialog(QWidget *pParent) :
QDialog(pParent)
{
setObjectName("LicenseDialog");
resize(640,480);
setWindowTitle(tr("Hopsan License"));
setAttribute(Qt::WA_DeleteOnClose, true);
QVBoxLayout *pLayout = new QVBoxLayout(this);
QLabel *pGUIText = new QLabel(this);
QLabel *pGPLv3Header = new QLabel(this);
QLabel *pGPLv3Notice = new QLabel(this);
QLabel *pALv2Notice = new QLabel(this);
QLabel *pALv2Header = new QLabel(this);
QLabel *pCoreText = new QLabel(this);
QLabel *pDepHeader = new QLabel(this);
QLabel *pDepText = new QLabel(this);
QString gplv3_notice;
QFile gplv3_notice_file(":/license/licenseNoticeGPLv3");
if (gplv3_notice_file.exists()) {
gplv3_notice_file.open(QIODevice::ReadOnly);
QTextStream ts(&gplv3_notice_file);
gplv3_notice = ts.readAll();
gplv3_notice_file.close();
}
QString alv2_notice;
QFile al2_notice_file(":/license/licenseNoticeALv2");
if (al2_notice_file.exists()) {
al2_notice_file.open(QIODevice::ReadOnly);
QTextStream ts(&al2_notice_file);
alv2_notice = ts.readAll();
al2_notice_file.close();
}
QFont bigFont = pGUIText->font();
QFont mediumFont = pGUIText->font();
mediumFont.setPointSizeF(mediumFont.pointSizeF()*1.2);
bigFont.setPointSizeF(bigFont.pointSizeF()*2.0);
pGUIText->setText("This application, HopsanGUI, is released under the GPL version 3 license.");
pCoreText->setText("The HopsanCore simulation library, default component library and utility function libraries are released under the\nApache License version 2.0.");
pGUIText->setFont(mediumFont);
pCoreText->setFont(mediumFont);
QWidget *pNoticeBox = new QWidget(this);
QGridLayout *pNoticeLayout = new QGridLayout(pNoticeBox);
pNoticeLayout->setColumnMinimumWidth(1,30);
pGPLv3Header->setText("GPL version 3");
pGPLv3Header->setFont(bigFont);
pGPLv3Notice->setText(gplv3_notice);
pNoticeLayout->addWidget(pGPLv3Header,0,0,1,1);
pNoticeLayout->addWidget(pGPLv3Notice,1,0,1,1);
pALv2Header->setText("Apache License version 2.0");
pALv2Header->setFont(bigFont);
pALv2Notice->setText(alv2_notice);
pNoticeLayout->addWidget(pALv2Header,0,2,1,1);
pNoticeLayout->addWidget(pALv2Notice,1,2,1,1);
pDepHeader->setText("Dependencies:");
pDepHeader->setFont(bigFont);
QString deps;
deps.append("Hopsan uses third-party dependencies released under various licenses such as:\n");
deps.append("LGPL v2.1, LGPL v3.0, BSD, MIT and Apache License 2.0\n\n");
deps.append("For details on third-party dependencies and their respective licenses, see the documentation!");
pDepText->setText(deps);
pLayout->addWidget(pGUIText, 1);
pLayout->addWidget(pCoreText, 1);
pLayout->addWidget(pNoticeBox);
pLayout->addWidget(pDepHeader, 1);
pLayout->addWidget(pDepText, 1);
pLayout->addWidget(new QLabel(this), 4);
QPushButton *pDocsButton = new QPushButton("Show license documentation", this);
connect(pDocsButton, SIGNAL(clicked(bool)), this, SLOT(showLicenseDocs()));
pLayout->addWidget(pDocsButton, 1);
QCheckBox *pAlwaysShow = new QCheckBox("Always show on startup", this);
pAlwaysShow->setChecked(gpConfig->getBoolSetting(CFG_SHOWLICENSEONSTARTUP));
connect(pAlwaysShow, SIGNAL(clicked(bool)), this, SLOT(toggleAlwaysShow(bool)));
QPushButton *pCloseButton = new QPushButton("Close", this);
pCloseButton->setDefault(true);
connect(pCloseButton, SIGNAL(clicked(bool)), this, SLOT(close()));
QHBoxLayout *pBottomHLayout = new QHBoxLayout();
pBottomHLayout->addWidget(pAlwaysShow, 2);
pBottomHLayout->addWidget(pCloseButton, 1);
pLayout->addLayout(pBottomHLayout, 1);
setLayout(pLayout);
}
void LicenseDialog::toggleAlwaysShow(bool tf)
{
gpConfig->setBoolSetting(CFG_SHOWLICENSEONSTARTUP, tf);
}
void LicenseDialog::showLicenseDocs()
{
gpHelpDialog->open("page_hopsandependencies.html");
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "ArduCopterFirmwarePlugin.h"
#include "QGCApplication.h"
#include "MissionManager.h"
#include "ParameterManager.h"
bool ArduCopterFirmwarePlugin::_remapParamNameIntialized = false;
FirmwarePlugin::remapParamNameMajorVersionMap_t ArduCopterFirmwarePlugin::_remapParamName;
APMCopterMode::APMCopterMode(uint32_t mode, bool settable) :
APMCustomMode(mode, settable)
{
QMap<uint32_t,QString> enumToString;
enumToString.insert(STABILIZE, "Stabilize");
enumToString.insert(ACRO, "Acro");
enumToString.insert(ALT_HOLD, "Altitude Hold");
enumToString.insert(AUTO, "Auto");
enumToString.insert(GUIDED, "Guided");
enumToString.insert(LOITER, "Loiter");
enumToString.insert(RTL, "RTL");
enumToString.insert(CIRCLE, "Circle");
enumToString.insert(LAND, "Land");
enumToString.insert(DRIFT, "Drift");
enumToString.insert(SPORT, "Sport");
enumToString.insert(FLIP, "Flip");
enumToString.insert(AUTOTUNE, "Autotune");
enumToString.insert(POS_HOLD, "Position Hold");
enumToString.insert(BRAKE, "Brake");
enumToString.insert(THROW, "Throw");
enumToString.insert(AVOID_ADSB,"Avoid ADSB");
enumToString.insert(GUIDED_NOGPS,"Guided No GPS");
enumToString.insert(SAFE_RTL,"Smart RTL");
setEnumToStringMapping(enumToString);
}
ArduCopterFirmwarePlugin::ArduCopterFirmwarePlugin(void)
{
QList<APMCustomMode> supportedFlightModes;
supportedFlightModes << APMCopterMode(APMCopterMode::STABILIZE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::ACRO ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::ALT_HOLD ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AUTO ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::GUIDED ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::LOITER ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::RTL ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::CIRCLE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::LAND ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::DRIFT ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::SPORT ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::FLIP ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AUTOTUNE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::POS_HOLD ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::BRAKE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::THROW ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AVOID_ADSB,true);
supportedFlightModes << APMCopterMode(APMCopterMode::GUIDED_NOGPS,true);
supportedFlightModes << APMCopterMode(APMCopterMode::SAFE_RTL,true);
setSupportedModes(supportedFlightModes);
if (!_remapParamNameIntialized) {
FirmwarePlugin::remapParamNameMap_t& remapV3_4 = _remapParamName[3][4];
remapV3_4["ATC_ANG_RLL_P"] = QStringLiteral("STB_RLL_P");
remapV3_4["ATC_ANG_PIT_P"] = QStringLiteral("STB_PIT_P");
remapV3_4["ATC_ANG_YAW_P"] = QStringLiteral("STB_YAW_P");
remapV3_4["ATC_RAT_RLL_P"] = QStringLiteral("RATE_RLL_P");
remapV3_4["ATC_RAT_RLL_I"] = QStringLiteral("RATE_RLL_I");
remapV3_4["ATC_RAT_RLL_IMAX"] = QStringLiteral("RATE_RLL_IMAX");
remapV3_4["ATC_RAT_RLL_D"] = QStringLiteral("RATE_RLL_D");
remapV3_4["ATC_RAT_RLL_FILT"] = QStringLiteral("RATE_RLL_FILT_HZ");
remapV3_4["ATC_RAT_PIT_P"] = QStringLiteral("RATE_PIT_P");
remapV3_4["ATC_RAT_PIT_I"] = QStringLiteral("RATE_PIT_I");
remapV3_4["ATC_RAT_PIT_IMAX"] = QStringLiteral("RATE_PIT_IMAX");
remapV3_4["ATC_RAT_PIT_D"] = QStringLiteral("RATE_PIT_D");
remapV3_4["ATC_RAT_PIT_FILT"] = QStringLiteral("RATE_PIT_FILT_HZ");
remapV3_4["ATC_RAT_YAW_P"] = QStringLiteral("RATE_YAW_P");
remapV3_4["ATC_RAT_YAW_I"] = QStringLiteral("RATE_YAW_I");
remapV3_4["ATC_RAT_YAW_IMAX"] = QStringLiteral("RATE_YAW_IMAX");
remapV3_4["ATC_RAT_YAW_D"] = QStringLiteral("RATE_YAW_D");
remapV3_4["ATC_RAT_YAW_FILT"] = QStringLiteral("RATE_YAW_FILT_HZ");
FirmwarePlugin::remapParamNameMap_t& remapV3_5 = _remapParamName[3][5];
remapV3_5["SERVO5_FUNCTION"] = QStringLiteral("RC5_FUNCTION");
remapV3_5["SERVO6_FUNCTION"] = QStringLiteral("RC6_FUNCTION");
remapV3_5["SERVO7_FUNCTION"] = QStringLiteral("RC7_FUNCTION");
remapV3_5["SERVO8_FUNCTION"] = QStringLiteral("RC8_FUNCTION");
remapV3_5["SERVO9_FUNCTION"] = QStringLiteral("RC9_FUNCTION");
remapV3_5["SERVO10_FUNCTION"] = QStringLiteral("RC10_FUNCTION");
remapV3_5["SERVO11_FUNCTION"] = QStringLiteral("RC11_FUNCTION");
remapV3_5["SERVO12_FUNCTION"] = QStringLiteral("RC12_FUNCTION");
remapV3_5["SERVO13_FUNCTION"] = QStringLiteral("RC13_FUNCTION");
remapV3_5["SERVO14_FUNCTION"] = QStringLiteral("RC14_FUNCTION");
remapV3_5["SERVO5_MIN"] = QStringLiteral("RC5_MIN");
remapV3_5["SERVO6_MIN"] = QStringLiteral("RC6_MIN");
remapV3_5["SERVO7_MIN"] = QStringLiteral("RC7_MIN");
remapV3_5["SERVO8_MIN"] = QStringLiteral("RC8_MIN");
remapV3_5["SERVO9_MIN"] = QStringLiteral("RC9_MIN");
remapV3_5["SERVO10_MIN"] = QStringLiteral("RC10_MIN");
remapV3_5["SERVO11_MIN"] = QStringLiteral("RC11_MIN");
remapV3_5["SERVO12_MIN"] = QStringLiteral("RC12_MIN");
remapV3_5["SERVO13_MIN"] = QStringLiteral("RC13_MIN");
remapV3_5["SERVO14_MIN"] = QStringLiteral("RC14_MIN");
remapV3_5["SERVO5_MAX"] = QStringLiteral("RC5_MAX");
remapV3_5["SERVO6_MAX"] = QStringLiteral("RC6_MAX");
remapV3_5["SERVO7_MAX"] = QStringLiteral("RC7_MAX");
remapV3_5["SERVO8_MAX"] = QStringLiteral("RC8_MAX");
remapV3_5["SERVO9_MAX"] = QStringLiteral("RC9_MAX");
remapV3_5["SERVO10_MAX"] = QStringLiteral("RC10_MAX");
remapV3_5["SERVO11_MAX"] = QStringLiteral("RC11_MAX");
remapV3_5["SERVO12_MAX"] = QStringLiteral("RC12_MAX");
remapV3_5["SERVO13_MAX"] = QStringLiteral("RC13_MAX");
remapV3_5["SERVO14_MAX"] = QStringLiteral("RC14_MAX");
remapV3_5["SERVO5_REVERSED"] = QStringLiteral("RC5_REVERSED");
remapV3_5["SERVO6_REVERSED"] = QStringLiteral("RC6_REVERSED");
remapV3_5["SERVO7_REVERSED"] = QStringLiteral("RC7_REVERSED");
remapV3_5["SERVO8_REVERSED"] = QStringLiteral("RC8_REVERSED");
remapV3_5["SERVO9_REVERSED"] = QStringLiteral("RC9_REVERSED");
remapV3_5["SERVO10_REVERSED"] = QStringLiteral("RC10_REVERSED");
remapV3_5["SERVO11_REVERSED"] = QStringLiteral("RC11_REVERSED");
remapV3_5["SERVO12_REVERSED"] = QStringLiteral("RC12_REVERSED");
remapV3_5["SERVO13_REVERSED"] = QStringLiteral("RC13_REVERSED");
remapV3_5["SERVO14_REVERSED"] = QStringLiteral("RC14_REVERSED");
remapV3_5["ARMING_VOLT_MIN"] = QStringLiteral("ARMING_MIN_VOLT");
remapV3_5["ARMING_VOLT2_MIN"] = QStringLiteral("ARMING_MIN_VOLT2");
FirmwarePlugin::remapParamNameMap_t& remapV3_6 = _remapParamName[3][6];
remapV3_6["BATT_AMP_PERVLT"] = QStringLiteral("BATT_AMP_PERVOL");
remapV3_6["BATT2_AMP_PERVLT"] = QStringLiteral("BATT2_AMP_PERVOL");
remapV3_6["BATT_LOW_MAH"] = QStringLiteral("FS_BATT_MAH");
remapV3_6["BATT_LOW_VOLT"] = QStringLiteral("FS_BATT_VOLTAGE");
remapV3_6["BATT_FS_LOW_ACT"] = QStringLiteral("FS_BATT_ENABLE");
remapV3_6["PSC_ACCZ_P"] = QStringLiteral("ACCEL_Z_P");
remapV3_6["PSC_ACCZ_I"] = QStringLiteral("ACCEL_Z_I");
_remapParamNameIntialized = true;
}
}
int ArduCopterFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
// Remapping supports up to 3.5
return majorVersionNumber == 3 ? 5 : Vehicle::versionNotSetValue;
}
void ArduCopterFirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
_setFlightModeAndValidate(vehicle, "Land");
}
bool ArduCopterFirmwarePlugin::multiRotorCoaxialMotors(Vehicle* vehicle)
{
Q_UNUSED(vehicle);
return _coaxialMotors;
}
bool ArduCopterFirmwarePlugin::multiRotorXConfig(Vehicle* vehicle)
{
return vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, "FRAME")->rawValue().toInt() != 0;
}
bool ArduCopterFirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
if (vehicle->isOfflineEditingVehicle()) {
return FirmwarePlugin::vehicleYawsToNextWaypointInMission(vehicle);
} else {
if (vehicle->multiRotor() && vehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"))) {
Fact* yawMode = vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"));
return yawMode && yawMode->rawValue().toInt() != 0;
}
}
return true;
}
<commit_msg>ArduCopterFirmwarePlugin: Add BATT_ARM_VOLT to remapper<commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "ArduCopterFirmwarePlugin.h"
#include "QGCApplication.h"
#include "MissionManager.h"
#include "ParameterManager.h"
bool ArduCopterFirmwarePlugin::_remapParamNameIntialized = false;
FirmwarePlugin::remapParamNameMajorVersionMap_t ArduCopterFirmwarePlugin::_remapParamName;
APMCopterMode::APMCopterMode(uint32_t mode, bool settable) :
APMCustomMode(mode, settable)
{
QMap<uint32_t,QString> enumToString;
enumToString.insert(STABILIZE, "Stabilize");
enumToString.insert(ACRO, "Acro");
enumToString.insert(ALT_HOLD, "Altitude Hold");
enumToString.insert(AUTO, "Auto");
enumToString.insert(GUIDED, "Guided");
enumToString.insert(LOITER, "Loiter");
enumToString.insert(RTL, "RTL");
enumToString.insert(CIRCLE, "Circle");
enumToString.insert(LAND, "Land");
enumToString.insert(DRIFT, "Drift");
enumToString.insert(SPORT, "Sport");
enumToString.insert(FLIP, "Flip");
enumToString.insert(AUTOTUNE, "Autotune");
enumToString.insert(POS_HOLD, "Position Hold");
enumToString.insert(BRAKE, "Brake");
enumToString.insert(THROW, "Throw");
enumToString.insert(AVOID_ADSB,"Avoid ADSB");
enumToString.insert(GUIDED_NOGPS,"Guided No GPS");
enumToString.insert(SAFE_RTL,"Smart RTL");
setEnumToStringMapping(enumToString);
}
ArduCopterFirmwarePlugin::ArduCopterFirmwarePlugin(void)
{
QList<APMCustomMode> supportedFlightModes;
supportedFlightModes << APMCopterMode(APMCopterMode::STABILIZE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::ACRO ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::ALT_HOLD ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AUTO ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::GUIDED ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::LOITER ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::RTL ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::CIRCLE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::LAND ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::DRIFT ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::SPORT ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::FLIP ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AUTOTUNE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::POS_HOLD ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::BRAKE ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::THROW ,true);
supportedFlightModes << APMCopterMode(APMCopterMode::AVOID_ADSB,true);
supportedFlightModes << APMCopterMode(APMCopterMode::GUIDED_NOGPS,true);
supportedFlightModes << APMCopterMode(APMCopterMode::SAFE_RTL,true);
setSupportedModes(supportedFlightModes);
if (!_remapParamNameIntialized) {
FirmwarePlugin::remapParamNameMap_t& remapV3_4 = _remapParamName[3][4];
remapV3_4["ATC_ANG_RLL_P"] = QStringLiteral("STB_RLL_P");
remapV3_4["ATC_ANG_PIT_P"] = QStringLiteral("STB_PIT_P");
remapV3_4["ATC_ANG_YAW_P"] = QStringLiteral("STB_YAW_P");
remapV3_4["ATC_RAT_RLL_P"] = QStringLiteral("RATE_RLL_P");
remapV3_4["ATC_RAT_RLL_I"] = QStringLiteral("RATE_RLL_I");
remapV3_4["ATC_RAT_RLL_IMAX"] = QStringLiteral("RATE_RLL_IMAX");
remapV3_4["ATC_RAT_RLL_D"] = QStringLiteral("RATE_RLL_D");
remapV3_4["ATC_RAT_RLL_FILT"] = QStringLiteral("RATE_RLL_FILT_HZ");
remapV3_4["ATC_RAT_PIT_P"] = QStringLiteral("RATE_PIT_P");
remapV3_4["ATC_RAT_PIT_I"] = QStringLiteral("RATE_PIT_I");
remapV3_4["ATC_RAT_PIT_IMAX"] = QStringLiteral("RATE_PIT_IMAX");
remapV3_4["ATC_RAT_PIT_D"] = QStringLiteral("RATE_PIT_D");
remapV3_4["ATC_RAT_PIT_FILT"] = QStringLiteral("RATE_PIT_FILT_HZ");
remapV3_4["ATC_RAT_YAW_P"] = QStringLiteral("RATE_YAW_P");
remapV3_4["ATC_RAT_YAW_I"] = QStringLiteral("RATE_YAW_I");
remapV3_4["ATC_RAT_YAW_IMAX"] = QStringLiteral("RATE_YAW_IMAX");
remapV3_4["ATC_RAT_YAW_D"] = QStringLiteral("RATE_YAW_D");
remapV3_4["ATC_RAT_YAW_FILT"] = QStringLiteral("RATE_YAW_FILT_HZ");
FirmwarePlugin::remapParamNameMap_t& remapV3_5 = _remapParamName[3][5];
remapV3_5["SERVO5_FUNCTION"] = QStringLiteral("RC5_FUNCTION");
remapV3_5["SERVO6_FUNCTION"] = QStringLiteral("RC6_FUNCTION");
remapV3_5["SERVO7_FUNCTION"] = QStringLiteral("RC7_FUNCTION");
remapV3_5["SERVO8_FUNCTION"] = QStringLiteral("RC8_FUNCTION");
remapV3_5["SERVO9_FUNCTION"] = QStringLiteral("RC9_FUNCTION");
remapV3_5["SERVO10_FUNCTION"] = QStringLiteral("RC10_FUNCTION");
remapV3_5["SERVO11_FUNCTION"] = QStringLiteral("RC11_FUNCTION");
remapV3_5["SERVO12_FUNCTION"] = QStringLiteral("RC12_FUNCTION");
remapV3_5["SERVO13_FUNCTION"] = QStringLiteral("RC13_FUNCTION");
remapV3_5["SERVO14_FUNCTION"] = QStringLiteral("RC14_FUNCTION");
remapV3_5["SERVO5_MIN"] = QStringLiteral("RC5_MIN");
remapV3_5["SERVO6_MIN"] = QStringLiteral("RC6_MIN");
remapV3_5["SERVO7_MIN"] = QStringLiteral("RC7_MIN");
remapV3_5["SERVO8_MIN"] = QStringLiteral("RC8_MIN");
remapV3_5["SERVO9_MIN"] = QStringLiteral("RC9_MIN");
remapV3_5["SERVO10_MIN"] = QStringLiteral("RC10_MIN");
remapV3_5["SERVO11_MIN"] = QStringLiteral("RC11_MIN");
remapV3_5["SERVO12_MIN"] = QStringLiteral("RC12_MIN");
remapV3_5["SERVO13_MIN"] = QStringLiteral("RC13_MIN");
remapV3_5["SERVO14_MIN"] = QStringLiteral("RC14_MIN");
remapV3_5["SERVO5_MAX"] = QStringLiteral("RC5_MAX");
remapV3_5["SERVO6_MAX"] = QStringLiteral("RC6_MAX");
remapV3_5["SERVO7_MAX"] = QStringLiteral("RC7_MAX");
remapV3_5["SERVO8_MAX"] = QStringLiteral("RC8_MAX");
remapV3_5["SERVO9_MAX"] = QStringLiteral("RC9_MAX");
remapV3_5["SERVO10_MAX"] = QStringLiteral("RC10_MAX");
remapV3_5["SERVO11_MAX"] = QStringLiteral("RC11_MAX");
remapV3_5["SERVO12_MAX"] = QStringLiteral("RC12_MAX");
remapV3_5["SERVO13_MAX"] = QStringLiteral("RC13_MAX");
remapV3_5["SERVO14_MAX"] = QStringLiteral("RC14_MAX");
remapV3_5["SERVO5_REVERSED"] = QStringLiteral("RC5_REVERSED");
remapV3_5["SERVO6_REVERSED"] = QStringLiteral("RC6_REVERSED");
remapV3_5["SERVO7_REVERSED"] = QStringLiteral("RC7_REVERSED");
remapV3_5["SERVO8_REVERSED"] = QStringLiteral("RC8_REVERSED");
remapV3_5["SERVO9_REVERSED"] = QStringLiteral("RC9_REVERSED");
remapV3_5["SERVO10_REVERSED"] = QStringLiteral("RC10_REVERSED");
remapV3_5["SERVO11_REVERSED"] = QStringLiteral("RC11_REVERSED");
remapV3_5["SERVO12_REVERSED"] = QStringLiteral("RC12_REVERSED");
remapV3_5["SERVO13_REVERSED"] = QStringLiteral("RC13_REVERSED");
remapV3_5["SERVO14_REVERSED"] = QStringLiteral("RC14_REVERSED");
remapV3_5["ARMING_VOLT_MIN"] = QStringLiteral("ARMING_MIN_VOLT");
remapV3_5["ARMING_VOLT2_MIN"] = QStringLiteral("ARMING_MIN_VOLT2");
FirmwarePlugin::remapParamNameMap_t& remapV3_6 = _remapParamName[3][6];
remapV3_6["BATT_AMP_PERVLT"] = QStringLiteral("BATT_AMP_PERVOL");
remapV3_6["BATT2_AMP_PERVLT"] = QStringLiteral("BATT2_AMP_PERVOL");
remapV3_6["BATT_LOW_MAH"] = QStringLiteral("FS_BATT_MAH");
remapV3_6["BATT_LOW_VOLT"] = QStringLiteral("FS_BATT_VOLTAGE");
remapV3_6["BATT_FS_LOW_ACT"] = QStringLiteral("FS_BATT_ENABLE");
remapV3_6["PSC_ACCZ_P"] = QStringLiteral("ACCEL_Z_P");
remapV3_6["PSC_ACCZ_I"] = QStringLiteral("ACCEL_Z_I");
FirmwarePlugin::remapParamNameMap_t& remapV3_7 = _remapParamName[3][7];
remapV3_7["BATT_ARM_VOLT"] = QStringLiteral("ARMING_VOLT_MIN");
remapV3_7["BATT2_ARM_VOLT"] = QStringLiteral("ARMING_VOLT2_MIN");
_remapParamNameIntialized = true;
}
}
int ArduCopterFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
// Remapping supports up to 3.7
return majorVersionNumber == 3 ? 7 : Vehicle::versionNotSetValue;
}
void ArduCopterFirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
_setFlightModeAndValidate(vehicle, "Land");
}
bool ArduCopterFirmwarePlugin::multiRotorCoaxialMotors(Vehicle* vehicle)
{
Q_UNUSED(vehicle);
return _coaxialMotors;
}
bool ArduCopterFirmwarePlugin::multiRotorXConfig(Vehicle* vehicle)
{
return vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, "FRAME")->rawValue().toInt() != 0;
}
bool ArduCopterFirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
if (vehicle->isOfflineEditingVehicle()) {
return FirmwarePlugin::vehicleYawsToNextWaypointInMission(vehicle);
} else {
if (vehicle->multiRotor() && vehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"))) {
Fact* yawMode = vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"));
return yawMode && yawMode->rawValue().toInt() != 0;
}
}
return true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractSelectedGraph.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkExtractSelectedGraph.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataArray.h"
#include "vtkEventForwarderCommand.h"
#include "vtkExtractSelection.h"
#include "vtkGraph.h"
#include "vtkGraphIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSignedCharArray.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include <vtksys/stl/map>
vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.13");
vtkStandardNewMacro(vtkExtractSelectedGraph);
vtkExtractSelectedGraph::vtkExtractSelectedGraph()
{
this->SetNumberOfInputPorts(2);
this->RemoveIsolatedVertices = true;
}
vtkExtractSelectedGraph::~vtkExtractSelectedGraph()
{
}
int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)
{
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAbstractGraph");
return 1;
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
return 1;
}
return 0;
}
void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(1, in);
}
int vtkExtractSelectedGraph::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkAbstractGraph* input = vtkAbstractGraph::GetData(inputVector[0]);
vtkSelection* selection = vtkSelection::GetData(inputVector[1]);
// If there is nothing in the list, there is nothing to select.
vtkAbstractArray* list = selection->GetSelectionList();
if (!list || list->GetNumberOfTuples() == 0)
{
return 1;
}
bool inverse = false;
if(selection->GetProperties()->Has(vtkSelection::INVERSE()))
{
inverse = selection->GetProperties()->Get(vtkSelection::INVERSE());
}
// If it is a selection with multiple parts, find a point or cell
// child selection, with preference to points.
if (selection->GetContentType() == vtkSelection::SELECTIONS)
{
vtkSelection* child = 0;
for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)
{
vtkSelection* cur = selection->GetChild(i);
if (cur->GetFieldType() == vtkSelection::POINT)
{
child = cur;
break;
}
else if (cur->GetFieldType() == vtkSelection::CELL)
{
child = cur;
}
}
selection = child;
}
// Convert the selection to an INDICES selection
vtkSelection* indexSelection =
vtkConvertSelection::ToIndexSelection(selection, input);
if (!indexSelection)
{
vtkErrorMacro("Selection conversion to INDICES failed.");
indexSelection->Delete();
return 0;
}
vtkAbstractArray* arr = indexSelection->GetSelectionList();
if (arr == NULL)
{
vtkErrorMacro("Selection list not found.");
return 0;
}
vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);
if (selectArr == NULL)
{
vtkErrorMacro("Selection list must be of type vtkIdTypeArray.");
return 0;
}
vtkIdType selectSize = selectArr->GetNumberOfTuples();
vtkGraph* output = vtkGraph::GetData(outputVector);
output->SetDirected(input->GetDirected());
output->GetFieldData()->PassData(input->GetFieldData());
if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) &&
selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::CELL)
{
//
// Edge selection
//
// Copy all vertices
output->SetNumberOfVertices(input->GetNumberOfVertices());
vtkCellData* inputEdgeData = input->GetEdgeData();
vtkCellData* outputEdgeData = output->GetEdgeData();
outputEdgeData->CopyAllocate(inputEdgeData);
// Copy unselected edges
if(inverse)
{
for (vtkIdType i = 0; i < inputEdgeData->GetNumberOfTuples(); i++)
{
if(selectArr->LookupValue(i) < 0 )
{
vtkIdType source = input->GetSourceVertex(i);
vtkIdType target = input->GetTargetVertex(i);
vtkIdType outputEdge = output->AddEdge(source, target);
outputEdgeData->CopyData(inputEdgeData, i, outputEdge);
}
}
}
// Copy selected edges
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputEdge = selectArr->GetValue(i);
if (inputEdge < input->GetNumberOfEdges())
{
vtkIdType source = input->GetSourceVertex(inputEdge);
vtkIdType target = input->GetTargetVertex(inputEdge);
vtkIdType outputEdge = output->AddEdge(source, target);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
}
// Remove isolated vertices
if (this->RemoveIsolatedVertices)
{
output->GetVertexData()->DeepCopy(input->GetVertexData());
output->GetPoints()->DeepCopy(input->GetPoints());
vtkIdTypeArray* isolated = vtkIdTypeArray::New();
for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)
{
if (output->GetDegree(i) == 0)
{
isolated->InsertNextValue(i);
}
}
output->RemoveVertices(isolated->GetPointer(0), isolated->GetNumberOfTuples());
isolated->Delete();
}
else
{
output->GetVertexData()->PassData(input->GetVertexData());
output->GetPoints()->ShallowCopy(input->GetPoints());
}
}
else
{
//
// Vertex selection
//
double pt[3];
vtkPoints* inputPoints = input->GetPoints();
vtkPoints* outputPoints = vtkPoints::New();
vtkPointData* inputVertexData = input->GetVertexData();
vtkPointData* outputVertexData = output->GetVertexData();
outputVertexData->CopyAllocate(inputVertexData);
vtksys_stl::map<vtkIdType, vtkIdType> idMap;
// Copy unselected vertices
if(inverse)
{
for (vtkIdType i = 0; i < inputVertexData->GetNumberOfTuples(); i++)
{
if(selectArr->LookupValue(i) < 0)
{
vtkIdType outputVertex = output->AddVertex();
outputVertexData->CopyData(inputVertexData, i, outputVertex);
idMap[i] = outputVertex;
inputPoints->GetPoint(i, pt);
outputPoints->InsertNextPoint(pt);
}
}
}
// Copy selected vertices
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputVertex = selectArr->GetValue(i);
if (inputVertex < input->GetNumberOfVertices())
{
vtkIdType outputVertex = output->AddVertex();
outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);
idMap[inputVertex] = outputVertex;
inputPoints->GetPoint(inputVertex, pt);
outputPoints->InsertNextPoint(pt);
}
}
}
output->SetPoints(outputPoints);
outputPoints->Delete();
// Make a directed shallow copy of the graph so GetOutEdges()
// returns every edge no more than once.
vtkAbstractGraph* copy = input;
bool madeCopy = false;
if (vtkGraph::SafeDownCast(input) && !input->GetDirected())
{
copy = vtkGraph::New();
copy->ShallowCopy(input);
vtkGraph::SafeDownCast(copy)->SetDirected(true);
madeCopy = true;
}
vtkCellData* inputEdgeData = input->GetEdgeData();
vtkCellData* outputEdgeData = output->GetEdgeData();
outputEdgeData->CopyAllocate(inputEdgeData);
vtkGraphIdList* edgeList = vtkGraphIdList::New();
// Copy any edges that connect UNSELECTED vertices
if(inverse)
{
vtksys_stl::map<vtkIdType, vtkIdType>::iterator mapIter = idMap.begin();
while(mapIter != idMap.end())
{
vtkIdType inputVertex = mapIter->first;
vtkIdType outputVertex = mapIter->second;
copy->GetOutEdges(inputVertex, edgeList);
for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)
{
vtkIdType inputEdge = edgeList->GetId(j);
vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
if (idMap.count(oppInputVertex) > 0)
{
vtkIdType oppOutputVertex = idMap[oppInputVertex];
vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
mapIter++;
}
}
// Copy any edges that connect SELECTED vertices
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputVertex = selectArr->GetValue(i);
if (idMap.count(inputVertex) > 0)
{
vtkIdType outputVertex = idMap[inputVertex];
copy->GetOutEdges(inputVertex, edgeList);
for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)
{
vtkIdType inputEdge = edgeList->GetId(j);
vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
if (idMap.count(oppInputVertex) > 0)
{
vtkIdType oppOutputVertex = idMap[oppInputVertex];
vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
}
}
}
edgeList->Delete();
// Clean up
if (madeCopy)
{
copy->Delete();
}
}
// Clean up
output->Squeeze();
indexSelection->Delete();
return 1;
}
void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "RemoveIsolatedVertices: "
<< (this->RemoveIsolatedVertices ? "on" : "off") << endl;
}
<commit_msg>COMP: Fix int to bool conversion warning.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractSelectedGraph.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkExtractSelectedGraph.h"
#include "vtkCellData.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataArray.h"
#include "vtkEventForwarderCommand.h"
#include "vtkExtractSelection.h"
#include "vtkGraph.h"
#include "vtkGraphIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkSelection.h"
#include "vtkSignedCharArray.h"
#include "vtkSmartPointer.h"
#include "vtkStringArray.h"
#include <vtksys/stl/map>
vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.14");
vtkStandardNewMacro(vtkExtractSelectedGraph);
vtkExtractSelectedGraph::vtkExtractSelectedGraph()
{
this->SetNumberOfInputPorts(2);
this->RemoveIsolatedVertices = true;
}
vtkExtractSelectedGraph::~vtkExtractSelectedGraph()
{
}
int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)
{
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkAbstractGraph");
return 1;
}
else if (port == 1)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection");
return 1;
}
return 0;
}
void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)
{
this->SetInputConnection(1, in);
}
int vtkExtractSelectedGraph::RequestData(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector)
{
vtkAbstractGraph* input = vtkAbstractGraph::GetData(inputVector[0]);
vtkSelection* selection = vtkSelection::GetData(inputVector[1]);
// If there is nothing in the list, there is nothing to select.
vtkAbstractArray* list = selection->GetSelectionList();
if (!list || list->GetNumberOfTuples() == 0)
{
return 1;
}
int inverse = 0;
if(selection->GetProperties()->Has(vtkSelection::INVERSE()))
{
inverse = selection->GetProperties()->Get(vtkSelection::INVERSE());
}
// If it is a selection with multiple parts, find a point or cell
// child selection, with preference to points.
if (selection->GetContentType() == vtkSelection::SELECTIONS)
{
vtkSelection* child = 0;
for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)
{
vtkSelection* cur = selection->GetChild(i);
if (cur->GetFieldType() == vtkSelection::POINT)
{
child = cur;
break;
}
else if (cur->GetFieldType() == vtkSelection::CELL)
{
child = cur;
}
}
selection = child;
}
// Convert the selection to an INDICES selection
vtkSelection* indexSelection =
vtkConvertSelection::ToIndexSelection(selection, input);
if (!indexSelection)
{
vtkErrorMacro("Selection conversion to INDICES failed.");
indexSelection->Delete();
return 0;
}
vtkAbstractArray* arr = indexSelection->GetSelectionList();
if (arr == NULL)
{
vtkErrorMacro("Selection list not found.");
return 0;
}
vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);
if (selectArr == NULL)
{
vtkErrorMacro("Selection list must be of type vtkIdTypeArray.");
return 0;
}
vtkIdType selectSize = selectArr->GetNumberOfTuples();
vtkGraph* output = vtkGraph::GetData(outputVector);
output->SetDirected(input->GetDirected());
output->GetFieldData()->PassData(input->GetFieldData());
if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) &&
selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::CELL)
{
//
// Edge selection
//
// Copy all vertices
output->SetNumberOfVertices(input->GetNumberOfVertices());
vtkCellData* inputEdgeData = input->GetEdgeData();
vtkCellData* outputEdgeData = output->GetEdgeData();
outputEdgeData->CopyAllocate(inputEdgeData);
// Copy unselected edges
if(inverse)
{
for (vtkIdType i = 0; i < inputEdgeData->GetNumberOfTuples(); i++)
{
if(selectArr->LookupValue(i) < 0 )
{
vtkIdType source = input->GetSourceVertex(i);
vtkIdType target = input->GetTargetVertex(i);
vtkIdType outputEdge = output->AddEdge(source, target);
outputEdgeData->CopyData(inputEdgeData, i, outputEdge);
}
}
}
// Copy selected edges
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputEdge = selectArr->GetValue(i);
if (inputEdge < input->GetNumberOfEdges())
{
vtkIdType source = input->GetSourceVertex(inputEdge);
vtkIdType target = input->GetTargetVertex(inputEdge);
vtkIdType outputEdge = output->AddEdge(source, target);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
}
// Remove isolated vertices
if (this->RemoveIsolatedVertices)
{
output->GetVertexData()->DeepCopy(input->GetVertexData());
output->GetPoints()->DeepCopy(input->GetPoints());
vtkIdTypeArray* isolated = vtkIdTypeArray::New();
for (vtkIdType i = 0; i < output->GetNumberOfVertices(); i++)
{
if (output->GetDegree(i) == 0)
{
isolated->InsertNextValue(i);
}
}
output->RemoveVertices(isolated->GetPointer(0), isolated->GetNumberOfTuples());
isolated->Delete();
}
else
{
output->GetVertexData()->PassData(input->GetVertexData());
output->GetPoints()->ShallowCopy(input->GetPoints());
}
}
else
{
//
// Vertex selection
//
double pt[3];
vtkPoints* inputPoints = input->GetPoints();
vtkPoints* outputPoints = vtkPoints::New();
vtkPointData* inputVertexData = input->GetVertexData();
vtkPointData* outputVertexData = output->GetVertexData();
outputVertexData->CopyAllocate(inputVertexData);
vtksys_stl::map<vtkIdType, vtkIdType> idMap;
// Copy unselected vertices
if(inverse)
{
for (vtkIdType i = 0; i < inputVertexData->GetNumberOfTuples(); i++)
{
if(selectArr->LookupValue(i) < 0)
{
vtkIdType outputVertex = output->AddVertex();
outputVertexData->CopyData(inputVertexData, i, outputVertex);
idMap[i] = outputVertex;
inputPoints->GetPoint(i, pt);
outputPoints->InsertNextPoint(pt);
}
}
}
// Copy selected vertices
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputVertex = selectArr->GetValue(i);
if (inputVertex < input->GetNumberOfVertices())
{
vtkIdType outputVertex = output->AddVertex();
outputVertexData->CopyData(inputVertexData, inputVertex, outputVertex);
idMap[inputVertex] = outputVertex;
inputPoints->GetPoint(inputVertex, pt);
outputPoints->InsertNextPoint(pt);
}
}
}
output->SetPoints(outputPoints);
outputPoints->Delete();
// Make a directed shallow copy of the graph so GetOutEdges()
// returns every edge no more than once.
vtkAbstractGraph* copy = input;
bool madeCopy = false;
if (vtkGraph::SafeDownCast(input) && !input->GetDirected())
{
copy = vtkGraph::New();
copy->ShallowCopy(input);
vtkGraph::SafeDownCast(copy)->SetDirected(true);
madeCopy = true;
}
vtkCellData* inputEdgeData = input->GetEdgeData();
vtkCellData* outputEdgeData = output->GetEdgeData();
outputEdgeData->CopyAllocate(inputEdgeData);
vtkGraphIdList* edgeList = vtkGraphIdList::New();
// Copy any edges that connect UNSELECTED vertices
if(inverse)
{
vtksys_stl::map<vtkIdType, vtkIdType>::iterator mapIter = idMap.begin();
while(mapIter != idMap.end())
{
vtkIdType inputVertex = mapIter->first;
vtkIdType outputVertex = mapIter->second;
copy->GetOutEdges(inputVertex, edgeList);
for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)
{
vtkIdType inputEdge = edgeList->GetId(j);
vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
if (idMap.count(oppInputVertex) > 0)
{
vtkIdType oppOutputVertex = idMap[oppInputVertex];
vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
mapIter++;
}
}
// Copy any edges that connect SELECTED vertices
else
{
for (vtkIdType i = 0; i < selectSize; i++)
{
vtkIdType inputVertex = selectArr->GetValue(i);
if (idMap.count(inputVertex) > 0)
{
vtkIdType outputVertex = idMap[inputVertex];
copy->GetOutEdges(inputVertex, edgeList);
for (vtkIdType j = 0; j < edgeList->GetNumberOfIds(); j++)
{
vtkIdType inputEdge = edgeList->GetId(j);
vtkIdType oppInputVertex = input->GetOppositeVertex(inputEdge, inputVertex);
if (idMap.count(oppInputVertex) > 0)
{
vtkIdType oppOutputVertex = idMap[oppInputVertex];
vtkIdType outputEdge = output->AddEdge(outputVertex, oppOutputVertex);
outputEdgeData->CopyData(inputEdgeData, inputEdge, outputEdge);
}
}
}
}
}
edgeList->Delete();
// Clean up
if (madeCopy)
{
copy->Delete();
}
}
// Clean up
output->Squeeze();
indexSelection->Delete();
return 1;
}
void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "RemoveIsolatedVertices: "
<< (this->RemoveIsolatedVertices ? "on" : "off") << endl;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: syslocale.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-06-16 10:30:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef GCC
#pragma hdrstop
#endif
#include "syslocale.hxx"
#ifndef _SVT_BROADCAST_HXX
#include <broadcast.hxx>
#endif
#ifndef _SVT_LISTENER_HXX
#include <listener.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALEOPTIONS_HXX
#include "syslocaleoptions.hxx"
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
using namespace osl;
using namespace com::sun::star;
SvtSysLocale_Impl* SvtSysLocale::pImpl = NULL;
sal_Int32 SvtSysLocale::nRefCount = 0;
class SvtSysLocale_Impl : public SvtListener
{
friend class SvtSysLocale;
SvtSysLocaleOptions aSysLocaleOptions;
LocaleDataWrapper* pLocaleData;
CharClass* pCharClass;
public:
SvtSysLocale_Impl();
virtual ~SvtSysLocale_Impl();
virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint );
};
// -----------------------------------------------------------------------
SvtSysLocale_Impl::SvtSysLocale_Impl()
{
const lang::Locale& rLocale = Application::GetSettings().GetLocale();
pLocaleData = new LocaleDataWrapper(
::comphelper::getProcessServiceFactory(), rLocale );
pCharClass = new CharClass(
::comphelper::getProcessServiceFactory(), rLocale );
aSysLocaleOptions.AddListener( *this );
}
SvtSysLocale_Impl::~SvtSysLocale_Impl()
{
aSysLocaleOptions.RemoveListener( *this );
delete pCharClass;
delete pLocaleData;
}
void SvtSysLocale_Impl::Notify( SvtBroadcaster& rBC, const SfxHint& rHint )
{
const SfxSimpleHint* p = PTR_CAST( SfxSimpleHint, &rHint );
if( p && (p->GetId() & SYSLOCALEOPTIONS_HINT_LOCALE) )
{
MutexGuard aGuard( SvtSysLocale::GetMutex() );
const lang::Locale& rLocale = Application::GetSettings().GetLocale();
pLocaleData->setLocale( rLocale );
pCharClass->setLocale( rLocale );
}
}
// ====================================================================
SvtSysLocale::SvtSysLocale()
{
MutexGuard aGuard( GetMutex() );
if ( !pImpl )
pImpl = new SvtSysLocale_Impl;
++nRefCount;
}
SvtSysLocale::~SvtSysLocale()
{
MutexGuard aGuard( GetMutex() );
if ( !--nRefCount )
{
delete pImpl;
pImpl = NULL;
}
}
// static
Mutex& SvtSysLocale::GetMutex()
{
static Mutex* pMutex = NULL;
if( !pMutex )
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if( !pMutex )
{
static Mutex aMutex;
pMutex = &aMutex;
}
}
return *pMutex;
}
const LocaleDataWrapper& SvtSysLocale::GetLocaleData() const
{
return *(pImpl->pLocaleData);
}
const LocaleDataWrapper* SvtSysLocale::GetLocaleDataPtr() const
{
return pImpl->pLocaleData;
}
const CharClass& SvtSysLocale::GetCharClass() const
{
return *(pImpl->pCharClass);
}
const CharClass* SvtSysLocale::GetCharClassPtr() const
{
return pImpl->pCharClass;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.474); FILE MERGED 2005/09/05 14:54:22 rt 1.4.474.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: syslocale.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:52:21 $
*
* 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 GCC
#pragma hdrstop
#endif
#include "syslocale.hxx"
#ifndef _SVT_BROADCAST_HXX
#include <broadcast.hxx>
#endif
#ifndef _SVT_LISTENER_HXX
#include <listener.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX
#include <smplhint.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SYSLOCALEOPTIONS_HXX
#include "syslocaleoptions.hxx"
#endif
#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX
#include <unotools/localedatawrapper.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
using namespace osl;
using namespace com::sun::star;
SvtSysLocale_Impl* SvtSysLocale::pImpl = NULL;
sal_Int32 SvtSysLocale::nRefCount = 0;
class SvtSysLocale_Impl : public SvtListener
{
friend class SvtSysLocale;
SvtSysLocaleOptions aSysLocaleOptions;
LocaleDataWrapper* pLocaleData;
CharClass* pCharClass;
public:
SvtSysLocale_Impl();
virtual ~SvtSysLocale_Impl();
virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint );
};
// -----------------------------------------------------------------------
SvtSysLocale_Impl::SvtSysLocale_Impl()
{
const lang::Locale& rLocale = Application::GetSettings().GetLocale();
pLocaleData = new LocaleDataWrapper(
::comphelper::getProcessServiceFactory(), rLocale );
pCharClass = new CharClass(
::comphelper::getProcessServiceFactory(), rLocale );
aSysLocaleOptions.AddListener( *this );
}
SvtSysLocale_Impl::~SvtSysLocale_Impl()
{
aSysLocaleOptions.RemoveListener( *this );
delete pCharClass;
delete pLocaleData;
}
void SvtSysLocale_Impl::Notify( SvtBroadcaster& rBC, const SfxHint& rHint )
{
const SfxSimpleHint* p = PTR_CAST( SfxSimpleHint, &rHint );
if( p && (p->GetId() & SYSLOCALEOPTIONS_HINT_LOCALE) )
{
MutexGuard aGuard( SvtSysLocale::GetMutex() );
const lang::Locale& rLocale = Application::GetSettings().GetLocale();
pLocaleData->setLocale( rLocale );
pCharClass->setLocale( rLocale );
}
}
// ====================================================================
SvtSysLocale::SvtSysLocale()
{
MutexGuard aGuard( GetMutex() );
if ( !pImpl )
pImpl = new SvtSysLocale_Impl;
++nRefCount;
}
SvtSysLocale::~SvtSysLocale()
{
MutexGuard aGuard( GetMutex() );
if ( !--nRefCount )
{
delete pImpl;
pImpl = NULL;
}
}
// static
Mutex& SvtSysLocale::GetMutex()
{
static Mutex* pMutex = NULL;
if( !pMutex )
{
MutexGuard aGuard( Mutex::getGlobalMutex() );
if( !pMutex )
{
static Mutex aMutex;
pMutex = &aMutex;
}
}
return *pMutex;
}
const LocaleDataWrapper& SvtSysLocale::GetLocaleData() const
{
return *(pImpl->pLocaleData);
}
const LocaleDataWrapper* SvtSysLocale::GetLocaleDataPtr() const
{
return pImpl->pLocaleData;
}
const CharClass& SvtSysLocale::GetCharClass() const
{
return *(pImpl->pCharClass);
}
const CharClass* SvtSysLocale::GetCharClassPtr() const
{
return pImpl->pCharClass;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: connpoolsettings.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:13:13 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#ifndef _OFFAPP_CONNPOOLSETTINGS_HXX_
#include "connpoolsettings.hxx"
#endif
//........................................................................
namespace offapp
{
//........................................................................
//====================================================================
//= DriverPooling
//====================================================================
//--------------------------------------------------------------------
DriverPooling::DriverPooling()
:bEnabled(sal_False)
,nTimeoutSeconds(0)
{
}
//--------------------------------------------------------------------
DriverPooling::DriverPooling( const String& _rName, sal_Bool _bEnabled, const sal_Int32 _nTimeout )
:sName(_rName)
,bEnabled(_bEnabled)
,nTimeoutSeconds(_nTimeout)
{
}
//--------------------------------------------------------------------
sal_Bool DriverPooling::operator == (const DriverPooling& _rR) const
{
return (sName == _rR.sName)
&& (bEnabled == _rR.bEnabled)
&& (nTimeoutSeconds == _rR.nTimeoutSeconds);
}
//====================================================================
//= DriverPoolingSettings
//====================================================================
//--------------------------------------------------------------------
DriverPoolingSettings::DriverPoolingSettings()
{
}
//====================================================================
//= DriverPoolingSettingsItem
//====================================================================
TYPEINIT1( DriverPoolingSettingsItem, SfxPoolItem )
//--------------------------------------------------------------------
DriverPoolingSettingsItem::DriverPoolingSettingsItem( sal_uInt16 _nId, const DriverPoolingSettings _rSettings )
:SfxPoolItem(_nId)
,m_aSettings(_rSettings)
{
}
//--------------------------------------------------------------------
int DriverPoolingSettingsItem::operator==( const SfxPoolItem& _rCompare ) const
{
const DriverPoolingSettingsItem* pItem = PTR_CAST(DriverPoolingSettingsItem, &_rCompare);
if (!pItem)
return sal_False;
if (m_aSettings.size() != pItem->m_aSettings.size())
return sal_False;
DriverPoolingSettings::const_iterator aOwn = m_aSettings.begin();
DriverPoolingSettings::const_iterator aOwnEnd = m_aSettings.end();
DriverPoolingSettings::const_iterator aForeign = pItem->m_aSettings.begin();
while (aOwn < aOwnEnd)
{
if (*aOwn != *aForeign)
return sal_False;
++aForeign;
++aOwn;
}
return sal_True;
}
//--------------------------------------------------------------------
SfxPoolItem* DriverPoolingSettingsItem::Clone( SfxItemPool * ) const
{
return new DriverPoolingSettingsItem(Which(), m_aSettings);
}
//--------------------------------------------------------------------
//........................................................................
} // namespace offapp
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.6.732); FILE MERGED 2008/04/01 12:48:07 thb 1.6.732.2: #i85898# Stripping all external header guards 2008/03/31 14:19:21 rt 1.6.732.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: connpoolsettings.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include "connpoolsettings.hxx"
//........................................................................
namespace offapp
{
//........................................................................
//====================================================================
//= DriverPooling
//====================================================================
//--------------------------------------------------------------------
DriverPooling::DriverPooling()
:bEnabled(sal_False)
,nTimeoutSeconds(0)
{
}
//--------------------------------------------------------------------
DriverPooling::DriverPooling( const String& _rName, sal_Bool _bEnabled, const sal_Int32 _nTimeout )
:sName(_rName)
,bEnabled(_bEnabled)
,nTimeoutSeconds(_nTimeout)
{
}
//--------------------------------------------------------------------
sal_Bool DriverPooling::operator == (const DriverPooling& _rR) const
{
return (sName == _rR.sName)
&& (bEnabled == _rR.bEnabled)
&& (nTimeoutSeconds == _rR.nTimeoutSeconds);
}
//====================================================================
//= DriverPoolingSettings
//====================================================================
//--------------------------------------------------------------------
DriverPoolingSettings::DriverPoolingSettings()
{
}
//====================================================================
//= DriverPoolingSettingsItem
//====================================================================
TYPEINIT1( DriverPoolingSettingsItem, SfxPoolItem )
//--------------------------------------------------------------------
DriverPoolingSettingsItem::DriverPoolingSettingsItem( sal_uInt16 _nId, const DriverPoolingSettings _rSettings )
:SfxPoolItem(_nId)
,m_aSettings(_rSettings)
{
}
//--------------------------------------------------------------------
int DriverPoolingSettingsItem::operator==( const SfxPoolItem& _rCompare ) const
{
const DriverPoolingSettingsItem* pItem = PTR_CAST(DriverPoolingSettingsItem, &_rCompare);
if (!pItem)
return sal_False;
if (m_aSettings.size() != pItem->m_aSettings.size())
return sal_False;
DriverPoolingSettings::const_iterator aOwn = m_aSettings.begin();
DriverPoolingSettings::const_iterator aOwnEnd = m_aSettings.end();
DriverPoolingSettings::const_iterator aForeign = pItem->m_aSettings.begin();
while (aOwn < aOwnEnd)
{
if (*aOwn != *aForeign)
return sal_False;
++aForeign;
++aOwn;
}
return sal_True;
}
//--------------------------------------------------------------------
SfxPoolItem* DriverPoolingSettingsItem::Clone( SfxItemPool * ) const
{
return new DriverPoolingSettingsItem(Which(), m_aSettings);
}
//--------------------------------------------------------------------
//........................................................................
} // namespace offapp
//........................................................................
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2012 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <znc/Buffer.h>
#include <znc/znc.h>
#include <znc/Client.h>
#include <znc/User.h>
CBufLine::CBufLine(const CString& sFormat, const CString& sText, const timeval* ts) {
m_sFormat = sFormat;
m_sText = sText;
if (ts == NULL)
UpdateTime();
else
m_time = *ts;
}
CBufLine::~CBufLine() {}
void CBufLine::UpdateTime() {
if (0 == gettimeofday(&m_time, NULL)) {
return;
}
time(&m_time.tv_sec);
m_time.tv_usec = 0;
}
CString CBufLine::GetLine(const CClient& Client, const MCString& msParams) const {
MCString msThisParams = msParams;
if (Client.HasServerTime()) {
msThisParams["text"] = m_sText;
CString sStr = CString::NamedFormat(m_sFormat, msThisParams);
CString s_msec(m_time.tv_usec / 1000);
while (s_msec.length() < 3) {
s_msec = "0" + s_msec;
}
// TODO support message-tags properly
return "@time=" + CString(m_time.tv_sec) + "." + s_msec + " " + sStr;
} else {
msThisParams["text"] = Client.GetUser()->AddTimestamp(m_time.tv_sec, m_sText);
return CString::NamedFormat(m_sFormat, msThisParams);
}
}
CBuffer::CBuffer(unsigned int uLineCount) {
m_uLineCount = uLineCount;
}
CBuffer::~CBuffer() {}
CBuffer::size_type CBuffer::AddLine(const CString& sFormat, const CString& sText, const timeval* ts) {
if (!m_uLineCount) {
return 0;
}
while (size() >= m_uLineCount) {
erase(begin());
}
push_back(CBufLine(sFormat, sText, ts));
return size();
}
CBuffer::size_type CBuffer::UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat().compare(0, sMatch.length(), sMatch) == 0) {
it->SetFormat(sFormat);
it->SetText(sText);
it->UpdateTime();
return size();
}
}
return AddLine(sFormat, sText);
}
CBuffer::size_type CBuffer::UpdateExactLine(const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat() == sFormat && it->GetText() == sText) {
return size();
}
}
return AddLine(sFormat, sText);
}
const CBufLine& CBuffer::GetBufLine(unsigned int uIdx) const {
return (*this)[uIdx];
}
CString CBuffer::GetLine(size_type uIdx, const CClient& Client, const MCString& msParams) const {
return (*this)[uIdx].GetLine(Client, msParams);
}
bool CBuffer::SetLineCount(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) {
return false;
}
m_uLineCount = u;
// We may need to shrink the buffer if the allowed size got smaller
while (size() > m_uLineCount) {
erase(begin());
}
return true;
}
<commit_msg>Fix fred's build.<commit_after>/*
* Copyright (C) 2004-2012 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <znc/Buffer.h>
#include <znc/znc.h>
#include <znc/Client.h>
#include <znc/User.h>
CBufLine::CBufLine(const CString& sFormat, const CString& sText, const timeval* ts) {
m_sFormat = sFormat;
m_sText = sText;
if (ts == NULL)
UpdateTime();
else
m_time = *ts;
}
CBufLine::~CBufLine() {}
void CBufLine::UpdateTime() {
if (0 == gettimeofday(&m_time, NULL)) {
return;
}
m_time.tv_sec = time(NULL);
m_time.tv_usec = 0;
}
CString CBufLine::GetLine(const CClient& Client, const MCString& msParams) const {
MCString msThisParams = msParams;
if (Client.HasServerTime()) {
msThisParams["text"] = m_sText;
CString sStr = CString::NamedFormat(m_sFormat, msThisParams);
CString s_msec(m_time.tv_usec / 1000);
while (s_msec.length() < 3) {
s_msec = "0" + s_msec;
}
// TODO support message-tags properly
return "@time=" + CString(m_time.tv_sec) + "." + s_msec + " " + sStr;
} else {
msThisParams["text"] = Client.GetUser()->AddTimestamp(m_time.tv_sec, m_sText);
return CString::NamedFormat(m_sFormat, msThisParams);
}
}
CBuffer::CBuffer(unsigned int uLineCount) {
m_uLineCount = uLineCount;
}
CBuffer::~CBuffer() {}
CBuffer::size_type CBuffer::AddLine(const CString& sFormat, const CString& sText, const timeval* ts) {
if (!m_uLineCount) {
return 0;
}
while (size() >= m_uLineCount) {
erase(begin());
}
push_back(CBufLine(sFormat, sText, ts));
return size();
}
CBuffer::size_type CBuffer::UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat().compare(0, sMatch.length(), sMatch) == 0) {
it->SetFormat(sFormat);
it->SetText(sText);
it->UpdateTime();
return size();
}
}
return AddLine(sFormat, sText);
}
CBuffer::size_type CBuffer::UpdateExactLine(const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat() == sFormat && it->GetText() == sText) {
return size();
}
}
return AddLine(sFormat, sText);
}
const CBufLine& CBuffer::GetBufLine(unsigned int uIdx) const {
return (*this)[uIdx];
}
CString CBuffer::GetLine(size_type uIdx, const CClient& Client, const MCString& msParams) const {
return (*this)[uIdx].GetLine(Client, msParams);
}
bool CBuffer::SetLineCount(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) {
return false;
}
m_uLineCount = u;
// We may need to shrink the buffer if the allowed size got smaller
while (size() > m_uLineCount) {
erase(begin());
}
return true;
}
<|endoftext|>
|
<commit_before>// model.cpp : interface of the CModel class
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// CModel
#include <string>
#include <vector>
#include "copasi.h"
#include "CGlobals.h"
#include "CModel.h"
#include "CCompartment.h"
#include "tnt/luX.h"
CModel::CModel()
{
mCompartments = NULL;
mSteps = NULL;
mMoieties = NULL;
initialize();
}
void CModel::initialize()
{
if ( !mCompartments ) mCompartments = new CCopasiVector < CCompartment >;
if ( !mSteps ) mSteps = new CCopasiVector < CStep >;
if ( !mMoieties ) mMoieties = new CCopasiVector < CMoiety >;
}
CModel::~CModel()
{
cleanup();
}
void CModel::cleanup()
{
if ( mCompartments )
{
mCompartments->cleanup();
mCompartments = NULL;
}
if ( mSteps )
{
mSteps->cleanup();
mSteps = NULL;
}
if ( mMoieties )
{
mMoieties->cleanup();
mMoieties = NULL;
}
}
C_INT32 CModel::load(CReadConfig & configBuffer)
{
C_INT32 Size = 0;
C_INT32 Fail = 0;
C_INT32 i;
initialize();
// For old Versions we need must read the list of Metabolites beforehand
if (configBuffer.getVersion() < "4")
{
if (Fail = configBuffer.getVariable("TotalMetabolites", "C_INT32",
&Size, CReadConfig::LOOP))
return Fail;
if (Fail = Copasi.OldMetabolites.load(configBuffer, Size))
return Fail;
}
if (Fail = configBuffer.getVariable("Title", "string", &mTitle,
CReadConfig::LOOP))
return Fail;
if (Fail = configBuffer.getVariable("Comments", "multiline", &mComments,
CReadConfig::SEARCH))
return Fail;
if (Fail = configBuffer.getVariable("TotalCompartments", "C_INT32", &Size,
CReadConfig::LOOP))
return Fail;
if (Fail = mCompartments->load(configBuffer, Size)) return Fail;
if (configBuffer.getVersion() < "4")
{
// Create the correct compartment / metabolite relationships
CMetab Metabolite;
for (i = 0; i < Copasi.OldMetabolites.size(); i++)
{
Metabolite = Copasi.OldMetabolites[i];
(*mCompartments)[Copasi.OldMetabolites[i].getIndex()].
addMetabolite(Metabolite);
}
}
// Create a vector of pointers to all metabolites.
// Note, the metabolites physically exist in the compartments.
for (i = 0; i < mCompartments->size(); i++)
for (C_INT32 j = 0; j < (*mCompartments)[i].metabolites().size(); j++)
mMetabolites.push_back(&(*mCompartments)[i].metabolites()[j]);
if (Fail = Copasi.FunctionDB.load(configBuffer)) return Fail;
if (Fail = configBuffer.getVariable("TotalSteps", "C_INT32", &Size,
CReadConfig::LOOP))
return Fail;
if (Fail = mSteps->load(configBuffer, Size)) return Fail;
// We must postprocess the steps for old file versions
if (configBuffer.getVersion() < "4")
for (i = 0; i < mSteps->size(); i++)
(*mSteps)[i].old2New(mMetabolites);
for (i = 0; i < mSteps->size(); i++)
(*mSteps)[i].compile(mCompartments);
return Fail;
}
C_INT32 CModel::save(CWriteConfig & configBuffer)
{
C_INT32 Size;
C_INT32 Fail = 0;
if (Fail = configBuffer.setVariable("Title", "string", &mTitle))
return Fail;
if (Fail = configBuffer.setVariable("Comments", "multiline", &mComments))
return Fail;
Size = mCompartments->size();
if (Fail = configBuffer.setVariable("TotalCompartments", "C_INT32", &Size))
return Fail;
if (Fail = mCompartments->save(configBuffer)) return Fail;
if (Fail = Copasi.FunctionDB.save(configBuffer)) return Fail;
Size = mSteps->size();
if (Fail = configBuffer.setVariable("TotalSteps", "C_INT32", &Size))
return Fail;
if (Fail = mSteps->save(configBuffer)) return Fail;
return Fail;
}
void CModel::buildStoi()
{
vector < CStep::ELEMENT > Structure;
C_INT32 i,j,k;
mStoi.newsize(mMetabolites.size(), mSteps->size());
for (i=0; i<mSteps->size(); i++)
{
Structure = (*mSteps)[i].getChemStructure();
for (j=0; j<mMetabolites.size(); j++)
{
for (k=0; k<Structure.size(); k++)
if (Structure[k].mName == mMetabolites[j]->getName()) break;
if (k<Structure.size())
mStoi[j][i] = Structure[k].mValue;
else
mStoi[j][i] = 0.0;
}
}
cout << mStoi << endl;
return;
}
void CModel::lUDecomposition()
{
C_INT32 i;
TNT::Vector < TNT::Subscript > rowLU(mStoi.num_rows());
TNT::Vector < TNT::Subscript > colLU(mStoi.num_cols());
TNT::LUX_factor(mStoi, rowLU, colLU);
mMetabolitesX = mMetabolites;
mStepsX.resize(mSteps->size());
for (i=0; i<mSteps->size(); i++)
mStepsX[i] = &(*mSteps)[i];
// permutate Metabolites and Steps to match rearangements done during
// LU decomposition
CMetab *pMetab;
for (i = 0; i < mMetabolitesX.size(); i++)
{
if (rowLU[i] - 1 > i)
{
pMetab = mMetabolitesX[i];
mMetabolitesX[i] = mMetabolitesX[rowLU[i]-1];
mMetabolitesX[rowLU[i]-1] = pMetab;
}
}
CStep *pStep;
for (i = mStepsX.size() - 1; 0 <= i; i--)
{
if (colLU[i]-1 < i)
{
pStep = mStepsX[i];
mStepsX[i] = mStepsX[colLU[i]-1];
mStepsX[colLU[i]-1] = pStep;
}
}
return;
}
void CModel::setMetabolitesStatus()
{
C_INT32 i,j,k;
C_FLOAT64 Sum;
for (i=0; i<min(mStoi.num_rows(), mStoi.num_cols()); i++)
{
if (mStoi[i][i] == 0.0) break;
mMetabolitesX[i]->setStatus(METAB_VARIABLE);
}
mMetabolitesInd.clear();
mMetabolitesInd.insert(0,&mMetabolitesX[0],&mMetabolitesX[i]);
mStepsInd.insert(0,&mStepsX[0],&mStepsX[i]);
for (j=i; j<mStoi.num_rows(); j++)
{
Sum = 0.0;
for (k=0; k<mStoi.num_cols(); k++)
Sum += fabs(mStoi[j][k]);
if (Sum == 0.0) break;
mMetabolitesX[j]->setStatus(METAB_DEPENDENT);
}
mMetabolitesDep.clear();
mMetabolitesDep.insert(0,&mMetabolitesX[i],&mMetabolitesX[j]);
for (k=j; k<mStoi.num_rows(); k++)
mMetabolitesX[k]->setStatus(METAB_FIXED);
return;
}
void CModel::buildRedStoi()
{
C_INT32 i,j,k;
C_FLOAT64 Sum;
mRedStoi.newsize(mMetabolitesInd.size(),mStepsX.size());
for (i=0; i<mRedStoi.num_rows(); i++)
for (j=0; j<mRedStoi.num_cols(); j++)
{
Sum = 0.0;
for (k=0; k<min(i,j+1); k++)
Sum += mStoi[i][k] * mStoi[k][j];
if (i<=j) Sum += mStoi[i][j];
mRedStoi[i][j] = Sum;
}
cout << mRedStoi << endl;
return;
}
void CModel::buildConsRel()
{
// Since we do not use L anymore we could use L to store ConsRel !!!
mConsRel.newsize(mMetabolites.size(), mMetabolitesInd.size());
C_INT32 i,j;
for (i=0; i<min(mConsRel.num_rows(), mConsRel.num_cols()); i++)
mConsRel[i+1][i] = mStoi[i+1][i];
for (j=0; j<mConsRel.num_cols(); j++)
for (i=j+2; i<mConsRel.num_rows(); i++)
mConsRel[i][j] = mStoi[i][j] + mStoi[i][i-1] * mConsRel[i-1][j];
return;
}
void CModel::buildMoieties()
{
C_INT32 i,j;
CMoiety Moiety;
mMoieties->cleanup();
for (i=mMetabolitesDep.size();
i<mMetabolitesDep.size() + mMetabolitesInd.size(); i++)
{
Moiety.cleanup();
Moiety.setName(mMetabolitesX[i]->getName());
Moiety.add(1.0, mMetabolitesX[i]);
for (j=0; j<mConsRel.num_cols(); j++)
{
if (mConsRel[i][j] != 0.0)
Moiety.add(mConsRel[i][j], mMetabolitesX[j]);
}
Moiety.setInitialValue();
mMoieties->add(Moiety);
}
return;
}
void CModel::setConcentrations(const C_FLOAT64 * y)
{
C_INT32 i,j;
// Set the concentration of the independent metabolites
for (i=0; i < mMetabolitesInd.size(); i++)
mMetabolitesInd[i]->
setConcentration(y[i] *
mMetabolitesInd[i]->getCompartment()->getVolume());
// Set the concentration of the dependent metabolites
for (i=0; i<mMetabolitesDep.size(); i++)
mMetabolitesDep[i]->
setConcentration((*mMoieties)[i].dependentNumber() *
mMetabolitesDep[i]->getCompartment()->getVolume());
return;
}
CCopasiVector<CStep> & CModel::getSteps()
{
return *mSteps;
}
void CModel::lSODAEval(C_INT32 n, C_FLOAT64 t, C_FLOAT64 * y, C_FLOAT64 * ydot)
{
C_INT32 i,j;
C_FLOAT64 v[mSteps->size()];
cout << mTitle << endl;
setConcentrations(y);
// Calculate the velocity vector depending on the step kinetics
for (i=0; i<mSteps->size(); i++)
v[i] = (*mSteps)[i].calculate();
// Calculate ydot = RedStoi * v
for (i=0; i<n; i++)
{
ydot[i] = 0.0;
for (j=0; j<mSteps->size(); j++)
ydot[i] += mRedStoi[i][j] * v[j];
}
return;
}
vector < CMetab * > & CModel::getMetabolitesInd(){return mMetabolitesInd;}
C_INT32 CModel::getTotMetab() const
{
return mMetabolites.size();
}
C_INT32 CModel::getIntMetab() const
{
return mMetabolitesInd.size() + mMetabolitesDep.size();
}
C_INT32 CModel::getIndMetab() const
{
return mMetabolitesInd.size();
}
C_INT32 CModel::getDepMetab() const
{
return mMetabolitesDep.size();
}
// Added by Yongqun He
/**
* Get the total steps
*
*/
//C_INT32 CModel::getTotSteps()
//{
// return mSteps; //should not return mSteps
//}
<commit_msg>1. Add methods used by Output Module. 2. Chang min() due to compiler error<commit_after>// model.cpp : interface of the CModel class
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// CModel
#include <string>
#include <vector>
#include "copasi.h"
#include "CGlobals.h"
#include "CModel.h"
#include "CCompartment.h"
#include "tnt/luX.h"
CModel::CModel()
{
mCompartments = NULL;
mSteps = NULL;
mMoieties = NULL;
initialize();
}
void CModel::initialize()
{
if ( !mCompartments ) mCompartments = new CCopasiVector < CCompartment >;
if ( !mSteps ) mSteps = new CCopasiVector < CStep >;
if ( !mMoieties ) mMoieties = new CCopasiVector < CMoiety >;
}
CModel::~CModel()
{
cleanup();
}
void CModel::cleanup()
{
if ( mCompartments )
{
mCompartments->cleanup();
mCompartments = NULL;
}
if ( mSteps )
{
mSteps->cleanup();
mSteps = NULL;
}
if ( mMoieties )
{
mMoieties->cleanup();
mMoieties = NULL;
}
}
C_INT32 CModel::load(CReadConfig & configBuffer)
{
C_INT32 Size = 0;
C_INT32 Fail = 0;
C_INT32 i;
initialize();
// For old Versions we need must read the list of Metabolites beforehand
if (configBuffer.getVersion() < "4")
{
if (Fail = configBuffer.getVariable("TotalMetabolites", "C_INT32",
&Size, CReadConfig::LOOP))
return Fail;
if (Fail = Copasi.OldMetabolites.load(configBuffer, Size))
return Fail;
}
if (Fail = configBuffer.getVariable("Title", "string", &mTitle,
CReadConfig::LOOP))
return Fail;
if (Fail = configBuffer.getVariable("Comments", "multiline", &mComments,
CReadConfig::SEARCH))
return Fail;
if (Fail = configBuffer.getVariable("TotalCompartments", "C_INT32", &Size,
CReadConfig::LOOP))
return Fail;
if (Fail = mCompartments->load(configBuffer, Size)) return Fail;
if (configBuffer.getVersion() < "4")
{
// Create the correct compartment / metabolite relationships
CMetab Metabolite;
for (i = 0; i < Copasi.OldMetabolites.size(); i++)
{
Metabolite = Copasi.OldMetabolites[i];
(*mCompartments)[Copasi.OldMetabolites[i].getIndex()].
addMetabolite(Metabolite);
}
}
// Create a vector of pointers to all metabolites.
// Note, the metabolites physically exist in the compartments.
for (i = 0; i < mCompartments->size(); i++)
for (C_INT32 j = 0; j < (*mCompartments)[i].metabolites().size(); j++)
mMetabolites.push_back(&(*mCompartments)[i].metabolites()[j]);
if (Fail = Copasi.FunctionDB.load(configBuffer)) return Fail;
if (Fail = configBuffer.getVariable("TotalSteps", "C_INT32", &Size,
CReadConfig::LOOP))
return Fail;
if (Fail = mSteps->load(configBuffer, Size)) return Fail;
// We must postprocess the steps for old file versions
if (configBuffer.getVersion() < "4")
for (i = 0; i < mSteps->size(); i++)
(*mSteps)[i].old2New(mMetabolites);
for (i = 0; i < mSteps->size(); i++)
(*mSteps)[i].compile(mCompartments);
return Fail;
}
C_INT32 CModel::save(CWriteConfig & configBuffer)
{
C_INT32 Size;
C_INT32 Fail = 0;
if (Fail = configBuffer.setVariable("Title", "string", &mTitle))
return Fail;
if (Fail = configBuffer.setVariable("Comments", "multiline", &mComments))
return Fail;
Size = mCompartments->size();
if (Fail = configBuffer.setVariable("TotalCompartments", "C_INT32", &Size))
return Fail;
if (Fail = mCompartments->save(configBuffer)) return Fail;
if (Fail = Copasi.FunctionDB.save(configBuffer)) return Fail;
Size = mSteps->size();
if (Fail = configBuffer.setVariable("TotalSteps", "C_INT32", &Size))
return Fail;
if (Fail = mSteps->save(configBuffer)) return Fail;
return Fail;
}
void CModel::buildStoi()
{
vector < CStep::ELEMENT > Structure;
C_INT32 i,j,k;
mStoi.newsize(mMetabolites.size(), mSteps->size());
for (i=0; i<mSteps->size(); i++)
{
Structure = (*mSteps)[i].getChemStructure();
for (j=0; j<mMetabolites.size(); j++)
{
for (k=0; k<Structure.size(); k++)
if (Structure[k].mName == mMetabolites[j]->getName()) break;
if (k<Structure.size())
mStoi[j][i] = Structure[k].mValue;
else
mStoi[j][i] = 0.0;
}
}
cout << mStoi << endl;
return;
}
void CModel::lUDecomposition()
{
C_INT32 i;
TNT::Vector < TNT::Subscript > rowLU(mStoi.num_rows());
TNT::Vector < TNT::Subscript > colLU(mStoi.num_cols());
TNT::LUX_factor(mStoi, rowLU, colLU);
mMetabolitesX = mMetabolites;
mStepsX.resize(mSteps->size());
for (i=0; i<mSteps->size(); i++)
mStepsX[i] = &(*mSteps)[i];
// permutate Metabolites and Steps to match rearangements done during
// LU decomposition
CMetab *pMetab;
for (i = 0; i < mMetabolitesX.size(); i++)
{
if (rowLU[i] - 1 > i)
{
pMetab = mMetabolitesX[i];
mMetabolitesX[i] = mMetabolitesX[rowLU[i]-1];
mMetabolitesX[rowLU[i]-1] = pMetab;
}
}
CStep *pStep;
for (i = mStepsX.size() - 1; 0 <= i; i--)
{
if (colLU[i]-1 < i)
{
pStep = mStepsX[i];
mStepsX[i] = mStepsX[colLU[i]-1];
mStepsX[colLU[i]-1] = pStep;
}
}
return;
}
void CModel::setMetabolitesStatus()
{
C_INT32 i,j,k;
C_FLOAT64 Sum;
// for (i=0; i<min(mStoi.num_rows(), mStoi.num_cols()); i++)
// for compiler
C_INT32 imax = (mStoi.num_rows() < mStoi.num_cols()) ? mStoi.num_cols() : mStoi.num_rows();
for (i=0; i<imax; i++)
{
if (mStoi[i][i] == 0.0) break;
mMetabolitesX[i]->setStatus(METAB_VARIABLE);
}
mMetabolitesInd.clear();
mMetabolitesInd.insert(0,&mMetabolitesX[0],&mMetabolitesX[i]);
mStepsInd.insert(0,&mStepsX[0],&mStepsX[i]);
for (j=i; j<mStoi.num_rows(); j++)
{
Sum = 0.0;
for (k=0; k<mStoi.num_cols(); k++)
Sum += fabs(mStoi[j][k]);
if (Sum == 0.0) break;
mMetabolitesX[j]->setStatus(METAB_DEPENDENT);
}
mMetabolitesDep.clear();
mMetabolitesDep.insert(0,&mMetabolitesX[i],&mMetabolitesX[j]);
for (k=j; k<mStoi.num_rows(); k++)
mMetabolitesX[k]->setStatus(METAB_FIXED);
return;
}
void CModel::buildRedStoi()
{
C_INT32 i,j,k;
C_FLOAT64 Sum;
C_INT32 kmax; // wei for compiler
mRedStoi.newsize(mMetabolitesInd.size(),mStepsX.size());
for (i=0; i<mRedStoi.num_rows(); i++)
for (j=0; j<mRedStoi.num_cols(); j++)
{
Sum = 0.0;
//for (k=0; k<min(i,j+1); k++) for compiler
kmax = (i < j+1) ? j+1 : i;
for (k=0; k<kmax; k++)
Sum += mStoi[i][k] * mStoi[k][j];
if (i<=j) Sum += mStoi[i][j];
mRedStoi[i][j] = Sum;
}
cout << mRedStoi << endl;
return;
}
void CModel::buildConsRel()
{
// Since we do not use L anymore we could use L to store ConsRel !!!
mConsRel.newsize(mMetabolites.size(), mMetabolitesInd.size());
C_INT32 i,j;
C_INT32 imax = (mConsRel.num_rows() < mConsRel.num_cols()) ?
mConsRel.num_cols() : mConsRel.num_rows();
// wei for compiler for (i=0; i<min(mConsRel.num_rows(), mConsRel.num_cols()); i++)
for (i=0; i<imax; i++)
mConsRel[i+1][i] = mStoi[i+1][i];
for (j=0; j<mConsRel.num_cols(); j++)
for (i=j+2; i<mConsRel.num_rows(); i++)
mConsRel[i][j] = mStoi[i][j] + mStoi[i][i-1] * mConsRel[i-1][j];
return;
}
void CModel::buildMoieties()
{
C_INT32 i,j;
CMoiety Moiety;
mMoieties->cleanup();
for (i=mMetabolitesDep.size();
i<mMetabolitesDep.size() + mMetabolitesInd.size(); i++)
{
Moiety.cleanup();
Moiety.setName(mMetabolitesX[i]->getName());
Moiety.add(1.0, mMetabolitesX[i]);
for (j=0; j<mConsRel.num_cols(); j++)
{
if (mConsRel[i][j] != 0.0)
Moiety.add(mConsRel[i][j], mMetabolitesX[j]);
}
Moiety.setInitialValue();
mMoieties->add(Moiety);
}
return;
}
void CModel::setConcentrations(const C_FLOAT64 * y)
{
C_INT32 i,j;
// Set the concentration of the independent metabolites
for (i=0; i < mMetabolitesInd.size(); i++)
mMetabolitesInd[i]->
setConcentration(y[i] *
mMetabolitesInd[i]->getCompartment()->getVolume());
// Set the concentration of the dependent metabolites
for (i=0; i<mMetabolitesDep.size(); i++)
mMetabolitesDep[i]->
setConcentration((*mMoieties)[i].dependentNumber() *
mMetabolitesDep[i]->getCompartment()->getVolume());
return;
}
#if 0
CCopasiVector<CStep> & CModel::getSteps()
{
return *mSteps;
}
#endif
void CModel::lSODAEval(C_INT32 n, C_FLOAT64 t, C_FLOAT64 * y, C_FLOAT64 * ydot)
{
C_INT32 i,j;
//C_FLOAT64 v[mSteps->size()]; Wei
C_FLOAT64 *v =new C_FLOAT64[mSteps->size()];
cout << mTitle << endl;
setConcentrations(y);
// Calculate the velocity vector depending on the step kinetics
for (i=0; i<mSteps->size(); i++)
v[i] = (*mSteps)[i].calculate();
// Calculate ydot = RedStoi * v
for (i=0; i<n; i++)
{
ydot[i] = 0.0;
for (j=0; j<mSteps->size(); j++)
ydot[i] += mRedStoi[i][j] * v[j];
}
return;
}
vector < CMetab * > & CModel::getMetabolitesInd(){return mMetabolitesInd;}
C_INT32 CModel::getTotMetab() const
{
return mMetabolites.size();
}
C_INT32 CModel::getIntMetab() const
{
return mMetabolitesInd.size() + mMetabolitesDep.size();
}
C_INT32 CModel::getIndMetab() const
{
return mMetabolitesInd.size();
}
C_INT32 CModel::getDepMetab() const
{
return mMetabolitesDep.size();
}
// Added by Yongqun He
/**
* Get the total steps
*
*/
//C_INT32 CModel::getTotSteps()
//{
// return mSteps; //should not return mSteps
//}
C_INT32 CModel::getDimension() const
{
return mMetabolitesInd.size();
}
/**
* Return the comments of this model Wei Sun
*/
string CModel::getComments() const
{
return mComments;
}
/**
* Return the msteps of this model
* @return CCopasiVector < CStep > *
*/
CCopasiVector < CStep > * CModel::getSteps()
{
return mSteps;
}
/**
* Return the title of this model
* @return string
*/
string CModel::getTitle() const
{
return mTitle;
}
/**
* Return the comments of this model
* @return CCopasiVector < CCompartment > *
*/
CCopasiVector < CCompartment > * CModel::getCompartments()
{
return mCompartments;
}
/**
* Return the metabolites of this model
* @return vector < CMetab * >
*/
vector < CMetab * > & CModel::getMetabolites()
{
return mMetabolites;
}
/**
* Get the Reduced Stoichiometry Matrix of this Model
*/
TNT::Matrix < C_FLOAT64 >& CModel::getRedStoi()
{
return mRedStoi;
}
/**
* Return the mMoieties of this model
* @return CCopasiVector < CMoiety > *
*/
CCopasiVector < CMoiety > * CModel::getMoieties()
{
return mMoieties;
}
/**
* Returns the index of the metab
*/
C_INT32 CModel::findMetab(string &Target)
{
int i;
string name;
for(i = 0; i < mMetabolites.size(); i++ )
{
name = mMetabolites[i]->getName();
if( name == Target) return i;
}
return -1;
}
/**
* Returns the index of the step
*/
C_INT32 CModel::findStep(string &Target)
{
int i;
string name;
for(i = 0; i < mSteps->size(); i++ )
{
name = (*mSteps)[i].getName();
if( name == Target) return i;
}
return -1;
}
/**
* Returns the index of the compartment
*/
C_INT32 CModel::findCompartment(string &Target)
{
int i;
string name;
for(i = 0; i < mCompartments->size(); i++ )
{
name = (*mCompartments)[i].getName();
if( name == Target) return i;
}
return -1;
}
/**
* Returns the index of the Moiety
*/
C_INT32 CModel::findMoiety(string &Target)
{
int i;
string name;
for(i = 0; i < mMoieties->size(); i++ )
{
name = (*mMoieties)[i].getName();
if( name == Target) return i;
}
return -1;
}
<|endoftext|>
|
<commit_before>#include "proclist.h"
// PDTK
#include <cxxutils/posix_helpers.h>
#if defined(__linux__) // Linux
#include <dirent.h>
#include <cstdlib>
int proclist(pid_t* list, size_t max_length)
{
DIR* dirp = ::opendir("/proc");
if(dirp == nullptr)
return posix::error_response;
struct dirent* entry;
size_t count = 0;
while((entry = ::readdir(dirp)) != nullptr &&
count < max_length)
{
if(entry->d_type == DT_DIR)
{
list[count] = std::atoi(entry->d_name);
if(list[count])
++count;
}
}
if(errno != posix::success_response)
return posix::error_response;
if(::closedir(dirp) == posix::error_response)
return posix::error_response;
return count;
}
#elif defined(BSD) || defined(__APPLE__) // *BSD/Darwin
// Darwin structure documentation
// kinfo_proc : https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/sysctl.h.auto.html
// BSD structure documentation
// kinfo_proc : http://fxr.watson.org/fxr/source/sys/user.h#L119
// *BSD/Darwin
#include <sys/sysctl.h>
// STL
#include <vector>
// PDTK
#include <cxxutils/misc_helpers.h>
int proclist(pid_t* list, size_t max_length)
{
size_t length = 0;
std::vector<struct kinfo_proc> proc_list;
int request[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
std::memset(list, 0, max_length);
if(::sysctl(request, arraylength(request), nullptr, &length, nullptr, 0) != posix::success_response)
return posix::error_response;
if(length > max_length)
return posix::error(std::errc::not_enough_memory);
proc_list.resize(length);
if(::sysctl(request, arraylength(request), proc_list.data(), &length, nullptr, 0) != posix::success_response)
return posix::error_response;
if(proc_list.size() >= length)
return posix::error(std::errc::not_enough_memory);
proc_list.resize(length);
struct kinfo_proc* proc_pos = proc_list.data();
for(pid_t* pos = list; pos != list + length; ++pos, ++proc_pos)
#if defined(__APPLE__)
*pos = proc_pos->kp_proc.p_pid;
#else
*pos = proc_pos->ki_pid;
#endif
return posix::success_response;
}
#elif defined(__unix__)
//system("ps -A -o pid=");
#error no code yet for your operating system. :(
#else
#error Unsupported platform! >:(
#endif
<commit_msg>test for strange situations<commit_after>#include "proclist.h"
// PDTK
#include <cxxutils/posix_helpers.h>
static_assert(sizeof(pid_t) <= sizeof(int), "insufficient storage type for maximum number of pids");
#if defined(__linux__) // Linux
#include <dirent.h>
#include <cstdlib>
int proclist(pid_t* list, size_t max_length)
{
DIR* dirp = ::opendir("/proc");
if(dirp == nullptr)
return posix::error_response;
struct dirent* entry;
int count = 0;
while((entry = ::readdir(dirp)) != nullptr &&
count >= 0 &&
size_t(count) < max_length)
{
if(entry->d_type == DT_DIR)
{
list[count] = std::atoi(entry->d_name);
if(list[count])
++count;
}
}
if(errno != posix::success_response)
{
error_t errback = errno;
::closedir(dirp);
return posix::error(errback);
}
if(::closedir(dirp) == posix::error_response)
return posix::error_response;
if(count < 0)
return posix::error(std::errc::result_out_of_range);
if(size_t(count) >= max_length)
return posix::error(std::errc::not_enough_memory);
return count;
}
#elif defined(BSD) || defined(__APPLE__) // *BSD/Darwin
// Darwin structure documentation
// kinfo_proc : https://opensource.apple.com/source/xnu/xnu-1456.1.26/bsd/sys/sysctl.h.auto.html
// BSD structure documentation
// kinfo_proc : http://fxr.watson.org/fxr/source/sys/user.h#L119
// *BSD/Darwin
#include <sys/sysctl.h>
// STL
#include <vector>
// PDTK
#include <cxxutils/misc_helpers.h>
int proclist(pid_t* list, size_t max_length)
{
size_t length = 0;
std::vector<struct kinfo_proc> proc_list;
int request[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
std::memset(list, 0, max_length);
if(::sysctl(request, arraylength(request), nullptr, &length, nullptr, 0) != posix::success_response)
return posix::error_response;
if(length > max_length)
return posix::error(std::errc::not_enough_memory);
proc_list.resize(length);
if(::sysctl(request, arraylength(request), proc_list.data(), &length, nullptr, 0) != posix::success_response)
return posix::error_response;
if(proc_list.size() >= length)
return posix::error(std::errc::not_enough_memory);
proc_list.resize(length);
struct kinfo_proc* proc_pos = proc_list.data();
for(pid_t* pos = list; pos != list + length; ++pos, ++proc_pos)
#if defined(__APPLE__)
*pos = proc_pos->kp_proc.p_pid;
#else
*pos = proc_pos->ki_pid;
#endif
return posix::success_response;
}
#elif defined(__unix__)
//system("ps -A -o pid=");
#error no code yet for your operating system. :(
#else
#error Unsupported platform! >:(
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 Google 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 Google 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.
*/
#include "config.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_proxy.h"
#include "V8Document.h"
#include "V8HTMLDocument.h"
#include "V8ObjectEventListener.h"
#include "ExceptionCode.h"
#include "MessagePort.h"
namespace WebCore {
// FIXME: merge these with XHR's CreateHiddenXHRDependency
// Use an array to hold dependents. It works like a ref-counted scheme.
// A value can be added more than once to the xhr object.
static void CreateHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value)
{
ASSERT(V8Proxy::GetDOMWrapperType(object) == V8ClassIndex::MESSAGEPORT);
v8::Local<v8::Value> cache = object->GetInternalField(V8Custom::kMessagePortRequestCacheIndex);
if (cache->IsNull() || cache->IsUndefined()) {
cache = v8::Array::New();
object->SetInternalField(V8Custom::kMessagePortRequestCacheIndex, cache);
}
v8::Local<v8::Array> cacheArray = v8::Local<v8::Array>::Cast(cache);
cacheArray->Set(v8::Integer::New(cacheArray->Length()), value);
}
static void RemoveHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value)
{
ASSERT(V8Proxy::GetDOMWrapperType(object) == V8ClassIndex::MESSAGEPORT);
v8::Local<v8::Value> cache = object->GetInternalField(V8Custom::kMessagePortRequestCacheIndex);
ASSERT(cache->IsArray());
v8::Local<v8::Array> cacheArray = v8::Local<v8::Array>::Cast(cache);
for (int i = cacheArray->Length() - 1; i >= 0; i--) {
v8::Local<v8::Value> cached = cacheArray->Get(v8::Integer::New(i));
if (cached->StrictEquals(value)) {
cacheArray->Delete(i);
return;
}
}
// We should only get here if we try to remove an event listener that was
// never added.
}
ACCESSOR_GETTER(MessagePortOnmessage)
{
INC_STATS("DOM.MessagePort.onmessage._get");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, info.Holder());
if (messagePort->onmessage()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(messagePort->onmessage());
v8::Local<v8::Object> v8Listener = listener->getListenerObject();
return v8Listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(MessagePortOnmessage)
{
INC_STATS("DOM.MessagePort.onmessage._set");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, info.Holder());
if (value->IsNull()) {
if (messagePort->onmessage()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(messagePort->onmessage());
v8::Local<v8::Object> v8Listener = listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), v8Listener);
}
// Clear the listener
messagePort->setOnmessage(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
messagePort->setOnmessage(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
ACCESSOR_GETTER(MessagePortOnclose)
{
INC_STATS("DOM.MessagePort.onclose._get");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, info.Holder());
if (messagePort->onclose()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(messagePort->onclose());
v8::Local<v8::Object> v8Listener = listener->getListenerObject();
return v8Listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(MessagePortOnclose)
{
INC_STATS("DOM.MessagePort.onclose._set");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, info.Holder());
if (value->IsNull()) {
if (messagePort->onclose()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(messagePort->onclose());
v8::Local<v8::Object> v8Listener = listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), v8Listener);
}
// Clear the listener
messagePort->setOnclose(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
messagePort->setOnclose(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
CALLBACK_FUNC_DECL(MessagePortStartConversation)
{
INC_STATS("DOM.MessagePort.StartConversation()");
if (args.Length() < 1) {
V8Proxy::ThrowError(V8Proxy::SYNTAX_ERROR, "Not enough arguments");
return v8::Undefined();
}
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<MessagePort> port =
messagePort->startConversation(messagePort->scriptExecutionContext(),
ToWebCoreString(args[0]));
v8::Handle<v8::Value> wrapper =
V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port.get());
return wrapper;
}
CALLBACK_FUNC_DECL(MessagePortAddEventListener)
{
INC_STATS("DOM.MessagePort.AddEventListener()");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
messagePort->addEventListener(type, listener, useCapture);
CreateHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
CALLBACK_FUNC_DECL(MessagePortRemoveEventListener)
{
INC_STATS("DOM.MessagePort.RemoveEventListener()");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(
V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined(); // probably leaked
RefPtr<EventListener> listener =
proxy->FindObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
messagePort->removeEventListener(type, listener.get(), useCapture);
RemoveHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
} // namespace WebCore
<commit_msg>Prepare V8MessagePortCustom.cpp for upstreaming to WebKit<commit_after>/*
* Copyright (C) 2009 Google 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 Google 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.
*/
#include "config.h"
#include "ExceptionCode.h"
#include "MessagePort.h"
#include "V8Binding.h"
#include "V8CustomBinding.h"
#include "V8ObjectEventListener.h"
#include "V8Proxy.h"
#include "V8Utilities.h"
namespace WebCore {
ACCESSOR_GETTER(MessagePortOnmessage)
{
INC_STATS("DOM.MessagePort.onmessage._get");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, info.Holder());
return V8Proxy::EventListenerToV8Object(messagePort->onmessage());
}
ACCESSOR_SETTER(MessagePortOnmessage)
{
INC_STATS("DOM.MessagePort.onmessage._set");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, info.Holder());
if (value->IsNull()) {
if (messagePort->onmessage()) {
V8ObjectEventListener* listener = static_cast<V8ObjectEventListener*>(messagePort->onmessage());
removeHiddenDependency(info.Holder(), listener->getListenerObject(), V8Custom::kMessagePortRequestCacheIndex);
}
// Clear the listener.
messagePort->setOnmessage(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener = proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
messagePort->setOnmessage(listener);
createHiddenDependency(info.Holder(), value, V8Custom::kMessagePortRequestCacheIndex);
}
}
}
ACCESSOR_GETTER(MessagePortOnclose)
{
INC_STATS("DOM.MessagePort.onclose._get");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, info.Holder());
return V8Proxy::EventListenerToV8Object(messagePort->onclose());
}
ACCESSOR_SETTER(MessagePortOnclose)
{
INC_STATS("DOM.MessagePort.onclose._set");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, info.Holder());
if (value->IsNull()) {
if (messagePort->onclose()) {
V8ObjectEventListener* listener = static_cast<V8ObjectEventListener*>(messagePort->onclose());
removeHiddenDependency(info.Holder(), listener->getListenerObject(), V8Custom::kXMLHttpRequestCacheIndex);
}
// Clear the listener.
messagePort->setOnclose(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener = proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
messagePort->setOnclose(listener);
createHiddenDependency(info.Holder(), value, V8Custom::kMessagePortRequestCacheIndex);
}
}
}
CALLBACK_FUNC_DECL(MessagePortStartConversation)
{
INC_STATS("DOM.MessagePort.StartConversation()");
if (args.Length() < 1)
return throwError("Not enough arguments", V8Proxy::SYNTAX_ERROR);
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<MessagePort> port = messagePort->startConversation(messagePort->scriptExecutionContext(), toWebCoreString(args[0]));
v8::Handle<v8::Value> wrapper = V8Proxy::ToV8Object(V8ClassIndex::MESSAGEPORT, port.get());
return wrapper;
}
CALLBACK_FUNC_DECL(MessagePortAddEventListener)
{
INC_STATS("DOM.MessagePort.AddEventListener()");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<EventListener> listener = proxy->FindOrCreateObjectEventListener(args[1], false);
if (listener) {
String type = toWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
messagePort->addEventListener(type, listener, useCapture);
createHiddenDependency(args.Holder(), args[1], V8Custom::kMessagePortRequestCacheIndex);
}
return v8::Undefined();
}
CALLBACK_FUNC_DECL(MessagePortRemoveEventListener)
{
INC_STATS("DOM.MessagePort.RemoveEventListener()");
MessagePort* messagePort = V8Proxy::ToNativeObject<MessagePort>(V8ClassIndex::MESSAGEPORT, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(messagePort->scriptExecutionContext());
if (!proxy)
return v8::Undefined(); // probably leaked
RefPtr<EventListener> listener = proxy->FindObjectEventListener(args[1], false);
if (listener) {
String type = toWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
messagePort->removeEventListener(type, listener.get(), useCapture);
removeHiddenDependency(args.Holder(), args[1], V8Custom::kMessagePortRequestCacheIndex);
}
return v8::Undefined();
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include "DictCache.hpp"
#include "NdbDictionaryImpl.hpp"
#include <NdbTick.h>
#include <NdbCondition.h>
#include <NdbSleep.h>
static NdbTableImpl f_invalid_table;
static NdbTableImpl f_altered_table;
Ndb_local_table_info *
Ndb_local_table_info::create(NdbTableImpl *table_impl, Uint32 sz)
{
Uint32 tot_size= sizeof(Ndb_local_table_info) - sizeof(Uint64)
+ ((sz+7) & ~7); // round to Uint64
void *data= malloc(tot_size);
if (data == 0)
return 0;
memset(data, 0, tot_size);
new (data) Ndb_local_table_info(table_impl);
return (Ndb_local_table_info *) data;
}
void Ndb_local_table_info::destroy(Ndb_local_table_info *info)
{
free((void *)info);
}
Ndb_local_table_info::Ndb_local_table_info(NdbTableImpl *table_impl)
{
m_table_impl= table_impl;
}
Ndb_local_table_info::~Ndb_local_table_info()
{
}
LocalDictCache::LocalDictCache(){
m_tableHash.createHashTable();
}
LocalDictCache::~LocalDictCache(){
m_tableHash.releaseHashTable();
}
Ndb_local_table_info *
LocalDictCache::get(const char * name){
const Uint32 len = strlen(name);
return m_tableHash.getData(name, len);
}
void
LocalDictCache::put(const char * name, Ndb_local_table_info * tab_info){
const Uint32 id = tab_info->m_table_impl->m_tableId;
m_tableHash.insertKey(name, strlen(name), id, tab_info);
}
void
LocalDictCache::drop(const char * name){
Ndb_local_table_info *info= m_tableHash.deleteKey(name, strlen(name));
DBUG_ASSERT(info != 0);
Ndb_local_table_info::destroy(info);
}
/*****************************************************************
* Global cache
*/
GlobalDictCache::GlobalDictCache(){
m_tableHash.createHashTable();
m_waitForTableCondition = NdbCondition_Create();
}
GlobalDictCache::~GlobalDictCache(){
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
while(curr != 0){
Vector<TableVersion> * vers = curr->theData;
const unsigned sz = vers->size();
for(unsigned i = 0; i<sz ; i++){
if((* vers)[i].m_impl != 0)
delete (* vers)[i].m_impl;
}
delete curr->theData;
curr = m_tableHash.getNext(curr);
}
m_tableHash.releaseHashTable();
NdbCondition_Destroy(m_waitForTableCondition);
}
#include <NdbOut.hpp>
NdbTableImpl *
GlobalDictCache::get(const char * name)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * versions = 0;
versions = m_tableHash.getData(name, len);
if(versions == 0){
versions = new Vector<TableVersion>(2);
m_tableHash.insertKey(name, len, 0, versions);
}
int waitTime = 100;
bool retreive = false;
while(versions->size() > 0 && !retreive){
TableVersion * ver = & versions->back();
switch(ver->m_status){
case OK:
ver->m_refCount++;
return ver->m_impl;
case DROPPED:
retreive = true; // Break loop
break;
case RETREIVING:
NdbCondition_WaitTimeout(m_waitForTableCondition, m_mutex, waitTime);
continue;
}
}
/**
* Create new...
*/
TableVersion tmp;
tmp.m_version = 0;
tmp.m_impl = 0;
tmp.m_status = RETREIVING;
tmp.m_refCount = 1; // The one retreiving it
versions->push_back(tmp);
return 0;
}
NdbTableImpl *
GlobalDictCache::put(const char * name, NdbTableImpl * tab)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * vers = m_tableHash.getData(name, len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
TableVersion & ver = vers->back();
if(ver.m_status != RETREIVING ||
!(ver.m_impl == 0 ||
ver.m_impl == &f_invalid_table || ver.m_impl == &f_altered_table) ||
ver.m_version != 0 ||
ver.m_refCount == 0){
abort();
}
if(tab == 0)
{
// No table found in db
vers->erase(sz - 1);
}
else if (ver.m_impl == 0) {
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = OK;
}
else if (ver.m_impl == &f_invalid_table)
{
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = DROPPED;
ver.m_impl->m_status = NdbDictionary::Object::Invalid;
}
else if(ver.m_impl == &f_altered_table)
{
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = DROPPED;
ver.m_impl->m_status = NdbDictionary::Object::Altered;
}
else
{
abort();
}
NdbCondition_Broadcast(m_waitForTableCondition);
return tab;
}
void
GlobalDictCache::drop(NdbTableImpl * tab)
{
unsigned i;
const Uint32 len = strlen(tab->m_internalName.c_str());
Vector<TableVersion> * vers =
m_tableHash.getData(tab->m_internalName.c_str(), len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
for(i = 0; i < sz; i++){
TableVersion & ver = (* vers)[i];
if(ver.m_impl == tab){
if(ver.m_refCount == 0 || ver.m_status == RETREIVING ||
ver.m_version != tab->m_version){
ndbout_c("Dropping with refCount=%d status=%d impl=%p",
ver.m_refCount, ver.m_status, ver.m_impl);
break;
}
ver.m_refCount--;
ver.m_status = DROPPED;
if(ver.m_refCount == 0){
delete ver.m_impl;
vers->erase(i);
}
return;
}
}
for(i = 0; i<sz; i++){
TableVersion & ver = (* vers)[i];
ndbout_c("%d: version: %d refCount: %d status: %d impl: %p",
i, ver.m_version, ver.m_refCount, ver.m_status, ver.m_impl);
}
abort();
}
unsigned
GlobalDictCache::get_size()
{
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
int sz = 0;
while(curr != 0){
sz += curr->theData->size();
curr = m_tableHash.getNext(curr);
}
return sz;
}
void
GlobalDictCache::invalidate_all()
{
DBUG_ENTER("GlobalDictCache::invalidate_all");
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
while(curr != 0){
Vector<TableVersion> * vers = curr->theData;
if (vers->size())
{
TableVersion * ver = & vers->back();
ver->m_impl->m_status = NdbDictionary::Object::Invalid;
ver->m_status = DROPPED;
if (ver->m_refCount == 0)
{
delete ver->m_impl;
vers->erase(vers->size() - 1);
}
}
curr = m_tableHash.getNext(curr);
}
DBUG_VOID_RETURN;
}
void
GlobalDictCache::release(NdbTableImpl * tab){
unsigned i;
const Uint32 len = strlen(tab->m_internalName.c_str());
Vector<TableVersion> * vers =
m_tableHash.getData(tab->m_internalName.c_str(), len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
for(i = 0; i < sz; i++){
TableVersion & ver = (* vers)[i];
if(ver.m_impl == tab){
if(ver.m_refCount == 0 || ver.m_status == RETREIVING ||
ver.m_version != tab->m_version){
ndbout_c("Releasing with refCount=%d status=%d impl=%p",
ver.m_refCount, ver.m_status, ver.m_impl);
break;
}
ver.m_refCount--;
return;
}
}
for(i = 0; i<sz; i++){
TableVersion & ver = (* vers)[i];
ndbout_c("%d: version: %d refCount: %d status: %d impl: %p",
i, ver.m_version, ver.m_refCount, ver.m_status, ver.m_impl);
}
abort();
}
void
GlobalDictCache::alter_table_rep(const char * name,
Uint32 tableId,
Uint32 tableVersion,
bool altered)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * vers =
m_tableHash.getData(name, len);
if(vers == 0)
{
return;
}
const Uint32 sz = vers->size();
if(sz == 0)
{
return;
}
for(Uint32 i = 0; i < sz; i++)
{
TableVersion & ver = (* vers)[i];
if(ver.m_version == tableVersion && ver.m_impl &&
ver.m_impl->m_tableId == tableId)
{
ver.m_status = DROPPED;
ver.m_impl->m_status = altered ?
NdbDictionary::Object::Altered : NdbDictionary::Object::Invalid;
return;
}
if(i == sz - 1 && ver.m_status == RETREIVING)
{
ver.m_impl = altered ? &f_altered_table : &f_invalid_table;
return;
}
}
}
template class Vector<GlobalDictCache::TableVersion>;
<commit_msg>backport of ndb DictCache fix - don't invalidate tables that are in state RETRIEVING<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include "DictCache.hpp"
#include "NdbDictionaryImpl.hpp"
#include <NdbTick.h>
#include <NdbCondition.h>
#include <NdbSleep.h>
static NdbTableImpl f_invalid_table;
static NdbTableImpl f_altered_table;
Ndb_local_table_info *
Ndb_local_table_info::create(NdbTableImpl *table_impl, Uint32 sz)
{
Uint32 tot_size= sizeof(Ndb_local_table_info) - sizeof(Uint64)
+ ((sz+7) & ~7); // round to Uint64
void *data= malloc(tot_size);
if (data == 0)
return 0;
memset(data, 0, tot_size);
new (data) Ndb_local_table_info(table_impl);
return (Ndb_local_table_info *) data;
}
void Ndb_local_table_info::destroy(Ndb_local_table_info *info)
{
free((void *)info);
}
Ndb_local_table_info::Ndb_local_table_info(NdbTableImpl *table_impl)
{
m_table_impl= table_impl;
}
Ndb_local_table_info::~Ndb_local_table_info()
{
}
LocalDictCache::LocalDictCache(){
m_tableHash.createHashTable();
}
LocalDictCache::~LocalDictCache(){
m_tableHash.releaseHashTable();
}
Ndb_local_table_info *
LocalDictCache::get(const char * name){
const Uint32 len = strlen(name);
return m_tableHash.getData(name, len);
}
void
LocalDictCache::put(const char * name, Ndb_local_table_info * tab_info){
const Uint32 id = tab_info->m_table_impl->m_tableId;
m_tableHash.insertKey(name, strlen(name), id, tab_info);
}
void
LocalDictCache::drop(const char * name){
Ndb_local_table_info *info= m_tableHash.deleteKey(name, strlen(name));
DBUG_ASSERT(info != 0);
Ndb_local_table_info::destroy(info);
}
/*****************************************************************
* Global cache
*/
GlobalDictCache::GlobalDictCache(){
m_tableHash.createHashTable();
m_waitForTableCondition = NdbCondition_Create();
}
GlobalDictCache::~GlobalDictCache(){
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
while(curr != 0){
Vector<TableVersion> * vers = curr->theData;
const unsigned sz = vers->size();
for(unsigned i = 0; i<sz ; i++){
if((* vers)[i].m_impl != 0)
delete (* vers)[i].m_impl;
}
delete curr->theData;
curr = m_tableHash.getNext(curr);
}
m_tableHash.releaseHashTable();
NdbCondition_Destroy(m_waitForTableCondition);
}
#include <NdbOut.hpp>
NdbTableImpl *
GlobalDictCache::get(const char * name)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * versions = 0;
versions = m_tableHash.getData(name, len);
if(versions == 0){
versions = new Vector<TableVersion>(2);
m_tableHash.insertKey(name, len, 0, versions);
}
int waitTime = 100;
bool retreive = false;
while(versions->size() > 0 && !retreive){
TableVersion * ver = & versions->back();
switch(ver->m_status){
case OK:
ver->m_refCount++;
return ver->m_impl;
case DROPPED:
retreive = true; // Break loop
break;
case RETREIVING:
NdbCondition_WaitTimeout(m_waitForTableCondition, m_mutex, waitTime);
continue;
}
}
/**
* Create new...
*/
TableVersion tmp;
tmp.m_version = 0;
tmp.m_impl = 0;
tmp.m_status = RETREIVING;
tmp.m_refCount = 1; // The one retreiving it
versions->push_back(tmp);
return 0;
}
NdbTableImpl *
GlobalDictCache::put(const char * name, NdbTableImpl * tab)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * vers = m_tableHash.getData(name, len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
TableVersion & ver = vers->back();
if(ver.m_status != RETREIVING ||
!(ver.m_impl == 0 ||
ver.m_impl == &f_invalid_table || ver.m_impl == &f_altered_table) ||
ver.m_version != 0 ||
ver.m_refCount == 0){
abort();
}
if(tab == 0)
{
// No table found in db
vers->erase(sz - 1);
}
else if (ver.m_impl == 0) {
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = OK;
}
else if (ver.m_impl == &f_invalid_table)
{
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = DROPPED;
ver.m_impl->m_status = NdbDictionary::Object::Invalid;
}
else if(ver.m_impl == &f_altered_table)
{
ver.m_impl = tab;
ver.m_version = tab->m_version;
ver.m_status = DROPPED;
ver.m_impl->m_status = NdbDictionary::Object::Altered;
}
else
{
abort();
}
NdbCondition_Broadcast(m_waitForTableCondition);
return tab;
}
void
GlobalDictCache::drop(NdbTableImpl * tab)
{
unsigned i;
const Uint32 len = strlen(tab->m_internalName.c_str());
Vector<TableVersion> * vers =
m_tableHash.getData(tab->m_internalName.c_str(), len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
for(i = 0; i < sz; i++){
TableVersion & ver = (* vers)[i];
if(ver.m_impl == tab){
if(ver.m_refCount == 0 || ver.m_status == RETREIVING ||
ver.m_version != tab->m_version){
ndbout_c("Dropping with refCount=%d status=%d impl=%p",
ver.m_refCount, ver.m_status, ver.m_impl);
break;
}
ver.m_refCount--;
ver.m_status = DROPPED;
if(ver.m_refCount == 0){
delete ver.m_impl;
vers->erase(i);
}
return;
}
}
for(i = 0; i<sz; i++){
TableVersion & ver = (* vers)[i];
ndbout_c("%d: version: %d refCount: %d status: %d impl: %p",
i, ver.m_version, ver.m_refCount, ver.m_status, ver.m_impl);
}
abort();
}
unsigned
GlobalDictCache::get_size()
{
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
int sz = 0;
while(curr != 0){
sz += curr->theData->size();
curr = m_tableHash.getNext(curr);
}
return sz;
}
void
GlobalDictCache::invalidate_all()
{
DBUG_ENTER("GlobalDictCache::invalidate_all");
NdbElement_t<Vector<TableVersion> > * curr = m_tableHash.getNext(0);
while(curr != 0){
Vector<TableVersion> * vers = curr->theData;
if (vers->size())
{
TableVersion * ver = & vers->back();
if (ver->m_status != RETREIVING)
{
ver->m_impl->m_status = NdbDictionary::Object::Invalid;
ver->m_status = DROPPED;
if (ver->m_refCount == 0)
{
delete ver->m_impl;
vers->erase(vers->size() - 1);
}
}
}
curr = m_tableHash.getNext(curr);
}
DBUG_VOID_RETURN;
}
void
GlobalDictCache::release(NdbTableImpl * tab){
unsigned i;
const Uint32 len = strlen(tab->m_internalName.c_str());
Vector<TableVersion> * vers =
m_tableHash.getData(tab->m_internalName.c_str(), len);
if(vers == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
const Uint32 sz = vers->size();
if(sz == 0){
// Should always tried to retreive it first
// and then there should be a record
abort();
}
for(i = 0; i < sz; i++){
TableVersion & ver = (* vers)[i];
if(ver.m_impl == tab){
if(ver.m_refCount == 0 || ver.m_status == RETREIVING ||
ver.m_version != tab->m_version){
ndbout_c("Releasing with refCount=%d status=%d impl=%p",
ver.m_refCount, ver.m_status, ver.m_impl);
break;
}
ver.m_refCount--;
return;
}
}
for(i = 0; i<sz; i++){
TableVersion & ver = (* vers)[i];
ndbout_c("%d: version: %d refCount: %d status: %d impl: %p",
i, ver.m_version, ver.m_refCount, ver.m_status, ver.m_impl);
}
abort();
}
void
GlobalDictCache::alter_table_rep(const char * name,
Uint32 tableId,
Uint32 tableVersion,
bool altered)
{
const Uint32 len = strlen(name);
Vector<TableVersion> * vers =
m_tableHash.getData(name, len);
if(vers == 0)
{
return;
}
const Uint32 sz = vers->size();
if(sz == 0)
{
return;
}
for(Uint32 i = 0; i < sz; i++)
{
TableVersion & ver = (* vers)[i];
if(ver.m_version == tableVersion && ver.m_impl &&
ver.m_impl->m_tableId == tableId)
{
ver.m_status = DROPPED;
ver.m_impl->m_status = altered ?
NdbDictionary::Object::Altered : NdbDictionary::Object::Invalid;
return;
}
if(i == sz - 1 && ver.m_status == RETREIVING)
{
ver.m_impl = altered ? &f_altered_table : &f_invalid_table;
return;
}
}
}
template class Vector<GlobalDictCache::TableVersion>;
<|endoftext|>
|
<commit_before>//
// Camera.cpp
// Cinder-EDSDK
//
// Created by Jean-Pierre Mouilleseaux on 08 Dec 2013.
// Copyright 2013-2015 Chorded Constructions. All rights reserved.
//
#include "Camera.h"
#include "CameraBrowser.h"
using namespace ci;
using namespace ci::app;
namespace Cinder { namespace EDSDK {
#pragma mark CAMERA FILE
CameraFileRef CameraFile::create(const EdsDirectoryItemRef& directoryItem) {
return CameraFileRef(new CameraFile(directoryItem))->shared_from_this();
}
CameraFile::CameraFile(const EdsDirectoryItemRef& directoryItem) {
if (!directoryItem) {
throw Exception();
}
EdsRetain(directoryItem);
mDirectoryItem = directoryItem;
EdsError error = EdsGetDirectoryItemInfo(mDirectoryItem, &mDirectoryItemInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get directory item info" << std::endl;
throw Exception();
}
}
CameraFile::~CameraFile() {
EdsRelease(mDirectoryItem);
mDirectoryItem = NULL;
}
#pragma mark - CAMERA
CameraRef Camera::create(const EdsCameraRef& camera) {
return CameraRef(new Camera(camera))->shared_from_this();
}
Camera::Camera(const EdsCameraRef& camera) : mHasOpenSession(false), mIsLiveViewActive(false) {
if (!camera) {
throw Exception();
}
EdsRetain(camera);
mCamera = camera;
EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get device info" << std::endl;
// TODO - NULL out mDeviceInfo
}
// set event handlers
error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set property event handler" << std::endl;
}
error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
}
Camera::~Camera() {
mRemovedHandler = NULL;
mFileAddedHandler = NULL;
if (mIsLiveViewActive) {
requestStopLiveView();
}
if (mHasOpenSession) {
requestCloseSession();
}
// NB - starting with EDSDK 2.10, this release will cause an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) at the end of the runloop
// EdsRelease(mCamera);
mCamera = nullptr;
}
#pragma mark -
void Camera::connectRemovedHandler(const std::function<void(CameraRef)>& handler) {
mRemovedHandler = handler;
}
void Camera::connectFileAddedHandler(const std::function<void(CameraRef, CameraFileRef)>& handler) {
mFileAddedHandler = handler;
}
EdsError Camera::requestOpenSession(const Settings &settings) {
if (mHasOpenSession) {
return EDS_ERR_SESSION_ALREADY_OPEN;
}
EdsError error = EdsOpenSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to open camera session" << std::endl;
return error;
}
mHasOpenSession = true;
mShouldKeepAlive = settings.getShouldKeepAlive();
EdsUInt32 saveTo = settings.getPictureSaveLocation();
error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set save destination host/device" << std::endl;
return error;
}
if (saveTo == kEdsSaveTo_Host) {
// ??? - requires UI lock?
EdsCapacity capacity = {0x7FFFFFFF, 0x1000, 1};
error = EdsSetCapacity(mCamera, capacity);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set capacity of host" << std::endl;
return error;
}
}
return EDS_ERR_OK;
}
EdsError Camera::requestCloseSession() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsCloseSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to close camera session" << std::endl;
return error;
}
mHasOpenSession = false;
return EDS_ERR_OK;
}
EdsError Camera::requestTakePicture() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsSendCommand(mCamera, kEdsCameraCommand_TakePicture, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to take picture" << std::endl;
}
return error;
}
void Camera::requestDownloadFile(const CameraFileRef& file, const fs::path& destinationFolderPath, const std::function<void(EdsError error, fs::path outputFilePath)>& callback) {
// check if destination exists and create if not
if (!fs::exists(destinationFolderPath)) {
bool status = fs::create_directories(destinationFolderPath);
if (!status) {
console() << "ERROR - failed to create destination folder path '" << destinationFolderPath << "'" << std::endl;
return callback(EDS_ERR_INTERNAL_ERROR, NULL);
}
}
fs::path filePath = destinationFolderPath / file->getName();
EdsStreamRef stream = NULL;
EdsError error = EdsCreateFileStream(filePath.generic_string().c_str(), kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create file stream" << std::endl;
goto download_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto download_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto download_cleanup;
}
download_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, filePath);
}
void Camera::requestReadFile(const CameraFileRef& file, const std::function<void(EdsError error, SurfaceRef surface)>& callback) {
Buffer buffer = NULL;
SurfaceRef surface = nullptr;
EdsStreamRef stream = NULL;
EdsError error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto read_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto read_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto read_cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto read_cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get stream length" << std::endl;
goto read_cleanup;
}
buffer = Buffer(data, length);
surface = Surface::create(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
read_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, surface);
}
EdsError Camera::requestStartLiveView() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
if (mIsLiveViewActive) {
return EDS_ERR_INTERNAL_ERROR;
}
EdsUInt32 device;
EdsError error = EdsGetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0, sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get output device for Live View" << std::endl;
return error;
}
// connect PC to Live View output device
device |= kEdsEvfOutputDevice_PC;
error = EdsSetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0 , sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set output device to connect PC to Live View output device" << std::endl;
return error;
}
mIsLiveViewActive = true;
return EDS_ERR_OK;
}
EdsError Camera::requestStopLiveView() {
if (!mIsLiveViewActive) {
return EDS_ERR_INTERNAL_ERROR;
}
EdsUInt32 device;
EdsError error = EdsGetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0, sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get output device for Live View" << std::endl;
return error;
}
// disconnect PC from Live View output device
device &= ~kEdsEvfOutputDevice_PC;
error = EdsSetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0 , sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set output device to disconnect PC from Live View output device" << std::endl;
return error;
}
mIsLiveViewActive = false;
return EDS_ERR_OK;
}
void Camera::toggleLiveView() {
if (mIsLiveViewActive) {
requestStopLiveView();
} else {
requestStartLiveView();
}
}
void Camera::requestLiveViewImage(const std::function<void(EdsError error, SurfaceRef surface)>& callback) {
EdsError error = EDS_ERR_OK;
EdsStreamRef stream = NULL;
EdsEvfImageRef evfImage = NULL;
Buffer buffer = NULL;
SurfaceRef surface = nullptr;
if (!mIsLiveViewActive) {
error = EDS_ERR_INTERNAL_ERROR;
goto cleanup;
}
error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto cleanup;
}
error = EdsCreateEvfImageRef(stream, &evfImage);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create Evf image" << std::endl;
goto cleanup;
}
error = EdsDownloadEvfImage(mCamera, evfImage);
if (error != EDS_ERR_OK) {
if (error == EDS_ERR_OBJECT_NOTREADY) {
console() << "ERROR - failed to download Evf image, not ready yet" << std::endl;
} else {
console() << "ERROR - failed to download Evf image" << std::endl;
}
goto cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get Evf image length" << std::endl;
goto cleanup;
}
if (length == 0) {
goto cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto cleanup;
}
buffer = Buffer(data, length);
surface = Surface::create(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
cleanup:
if (stream) {
EdsRelease(stream);
}
if (evfImage) {
EdsRelease(evfImage);
}
callback(error, surface);
}
#pragma mark - CALLBACKS
EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 event, EdsBaseRef ref, EdsVoid* context) {
Camera* c = (Camera*)context;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (event) {
case kEdsObjectEvent_DirItemRequestTransfer: {
EdsDirectoryItemRef directoryItem = (EdsDirectoryItemRef)ref;
CameraFileRef file = nullptr;
try {
file = CameraFile::create(directoryItem);
} catch (...) {
EdsRelease(directoryItem);
break;
}
EdsRelease(directoryItem);
directoryItem = NULL;
if (camera->mFileAddedHandler) {
camera->mFileAddedHandler(camera, file);
}
break;
}
default:
if (ref) {
EdsRelease(ref);
ref = NULL;
}
break;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 event, EdsUInt32 propertyID, EdsUInt32 param, EdsVoid* context) {
if (propertyID == kEdsPropID_Evf_OutputDevice && event == kEdsPropertyEvent_PropertyChanged) {
// console() << "output device changed, Live View possibly ready" << std::endl;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 event, EdsUInt32 param, EdsVoid* context) {
Camera* c = (Camera*)context;
CameraRef camera = c->shared_from_this();
switch (event) {
case kEdsStateEvent_WillSoonShutDown:
if (camera->mHasOpenSession && camera->mShouldKeepAlive) {
EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to extend shut down timer" << std::endl;
}
}
break;
case kEdsStateEvent_Shutdown:
camera->requestCloseSession();
// send handler and browser removal notices
if (camera->mRemovedHandler) {
camera->mRemovedHandler(camera);
}
CameraBrowser::instance()->removeCamera(camera);
break;
default:
break;
}
return EDS_ERR_OK;
}
}}
<commit_msg>fix error from boost upgrade<commit_after>//
// Camera.cpp
// Cinder-EDSDK
//
// Created by Jean-Pierre Mouilleseaux on 08 Dec 2013.
// Copyright 2013-2015 Chorded Constructions. All rights reserved.
//
#include "Camera.h"
#include "CameraBrowser.h"
using namespace ci;
using namespace ci::app;
namespace Cinder { namespace EDSDK {
#pragma mark CAMERA FILE
CameraFileRef CameraFile::create(const EdsDirectoryItemRef& directoryItem) {
return CameraFileRef(new CameraFile(directoryItem))->shared_from_this();
}
CameraFile::CameraFile(const EdsDirectoryItemRef& directoryItem) {
if (!directoryItem) {
throw Exception();
}
EdsRetain(directoryItem);
mDirectoryItem = directoryItem;
EdsError error = EdsGetDirectoryItemInfo(mDirectoryItem, &mDirectoryItemInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get directory item info" << std::endl;
throw Exception();
}
}
CameraFile::~CameraFile() {
EdsRelease(mDirectoryItem);
mDirectoryItem = NULL;
}
#pragma mark - CAMERA
CameraRef Camera::create(const EdsCameraRef& camera) {
return CameraRef(new Camera(camera))->shared_from_this();
}
Camera::Camera(const EdsCameraRef& camera) : mHasOpenSession(false), mIsLiveViewActive(false) {
if (!camera) {
throw Exception();
}
EdsRetain(camera);
mCamera = camera;
EdsError error = EdsGetDeviceInfo(mCamera, &mDeviceInfo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get device info" << std::endl;
// TODO - NULL out mDeviceInfo
}
// set event handlers
error = EdsSetObjectEventHandler(mCamera, kEdsObjectEvent_All, Camera::handleObjectEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
error = EdsSetPropertyEventHandler(mCamera, kEdsPropertyEvent_All, Camera::handlePropertyEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set property event handler" << std::endl;
}
error = EdsSetCameraStateEventHandler(mCamera, kEdsStateEvent_All, Camera::handleStateEvent, this);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set object event handler" << std::endl;
}
}
Camera::~Camera() {
mRemovedHandler = NULL;
mFileAddedHandler = NULL;
if (mIsLiveViewActive) {
requestStopLiveView();
}
if (mHasOpenSession) {
requestCloseSession();
}
// NB - starting with EDSDK 2.10, this release will cause an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) at the end of the runloop
// EdsRelease(mCamera);
mCamera = nullptr;
}
#pragma mark -
void Camera::connectRemovedHandler(const std::function<void(CameraRef)>& handler) {
mRemovedHandler = handler;
}
void Camera::connectFileAddedHandler(const std::function<void(CameraRef, CameraFileRef)>& handler) {
mFileAddedHandler = handler;
}
EdsError Camera::requestOpenSession(const Settings &settings) {
if (mHasOpenSession) {
return EDS_ERR_SESSION_ALREADY_OPEN;
}
EdsError error = EdsOpenSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to open camera session" << std::endl;
return error;
}
mHasOpenSession = true;
mShouldKeepAlive = settings.getShouldKeepAlive();
EdsUInt32 saveTo = settings.getPictureSaveLocation();
error = EdsSetPropertyData(mCamera, kEdsPropID_SaveTo, 0, sizeof(saveTo) , &saveTo);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set save destination host/device" << std::endl;
return error;
}
if (saveTo == kEdsSaveTo_Host) {
// ??? - requires UI lock?
EdsCapacity capacity = {0x7FFFFFFF, 0x1000, 1};
error = EdsSetCapacity(mCamera, capacity);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set capacity of host" << std::endl;
return error;
}
}
return EDS_ERR_OK;
}
EdsError Camera::requestCloseSession() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsCloseSession(mCamera);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to close camera session" << std::endl;
return error;
}
mHasOpenSession = false;
return EDS_ERR_OK;
}
EdsError Camera::requestTakePicture() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
EdsError error = EdsSendCommand(mCamera, kEdsCameraCommand_TakePicture, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to take picture" << std::endl;
}
return error;
}
void Camera::requestDownloadFile(const CameraFileRef& file, const fs::path& destinationFolderPath, const std::function<void(EdsError error, fs::path outputFilePath)>& callback) {
// check if destination exists and create if not
if (!fs::exists(destinationFolderPath)) {
bool status = fs::create_directories(destinationFolderPath);
if (!status) {
console() << "ERROR - failed to create destination folder path '" << destinationFolderPath << "'" << std::endl;
return callback(EDS_ERR_INTERNAL_ERROR, "");
}
}
fs::path filePath = destinationFolderPath / file->getName();
EdsStreamRef stream = NULL;
EdsError error = EdsCreateFileStream(filePath.generic_string().c_str(), kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create file stream" << std::endl;
goto download_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto download_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto download_cleanup;
}
download_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, filePath);
}
void Camera::requestReadFile(const CameraFileRef& file, const std::function<void(EdsError error, SurfaceRef surface)>& callback) {
Buffer buffer = NULL;
SurfaceRef surface = nullptr;
EdsStreamRef stream = NULL;
EdsError error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto read_cleanup;
}
error = EdsDownload(file->mDirectoryItem, file->getSize(), stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to download" << std::endl;
goto read_cleanup;
}
error = EdsDownloadComplete(file->mDirectoryItem);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to mark download as complete" << std::endl;
goto read_cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto read_cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get stream length" << std::endl;
goto read_cleanup;
}
buffer = Buffer(data, length);
surface = Surface::create(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
read_cleanup:
if (stream) {
EdsRelease(stream);
}
callback(error, surface);
}
EdsError Camera::requestStartLiveView() {
if (!mHasOpenSession) {
return EDS_ERR_SESSION_NOT_OPEN;
}
if (mIsLiveViewActive) {
return EDS_ERR_INTERNAL_ERROR;
}
EdsUInt32 device;
EdsError error = EdsGetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0, sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get output device for Live View" << std::endl;
return error;
}
// connect PC to Live View output device
device |= kEdsEvfOutputDevice_PC;
error = EdsSetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0 , sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set output device to connect PC to Live View output device" << std::endl;
return error;
}
mIsLiveViewActive = true;
return EDS_ERR_OK;
}
EdsError Camera::requestStopLiveView() {
if (!mIsLiveViewActive) {
return EDS_ERR_INTERNAL_ERROR;
}
EdsUInt32 device;
EdsError error = EdsGetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0, sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get output device for Live View" << std::endl;
return error;
}
// disconnect PC from Live View output device
device &= ~kEdsEvfOutputDevice_PC;
error = EdsSetPropertyData(mCamera, kEdsPropID_Evf_OutputDevice, 0 , sizeof(device), &device);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to set output device to disconnect PC from Live View output device" << std::endl;
return error;
}
mIsLiveViewActive = false;
return EDS_ERR_OK;
}
void Camera::toggleLiveView() {
if (mIsLiveViewActive) {
requestStopLiveView();
} else {
requestStartLiveView();
}
}
void Camera::requestLiveViewImage(const std::function<void(EdsError error, SurfaceRef surface)>& callback) {
EdsError error = EDS_ERR_OK;
EdsStreamRef stream = NULL;
EdsEvfImageRef evfImage = NULL;
Buffer buffer = NULL;
SurfaceRef surface = nullptr;
if (!mIsLiveViewActive) {
error = EDS_ERR_INTERNAL_ERROR;
goto cleanup;
}
error = EdsCreateMemoryStream(0, &stream);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create memory stream" << std::endl;
goto cleanup;
}
error = EdsCreateEvfImageRef(stream, &evfImage);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to create Evf image" << std::endl;
goto cleanup;
}
error = EdsDownloadEvfImage(mCamera, evfImage);
if (error != EDS_ERR_OK) {
if (error == EDS_ERR_OBJECT_NOTREADY) {
console() << "ERROR - failed to download Evf image, not ready yet" << std::endl;
} else {
console() << "ERROR - failed to download Evf image" << std::endl;
}
goto cleanup;
}
EdsUInt32 length;
error = EdsGetLength(stream, &length);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get Evf image length" << std::endl;
goto cleanup;
}
if (length == 0) {
goto cleanup;
}
void* data;
error = EdsGetPointer(stream, (EdsVoid**)&data);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to get pointer from stream" << std::endl;
goto cleanup;
}
buffer = Buffer(data, length);
surface = Surface::create(loadImage(DataSourceBuffer::create(buffer), ImageSource::Options(), "jpg"));
cleanup:
if (stream) {
EdsRelease(stream);
}
if (evfImage) {
EdsRelease(evfImage);
}
callback(error, surface);
}
#pragma mark - CALLBACKS
EdsError EDSCALLBACK Camera::handleObjectEvent(EdsUInt32 event, EdsBaseRef ref, EdsVoid* context) {
Camera* c = (Camera*)context;
CameraRef camera = CameraBrowser::instance()->cameraForPortName(c->getPortName());
switch (event) {
case kEdsObjectEvent_DirItemRequestTransfer: {
EdsDirectoryItemRef directoryItem = (EdsDirectoryItemRef)ref;
CameraFileRef file = nullptr;
try {
file = CameraFile::create(directoryItem);
} catch (...) {
EdsRelease(directoryItem);
break;
}
EdsRelease(directoryItem);
directoryItem = NULL;
if (camera->mFileAddedHandler) {
camera->mFileAddedHandler(camera, file);
}
break;
}
default:
if (ref) {
EdsRelease(ref);
ref = NULL;
}
break;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsUInt32 event, EdsUInt32 propertyID, EdsUInt32 param, EdsVoid* context) {
if (propertyID == kEdsPropID_Evf_OutputDevice && event == kEdsPropertyEvent_PropertyChanged) {
// console() << "output device changed, Live View possibly ready" << std::endl;
}
return EDS_ERR_OK;
}
EdsError EDSCALLBACK Camera::handleStateEvent(EdsUInt32 event, EdsUInt32 param, EdsVoid* context) {
Camera* c = (Camera*)context;
CameraRef camera = c->shared_from_this();
switch (event) {
case kEdsStateEvent_WillSoonShutDown:
if (camera->mHasOpenSession && camera->mShouldKeepAlive) {
EdsError error = EdsSendCommand(camera->mCamera, kEdsCameraCommand_ExtendShutDownTimer, 0);
if (error != EDS_ERR_OK) {
console() << "ERROR - failed to extend shut down timer" << std::endl;
}
}
break;
case kEdsStateEvent_Shutdown:
camera->requestCloseSession();
// send handler and browser removal notices
if (camera->mRemovedHandler) {
camera->mRemovedHandler(camera);
}
CameraBrowser::instance()->removeCamera(camera);
break;
default:
break;
}
return EDS_ERR_OK;
}
}}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QSerialPort>
#include "../arduino_st/simple_comm.h"
#include <thread>
#include <chrono>
#include "union_cast.h"
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
#include "stell_msg.h"
#include "star_math.h"
#include <QDir>
#include <QFileDialog>
#include <QtSql/QtSql>
//if defined - writes all Z-readings to the file (for debug purposes)
//#define EXPORT_Z
#define SQL_DRIVER "QSQLITE"
#ifdef EXPORT_Z
#include <QFile>
#ifndef NO_STELLARIUM_RUN
#define NO_STELLARIUM_RUN
#endif
#endif
Q_DECLARE_METATYPE(QSerialPortInfo);
static const QString nightScheme = "QWidget {background-color: #660000;}";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
comThread(nullptr),
skipWrite(ATOMIC_FLAG_INIT),
gaz(0), gel(0),
server(nullptr),
readyToTrackMap(false)
{
ui->setupUi(this);
setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint);
ui->latBox->setPrefixType(AngleSpinBox::PrefixType::Latitude);
ui->lonBox->setPrefixType(AngleSpinBox::PrefixType::Longitude);
database = QSqlDatabase::addDatabase(SQL_DRIVER, "DB");
connect(this, &MainWindow::onArduinoRead, this, &MainWindow::arduinoRead, Qt::QueuedConnection);
server = std::make_shared<QTcpServer>(nullptr);
connect(server.get(), &QTcpServer::newConnection, this, [this]()
{
static uint64_t connCounter = 0;
auto dumb = connCounter++;
QPointer<QTcpSocket> tmp = stellarium[dumb] = server->nextPendingConnection();
connect(tmp, &QAbstractSocket::disconnected, this, [this, dumb, tmp]()
{
if (stellarium.count(dumb))
stellarium.erase(dumb);
if (tmp)
tmp->deleteLater();
}, Qt::QueuedConnection);
connect(tmp, &QTcpSocket::readyRead, this, [this, tmp]()
{
if (tmp)
onStellariumDataReady(tmp);
}, Qt::QueuedConnection);
}, Qt::QueuedConnection);
server->listen(QHostAddress::Any, 10001);
on_pushButton_clicked();
readSettings(this);
}
MainWindow::~MainWindow()
{
comThread.reset();
writeSettings(this);
if (database.isOpen())
database.close();
delete ui;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::recurseRead(QSettings &settings, QObject *object)
{
Q_UNUSED(object);
auto ps = settings.value("COMPort", "").toString();
ui->cbPorts->setCurrentText(ps);
ui->lonBox->setRadians(settings.value("Longitude", 0).toDouble());
ui->latBox->setRadians(settings.value("Latitude", 0).toDouble());
ui->cbNight->setChecked(settings.value("Night", false).toBool());
ui->cbUseDb->setChecked(settings.value("UseDb", true).toBool());
ui->editFolder->setText(settings.value("Folder", QDir::homePath()).toString());
}
void MainWindow::recurseWrite(QSettings &settings, QObject *object)
{
Q_UNUSED(object);
auto ps = ui->cbPorts->currentText();
settings.setValue("COMPort", ps);
settings.setValue("Longitude", ui->lonBox->valueRadians());
settings.setValue("Latitude", ui->latBox->valueRadians());
settings.setValue("Night", ui->cbNight->isChecked());
settings.setValue("UseDb", ui->cbUseDb->isChecked());
settings.setValue("Folder", ui->editFolder->text());
}
void MainWindow::on_pushButton_clicked()
{
readyToTrackMap = false;
comThread.reset();
ui->cbPorts->clear();
ui->cbPorts->addItem("Select to Stop");
ui->cbPorts->blockSignals(true);
auto pl = QSerialPortInfo::availablePorts();
for (const auto& p : pl)
ui->cbPorts->addItem(p.portName(), QVariant::fromValue<QSerialPortInfo>(p));
ui->cbPorts->setCurrentIndex(0);
ui->cbPorts->blockSignals(false);
}
void MainWindow::on_cbPorts_currentIndexChanged(int index)
{
if (index > 0)
startComPoll();
else
comThread.reset();
}
void MainWindow::startComPoll()
{
comThread = utility::startNewRunner([this](auto stop)
{
using namespace std::chrono_literals;
using namespace ard_st;
#ifdef EXPORT_Z
QFile of (QDir::homePath()+"/sensor_values.csv");
long os_counter = 0;
of.open(QFile::WriteOnly | QFile::Truncate | QFile::Text);
of.write("Azimuth, Altitude, W, X, Y, Z, Sample\n");
#endif
while (!(*stop)) //device reconnect loop
{
QSerialPort port(ui->cbPorts->currentData().value<QSerialPortInfo>());
port.setBaudRate(115200);
//8N1 default settings
port.setDataBits(QSerialPort::Data8);
port.setParity(QSerialPort::Parity::NoParity);
port.setStopBits(QSerialPort::OneStop);
const bool op = port.open(QIODevice::ReadWrite);
std::this_thread::sleep_for(15s); // device gets reset, have to wait
port.setDataTerminalReady(false); //disable autoreset of device
skipWrite.test_and_set();
readyToTrackMap = false;
uint64_t counter = 0;
while (!(*stop))
{
if (op) //if failed to open, still should start thread which does nothing
{
const static std::string header(MESSAGE_HDR);
Message msg;
packAzEl(msg.message.value, gaz, gel);
bool shouldSet = !skipWrite.test_and_set();
if (shouldSet)
{
//cleansing all sensor data there and let'em gather some
msg.message.Command = 'C';
port.write(header.c_str(), static_cast<int>(header.size()));
port.write(msg.buffer, sizeof(msg.buffer));
if (*stop || !port.waitForBytesWritten(5000))
break;
std::this_thread::sleep_for(500ms);
}
msg.message.Command = (shouldSet)?'S':'R';
port.write(header.c_str(), static_cast<int>(header.size()));
port.write(msg.buffer, sizeof(msg.buffer));
if (*stop || !port.waitForBytesWritten(5000))
break;
readyToTrackMap = readyToTrackMap || shouldSet;
if (!shouldSet)
{
const static auto msz = static_cast<decltype (port.bytesAvailable())>(sizeof(msg.message.value));
for(int i = 0; i < 100 && !(*stop) && port.bytesAvailable() < msz; ++i)
std::this_thread::sleep_for(20ms);
if (sizeof(msg.message.value.buffer) == port.read(msg.message.value.buffer, sizeof(msg.message.value.buffer)))
{
float az, el;
readAzEl(msg.message.value, &az, &el);
//qDebug() <<"Az = " <<degrees(az) << "; El = "<<degrees(el);
emit this->onArduinoRead(az, el);
#ifdef EXPORT_Z
const static double div = 1 << (8 * sizeof(msg.message.value.vals.current_quat[0]) - 1);
of.write(QString("%1,%2,%3,%4,%5,%6,%7\n")
.arg(degrees(az))
.arg(degrees(el))
.arg(msg.message.value.vals.current_quat[0] / div)
.arg(msg.message.value.vals.current_quat[1] / div)
.arg(msg.message.value.vals.current_quat[2] / div)
.arg(msg.message.value.vals.current_quat[3] / div)
.arg(os_counter++).toUtf8());
#endif
}
}
else
++counter;
}
else
break;
std::this_thread::sleep_for(500ms);
}
if (!(*stop))
std::this_thread::sleep_for(5000ms);
}
});
}
void MainWindow::writeToArduino(float az_rad, float el_rad)
{
gaz = az_rad;
gel = el_rad;
skipWrite.clear();
}
int64_t MainWindow::getMicrosNow()
{
using namespace std::chrono;
return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
}
void MainWindow::arduinoRead(float az_rad, float el_rad)
{
ui->lblAz-> setText(QString("%1").arg(degrees(az_rad)));
ui->lblAlt->setText(QString("%1").arg(degrees(el_rad)));
if (readyToTrackMap && stellarium.size())
{
//writting alt/az from arduino to stellarium
double ra, dec;
convertAZ_RA(static_cast<double>(az_rad), static_cast<double>(el_rad), ui->latBox->valueRadians(), ui->lonBox->valueRadians(), ra, dec);
//qDebug() << "Az(deg): "<< degrees(az_rad)<<" ALT(deg): "<<degrees(el_rad);
//qDebug() << "RA(hrs): "<< degrees(ra) / 15 << " DEC(deg): "<< degrees(dec);
if (stellarium.size())
{
ToStellMessage msg;
msg.msg.size = sizeof(ToStellMessage);
msg.msg.type = 0;
msg.msg.status = 0;
msg.msg.clientMicros = getMicrosNow();
//from ServerDummy.cpp
msg.msg.ra_int = static_cast<decltype(msg.msg.ra_int)>(floor(0.5 + ra * static_cast<uint64_t>(0x80000000)/M_PI));
msg.msg.dec_int = static_cast<decltype(msg.msg.dec_int)>(floor(0.5 + dec * static_cast<uint64_t>(0x80000000)/M_PI)); //yes, uint64_t or u get negated dec
for (const auto & s : stellarium)
{
s.second->write(msg.buffer, sizeof(ToStellMessage));
}
if (ui->cbUseDb->isChecked())
{
if (!database.isOpen())
{
const static QString datestr = QDate::currentDate().toString("dd_MMM_yyyy");
QString sqlDb = ui->editFolder->text() + QDir::separator() + datestr + "_startrack.db";
database.setDatabaseName(sqlDb);
if (database.open())
{
//ensruing it has all needed tables
QSqlQuery sql(database);
qDebug() <<"CREATE TABLE: " <<
sql.exec("CREATE TABLE IF NOT EXISTS Track(ID integer primary key asc, "
"Az_rad REAL not null, Alt_rad REAL not null, LocalDt INTEGER not null, RA_rad not null, DEC_rad not null, "
"W INTEGER, X INTEGER, Y INTEGER, Z INTEGER);"
);
qDebug() <<"CREATE INDEX: " <<
sql.exec("CREATE UNIQUE INDEX IF NOT EXISTS Track_LocalDt ON Track(LocalDt);");
}
}
if (database.isOpen())
{
QSqlQuery sql(database);
sql.exec(QString("INSERT OR REPLACE INTO Track(Az_rad, Alt_rad, RA_rad, DEC_rad, LocalDt) VALUES(%1, %2, %3, %4, %5)")
.arg(az_rad).arg(el_rad).arg(ra).arg(dec)
.arg(QDateTime::currentMSecsSinceEpoch()));
}
}
}
}
}
void MainWindow::onStellariumDataReady(QTcpSocket *p)
{
auto all = p->readAll();
u_int16_t size = *reinterpret_cast<uint16_t*>(all.data()); //size counts itself, but we dont place it in packet
//qDebug() << "Packet Size: "<<size;
if (!(size < 4 || size > all.size() || size - 2 > sizeof(StellBasicMessage)))
{
StellBasicMessage msg;
memcpy(msg.buffer, all.data() + 2, size - 2);
//qDebug() << msg.msg.clientMicros << msg.msg.ra_int << msg.msg.dec_int;
//took from ServerDummy.cpp, it is RADIANS now as we want
const double ra = msg.msg.ra_int * (M_PI/static_cast<uint64_t>(0x80000000));
const double dec = msg.msg.dec_int * (M_PI/static_cast<uint64_t>(0x80000000));
// qDebug() << "RA(hrs): "<< degrees(ra) / 15 << " DEC(deg): "<< degrees(dec);
double az, alt;
convertRA_AZ(ra, dec, ui->latBox->valueRadians(), ui->lonBox->valueRadians(), az, alt);
//qDebug() << "Az(deg): "<< degrees(az)<<" ALT(deg): "<<degrees(alt);
writeToArduino(static_cast<float>(az), static_cast<float>(alt));
}
}
void MainWindow::on_cbNight_toggled(bool checked)
{
if (checked)
qApp->setStyleSheet(nightScheme);
else
qApp->setStyleSheet("");
}
void MainWindow::on_btnSelectFodler_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Select folderto save tracks"), ui->editFolder->text(),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
ui->editFolder->setText(dir);
if (database.isOpen())
database.close();
}
}
<commit_msg>small change to server, if device is lost - stop sending to stellarium immediatly<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QSerialPort>
#include "../arduino_st/simple_comm.h"
#include <thread>
#include <chrono>
#include "union_cast.h"
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
#include "stell_msg.h"
#include "star_math.h"
#include <QDir>
#include <QFileDialog>
#include <QtSql/QtSql>
//if defined - writes all Z-readings to the file (for debug purposes)
//#define EXPORT_Z
#define SQL_DRIVER "QSQLITE"
#ifdef EXPORT_Z
#include <QFile>
#ifndef NO_STELLARIUM_RUN
#define NO_STELLARIUM_RUN
#endif
#endif
Q_DECLARE_METATYPE(QSerialPortInfo);
static const QString nightScheme = "QWidget {background-color: #660000;}";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
comThread(nullptr),
skipWrite(ATOMIC_FLAG_INIT),
gaz(0), gel(0),
server(nullptr),
readyToTrackMap(false)
{
ui->setupUi(this);
setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint);
ui->latBox->setPrefixType(AngleSpinBox::PrefixType::Latitude);
ui->lonBox->setPrefixType(AngleSpinBox::PrefixType::Longitude);
database = QSqlDatabase::addDatabase(SQL_DRIVER, "DB");
connect(this, &MainWindow::onArduinoRead, this, &MainWindow::arduinoRead, Qt::QueuedConnection);
server = std::make_shared<QTcpServer>(nullptr);
connect(server.get(), &QTcpServer::newConnection, this, [this]()
{
static uint64_t connCounter = 0;
auto dumb = connCounter++;
QPointer<QTcpSocket> tmp = stellarium[dumb] = server->nextPendingConnection();
connect(tmp, &QAbstractSocket::disconnected, this, [this, dumb, tmp]()
{
if (stellarium.count(dumb))
stellarium.erase(dumb);
if (tmp)
tmp->deleteLater();
}, Qt::QueuedConnection);
connect(tmp, &QTcpSocket::readyRead, this, [this, tmp]()
{
if (tmp)
onStellariumDataReady(tmp);
}, Qt::QueuedConnection);
}, Qt::QueuedConnection);
server->listen(QHostAddress::Any, 10001);
on_pushButton_clicked();
readSettings(this);
}
MainWindow::~MainWindow()
{
comThread.reset();
writeSettings(this);
if (database.isOpen())
database.close();
delete ui;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::recurseRead(QSettings &settings, QObject *object)
{
Q_UNUSED(object);
auto ps = settings.value("COMPort", "").toString();
ui->cbPorts->setCurrentText(ps);
ui->lonBox->setRadians(settings.value("Longitude", 0).toDouble());
ui->latBox->setRadians(settings.value("Latitude", 0).toDouble());
ui->cbNight->setChecked(settings.value("Night", false).toBool());
ui->cbUseDb->setChecked(settings.value("UseDb", true).toBool());
ui->editFolder->setText(settings.value("Folder", QDir::homePath()).toString());
}
void MainWindow::recurseWrite(QSettings &settings, QObject *object)
{
Q_UNUSED(object);
auto ps = ui->cbPorts->currentText();
settings.setValue("COMPort", ps);
settings.setValue("Longitude", ui->lonBox->valueRadians());
settings.setValue("Latitude", ui->latBox->valueRadians());
settings.setValue("Night", ui->cbNight->isChecked());
settings.setValue("UseDb", ui->cbUseDb->isChecked());
settings.setValue("Folder", ui->editFolder->text());
}
void MainWindow::on_pushButton_clicked()
{
readyToTrackMap = false;
comThread.reset();
ui->cbPorts->clear();
ui->cbPorts->addItem("Select to Stop");
ui->cbPorts->blockSignals(true);
auto pl = QSerialPortInfo::availablePorts();
for (const auto& p : pl)
ui->cbPorts->addItem(p.portName(), QVariant::fromValue<QSerialPortInfo>(p));
ui->cbPorts->setCurrentIndex(0);
ui->cbPorts->blockSignals(false);
}
void MainWindow::on_cbPorts_currentIndexChanged(int index)
{
if (index > 0)
startComPoll();
else
comThread.reset();
}
void MainWindow::startComPoll()
{
comThread = utility::startNewRunner([this](auto stop)
{
using namespace std::chrono_literals;
using namespace ard_st;
#ifdef EXPORT_Z
QFile of (QDir::homePath()+"/sensor_values.csv");
long os_counter = 0;
of.open(QFile::WriteOnly | QFile::Truncate | QFile::Text);
of.write("Azimuth, Altitude, W, X, Y, Z, Sample\n");
#endif
while (!(*stop)) //device reconnect loop
{
QSerialPort port(ui->cbPorts->currentData().value<QSerialPortInfo>());
port.setBaudRate(115200);
//8N1 default settings
port.setDataBits(QSerialPort::Data8);
port.setParity(QSerialPort::Parity::NoParity);
port.setStopBits(QSerialPort::OneStop);
const bool op = port.open(QIODevice::ReadWrite);
std::this_thread::sleep_for(15s); // device gets reset, have to wait
port.setDataTerminalReady(false); //disable autoreset of device
skipWrite.test_and_set();
readyToTrackMap = false;
uint64_t counter = 0;
while (!(*stop))
{
if (op) //if failed to open, still should start thread which does nothing
{
const static std::string header(MESSAGE_HDR);
Message msg;
packAzEl(msg.message.value, gaz, gel);
bool shouldSet = !skipWrite.test_and_set();
if (shouldSet)
{
//cleansing all sensor data there and let'em gather some
msg.message.Command = 'C';
port.write(header.c_str(), static_cast<int>(header.size()));
port.write(msg.buffer, sizeof(msg.buffer));
if (*stop || !port.waitForBytesWritten(5000))
break;
std::this_thread::sleep_for(500ms);
}
msg.message.Command = (shouldSet)?'S':'R';
port.write(header.c_str(), static_cast<int>(header.size()));
port.write(msg.buffer, sizeof(msg.buffer));
if (*stop || !port.waitForBytesWritten(5000))
break;
readyToTrackMap = readyToTrackMap || shouldSet;
if (!shouldSet)
{
const static auto msz = static_cast<decltype (port.bytesAvailable())>(sizeof(msg.message.value));
for(int i = 0; i < 100 && !(*stop) && port.bytesAvailable() < msz; ++i)
std::this_thread::sleep_for(20ms);
if (sizeof(msg.message.value.buffer) == port.read(msg.message.value.buffer, sizeof(msg.message.value.buffer)))
{
float az, el;
readAzEl(msg.message.value, &az, &el);
//qDebug() <<"Az = " <<degrees(az) << "; El = "<<degrees(el);
emit this->onArduinoRead(az, el);
#ifdef EXPORT_Z
const static double div = 1 << (8 * sizeof(msg.message.value.vals.current_quat[0]) - 1);
of.write(QString("%1,%2,%3,%4,%5,%6,%7\n")
.arg(degrees(az))
.arg(degrees(el))
.arg(msg.message.value.vals.current_quat[0] / div)
.arg(msg.message.value.vals.current_quat[1] / div)
.arg(msg.message.value.vals.current_quat[2] / div)
.arg(msg.message.value.vals.current_quat[3] / div)
.arg(os_counter++).toUtf8());
#endif
}
}
else
++counter;
}
else
break;
std::this_thread::sleep_for(500ms);
}
readyToTrackMap = false;
if (!(*stop))
std::this_thread::sleep_for(5000ms);
}
});
}
void MainWindow::writeToArduino(float az_rad, float el_rad)
{
gaz = az_rad;
gel = el_rad;
skipWrite.clear();
}
int64_t MainWindow::getMicrosNow()
{
using namespace std::chrono;
return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
}
void MainWindow::arduinoRead(float az_rad, float el_rad)
{
ui->lblAz-> setText(QString("%1").arg(degrees(az_rad)));
ui->lblAlt->setText(QString("%1").arg(degrees(el_rad)));
if (readyToTrackMap && stellarium.size())
{
//writting alt/az from arduino to stellarium
double ra, dec;
convertAZ_RA(static_cast<double>(az_rad), static_cast<double>(el_rad), ui->latBox->valueRadians(), ui->lonBox->valueRadians(), ra, dec);
//qDebug() << "Az(deg): "<< degrees(az_rad)<<" ALT(deg): "<<degrees(el_rad);
//qDebug() << "RA(hrs): "<< degrees(ra) / 15 << " DEC(deg): "<< degrees(dec);
if (stellarium.size())
{
ToStellMessage msg;
msg.msg.size = sizeof(ToStellMessage);
msg.msg.type = 0;
msg.msg.status = 0;
msg.msg.clientMicros = getMicrosNow();
//from ServerDummy.cpp
msg.msg.ra_int = static_cast<decltype(msg.msg.ra_int)>(floor(0.5 + ra * static_cast<uint64_t>(0x80000000)/M_PI));
msg.msg.dec_int = static_cast<decltype(msg.msg.dec_int)>(floor(0.5 + dec * static_cast<uint64_t>(0x80000000)/M_PI)); //yes, uint64_t or u get negated dec
for (const auto & s : stellarium)
{
s.second->write(msg.buffer, sizeof(ToStellMessage));
}
if (ui->cbUseDb->isChecked())
{
if (!database.isOpen())
{
const static QString datestr = QDate::currentDate().toString("dd_MMM_yyyy");
QString sqlDb = ui->editFolder->text() + QDir::separator() + datestr + "_startrack.db";
database.setDatabaseName(sqlDb);
if (database.open())
{
//ensruing it has all needed tables
QSqlQuery sql(database);
qDebug() <<"CREATE TABLE: " <<
sql.exec("CREATE TABLE IF NOT EXISTS Track(ID integer primary key asc, "
"Az_rad REAL not null, Alt_rad REAL not null, LocalDt INTEGER not null, RA_rad not null, DEC_rad not null, "
"W INTEGER, X INTEGER, Y INTEGER, Z INTEGER);"
);
qDebug() <<"CREATE INDEX: " <<
sql.exec("CREATE UNIQUE INDEX IF NOT EXISTS Track_LocalDt ON Track(LocalDt);");
}
}
if (database.isOpen())
{
QSqlQuery sql(database);
sql.exec(QString("INSERT OR REPLACE INTO Track(Az_rad, Alt_rad, RA_rad, DEC_rad, LocalDt) VALUES(%1, %2, %3, %4, %5)")
.arg(az_rad).arg(el_rad).arg(ra).arg(dec)
.arg(QDateTime::currentMSecsSinceEpoch()));
}
}
}
}
}
void MainWindow::onStellariumDataReady(QTcpSocket *p)
{
auto all = p->readAll();
u_int16_t size = *reinterpret_cast<uint16_t*>(all.data()); //size counts itself, but we dont place it in packet
//qDebug() << "Packet Size: "<<size;
if (!(size < 4 || size > all.size() || size - 2 > sizeof(StellBasicMessage)))
{
StellBasicMessage msg;
memcpy(msg.buffer, all.data() + 2, size - 2);
//qDebug() << msg.msg.clientMicros << msg.msg.ra_int << msg.msg.dec_int;
//took from ServerDummy.cpp, it is RADIANS now as we want
const double ra = msg.msg.ra_int * (M_PI/static_cast<uint64_t>(0x80000000));
const double dec = msg.msg.dec_int * (M_PI/static_cast<uint64_t>(0x80000000));
// qDebug() << "RA(hrs): "<< degrees(ra) / 15 << " DEC(deg): "<< degrees(dec);
double az, alt;
convertRA_AZ(ra, dec, ui->latBox->valueRadians(), ui->lonBox->valueRadians(), az, alt);
//qDebug() << "Az(deg): "<< degrees(az)<<" ALT(deg): "<<degrees(alt);
writeToArduino(static_cast<float>(az), static_cast<float>(alt));
}
}
void MainWindow::on_cbNight_toggled(bool checked)
{
if (checked)
qApp->setStyleSheet(nightScheme);
else
qApp->setStyleSheet("");
}
void MainWindow::on_btnSelectFodler_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Select folderto save tracks"), ui->editFolder->text(),
QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
ui->editFolder->setText(dir);
if (database.isOpen())
database.close();
}
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* merge_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/merge_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
join_clauses_ = nullptr;
}
bool MergeJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false)
return status;
const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();
join_clauses_ = node.GetJoinClauses();
if (join_clauses_ == nullptr)
return false;
left_end_ = true;
right_end_ = true;
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool MergeJoinExecutor::DExecute() {
LOG_INFO("********** Merge Join executor :: 2 children \n");
if (right_end_) {
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
return false;
}
std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
right_tiles_.push_back(right.release());
LOG_INFO("size of right tiles: %lu", right_tiles_.size());
}
LOG_INFO("Got right tile \n");
if (left_end_) {
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
left_tiles_.push_back(left.release());
LOG_INFO("size of right tiles: %lu", left_tiles_.size());
}
LOG_INFO("Got left tile \n");
LogicalTile *left_tile = left_tiles_.back();
LogicalTile *right_tile = right_tiles_.back();
// Build output logical tile
auto output_tile = BuildOutputLogicalTile(left_tile, right_tile);
// Build position lists
auto position_lists = BuildPostitionLists(left_tile, right_tile);
// Get position list from two logical tiles
auto &left_tile_position_lists = left_tile->GetPositionLists();
auto &right_tile_position_lists = right_tile->GetPositionLists();
size_t left_tile_column_count = left_tile_position_lists.size();
size_t right_tile_column_count = right_tile_position_lists.size();
// TODO: What are these ?
size_t left_start_row = 0;
size_t right_start_row = 0;
size_t left_end_row = Advance(left_tile, left_start_row, true);
size_t right_end_row = Advance(right_tile, right_start_row, false);
while ((left_end_row > left_start_row) && (right_end_row > right_start_row)) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_start_row);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_start_row);
bool diff = false;
// try to match the join clauses
for (auto &clause : *join_clauses_) {
auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
nullptr);
auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
nullptr);
int ret = left_value.Compare(right_value);
if (ret < 0) {
// Left key < Right key, advance left
LOG_INFO("left < right, advance left");
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
diff = true;
break;
} else if (ret > 0) {
// Left key > Right key, advance right
LOG_INFO("left > right, advance right");
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
diff = true;
break;
}
// Left key == Right key, go check next join clause
}
if (diff) {
// join clauses are not matched, one of the tile has been advanced
continue;
}
// join clauses are matched, try to match predicate
LOG_INFO("one pair of tuples matches join clause");
// Join predicate exists
if (predicate_ != nullptr) {
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
// Join predicate is false. Advance both.
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
}
// sub tile matched, do a Cartesian product
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = left_start_row;
left_tile_row_itr < left_end_row; left_tile_row_itr++) {
for (size_t right_tile_row_itr = right_start_row;
right_tile_row_itr < right_end_row; right_tile_row_itr++) {
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < left_tile_column_count;
output_tile_column_itr++) {
position_lists[output_tile_column_itr].push_back(
left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]);
}
// Then, copy the elements in left logical tile's tuple
for (size_t output_tile_column_itr = 0;
output_tile_column_itr < right_tile_column_count;
output_tile_column_itr++) {
position_lists[left_tile_column_count + output_tile_column_itr]
.push_back(
right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]);
}
}
}
// then Advance both
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
// set the corresponding flags if left or right is end
// so that next execution time, it will be re executed
if (left_end_row == left_start_row) {
left_end_ = true;
}
if (right_end_row == right_start_row) {
right_end_ = true;
}
// Check if we have any matching tuples.
if (position_lists[0].size() > 0) {
output_tile->SetPositionListsAndVisibility(std::move(position_lists));
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
/**
* @brief Advance the row iterator until value changes in terms of the join clauses
* @return the end row number, [start_row, end_row) are the rows of the same value
* if the end_row == start_row, the subset is empty
*/
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
size_t end_row = start_row + 1;
size_t this_row = start_row;
size_t tuple_count = tile->GetTupleCount();
if (start_row >= tuple_count)
return start_row;
while (end_row < tuple_count) {
expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
this_row);
expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);
bool diff = false;
for (auto &clause : *join_clauses_) {
// Go through each join clauses
auto expr = is_left ? clause.left_.get() : clause.right_.get();
peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
nullptr);
peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
nullptr);
if (0 != this_value.Compare(next_value)) {
diff = true;
break;
}
}
if (diff) {
break;
}
// the two tuples are the same, we advance by 1
end_row++;
this_row = end_row;
}
LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
end_row - start_row);
return end_row;
}
} // namespace executor
} // namespace peloton
<commit_msg>refactor merge join executor<commit_after>/*-------------------------------------------------------------------------
*
* merge_join.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/executor/merge_join_executor.cpp
*
*-------------------------------------------------------------------------
*/
#include <vector>
#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for nested loop join executor.
* @param node Nested loop join node corresponding to this executor.
*/
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
join_clauses_ = nullptr;
}
bool MergeJoinExecutor::DInit() {
auto status = AbstractJoinExecutor::DInit();
if (status == false)
return status;
const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();
join_clauses_ = node.GetJoinClauses();
if (join_clauses_ == nullptr)
return false;
left_end_ = true;
right_end_ = true;
return true;
}
/**
* @brief Creates logical tiles from the two input logical tiles after applying
* join predicate.
* @return true on success, false otherwise.
*/
bool MergeJoinExecutor::DExecute() {
LOG_INFO("********** Merge Join executor :: 2 children \n");
if (right_end_) {
// Try to get next tile from RIGHT child
if (children_[1]->Execute() == false) {
LOG_INFO("Did not get right tile \n");
return false;
}
std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
right_tiles_.push_back(right.release());
LOG_INFO("size of right tiles: %lu", right_tiles_.size());
}
LOG_INFO("Got right tile \n");
if (left_end_) {
// Try to get next tile from LEFT child
if (children_[0]->Execute() == false) {
LOG_INFO("Did not get left tile \n");
return false;
}
std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
left_tiles_.push_back(left.release());
LOG_INFO("size of right tiles: %lu", left_tiles_.size());
}
LOG_INFO("Got left tile \n");
LogicalTile *left_tile = left_tiles_.back();
LogicalTile *right_tile = right_tiles_.back();
// Build output logical tile
auto output_tile = BuildOutputLogicalTile(left_tile, right_tile);
// Build position lists
LogicalTile::PositionListsBuilder pos_lists_builder(left_tile, right_tile);
// TODO: What are these ?
size_t left_start_row = 0;
size_t right_start_row = 0;
size_t left_end_row = Advance(left_tile, left_start_row, true);
size_t right_end_row = Advance(right_tile, right_start_row, false);
while ((left_end_row > left_start_row) && (right_end_row > right_start_row)) {
expression::ContainerTuple<executor::LogicalTile> left_tuple(
left_tile, left_start_row);
expression::ContainerTuple<executor::LogicalTile> right_tuple(
right_tile, right_start_row);
bool diff = false;
// try to match the join clauses
for (auto &clause : *join_clauses_) {
auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
nullptr);
auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
nullptr);
int ret = left_value.Compare(right_value);
if (ret < 0) {
// Left key < Right key, advance left
LOG_INFO("left < right, advance left");
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
diff = true;
break;
} else if (ret > 0) {
// Left key > Right key, advance right
LOG_INFO("left > right, advance right");
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
diff = true;
break;
}
// Left key == Right key, go check next join clause
}
if (diff) {
// join clauses are not matched, one of the tile has been advanced
continue;
}
// join clauses are matched, try to match predicate
LOG_INFO("one pair of tuples matches join clause");
// Join predicate exists
if (predicate_ != nullptr) {
if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
.IsFalse()) {
// Join predicate is false. Advance both.
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
}
// sub tile matched, do a Cartesian product
// Go over every pair of tuples in left and right logical tiles
for (size_t left_tile_row_itr = left_start_row;
left_tile_row_itr < left_end_row; left_tile_row_itr++) {
for (size_t right_tile_row_itr = right_start_row;
right_tile_row_itr < right_end_row; right_tile_row_itr++) {
// Insert a tuple into the output logical tile
// First, copy the elements in left logical tile's tuple
pos_lists_builder.AddRow(left_tile_row_itr, right_tile_row_itr);
}
}
// then Advance both
left_start_row = left_end_row;
left_end_row = Advance(left_tile, left_start_row, true);
right_start_row = right_end_row;
right_end_row = Advance(right_tile, right_start_row, false);
}
// set the corresponding flags if left or right is end
// so that next execution time, it will be re executed
if (left_end_row == left_start_row) {
left_end_ = true;
}
if (right_end_row == right_start_row) {
right_end_ = true;
}
// Check if we have any matching tuples.
if (pos_lists_builder.Size() > 0) {
output_tile->SetPositionListsAndVisibility(pos_lists_builder.Release());
SetOutput(output_tile.release());
return true;
}
// Try again
else {
// If we are out of any more pairs of child tiles to examine,
// then we will return false earlier in this function.
// So, we don't have to return false here.
DExecute();
}
return true;
}
/**
* @brief Advance the row iterator until value changes in terms of the join clauses
* @return the end row number, [start_row, end_row) are the rows of the same value
* if the end_row == start_row, the subset is empty
*/
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
size_t end_row = start_row + 1;
size_t this_row = start_row;
size_t tuple_count = tile->GetTupleCount();
if (start_row >= tuple_count)
return start_row;
while (end_row < tuple_count) {
expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
this_row);
expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);
bool diff = false;
for (auto &clause : *join_clauses_) {
// Go through each join clauses
auto expr = is_left ? clause.left_.get() : clause.right_.get();
peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
nullptr);
peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
nullptr);
if (0 != this_value.Compare(next_value)) {
diff = true;
break;
}
}
if (diff) {
break;
}
// the two tuples are the same, we advance by 1
end_row++;
this_row = end_row;
}
LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
end_row - start_row);
return end_row;
}
} // namespace executor
} // namespace peloton
<|endoftext|>
|
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
***********************************************************************
*
* Last port: operation/overlay/validate/FuzzyPointLocator.java rev. 1.1 (JTS-1.10)
*
**********************************************************************/
#include <geos/operation/overlay/validate/FuzzyPointLocator.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Point.h> // for Point upcast
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Location.h> // for Location::Value enum
#include <geos/util.h>
#include <cassert>
#include <functional>
#include <vector>
#include <sstream>
#include <memory> // for unique_ptr
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
#define COMPUTE_Z 1
#define USE_ELEVATION_MATRIX 1
#define USE_INPUT_AVGZ 0
using namespace std;
using namespace geos::geom;
using namespace geos::algorithm;
namespace geos {
namespace operation { // geos.operation
namespace overlay { // geos.operation.overlay
namespace validate { // geos.operation.overlay.validate
FuzzyPointLocator::FuzzyPointLocator(const geom::Geometry& geom,
double nTolerance)
:
g(geom),
tolerance(nTolerance),
ptLocator(),
linework(extractLineWork(g))
{
}
/*private*/
std::unique_ptr<Geometry>
FuzzyPointLocator::extractLineWork(const geom::Geometry& geom)
{
::geos::ignore_unused_variable_warning(geom);
vector<Geometry*>* lineGeoms = new vector<Geometry*>();
try { // geoms array will leak if an exception is thrown
for(size_t i = 0, n = g.getNumGeometries(); i < n; ++i) {
const Geometry* gComp = g.getGeometryN(i);
Geometry* lineGeom = nullptr;
// only get linework for polygonal components
if(gComp->getDimension() == 2) {
lineGeom = gComp->getBoundary().release();
lineGeoms->push_back(lineGeom);
}
}
return std::unique_ptr<Geometry>(g.getFactory()->buildGeometry(lineGeoms));
}
catch(...) { // avoid leaks
for(size_t i = 0, n = lineGeoms->size(); i < n; ++i) {
delete(*lineGeoms)[i];
}
delete lineGeoms;
throw;
}
}
/*private*/
std::unique_ptr<Geometry>
FuzzyPointLocator::getLineWork(const geom::Geometry& geom)
{
::geos::ignore_unused_variable_warning(geom);
vector<Geometry*>* lineGeoms = new vector<Geometry*>();
try { // geoms array will leak if an exception is thrown
for(size_t i = 0, n = g.getNumGeometries(); i < n; ++i) {
const Geometry* gComp = g.getGeometryN(i);
Geometry* lineGeom;
if(gComp->getDimension() == 2) {
lineGeom = gComp->getBoundary().release();
}
else {
lineGeom = gComp->clone().release();
}
lineGeoms->push_back(lineGeom);
}
return std::unique_ptr<Geometry>(g.getFactory()->buildGeometry(lineGeoms));
}
catch(...) { // avoid leaks
for(size_t i = 0, n = lineGeoms->size(); i < n; ++i) {
delete(*lineGeoms)[i];
}
delete lineGeoms;
throw;
}
}
/* public */
Location
FuzzyPointLocator::getLocation(const Coordinate& pt)
{
unique_ptr<Geometry> point(g.getFactory()->createPoint(pt));
double dist = linework->distance(point.get());
// if point is close to boundary, it is considered
// to be on the boundary
if(dist < tolerance) {
return Location::BOUNDARY;
}
// now we know point must be clearly inside or outside geometry,
// so return actual location value
return ptLocator.locate(pt, &g);
}
} // namespace geos.operation.overlay.validate
} // namespace geos.operation.overlay
} // namespace geos.operation
} // namespace geos
<commit_msg>Simplify FuzzyPointLocator<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
***********************************************************************
*
* Last port: operation/overlay/validate/FuzzyPointLocator.java rev. 1.1 (JTS-1.10)
*
**********************************************************************/
#include <geos/operation/overlay/validate/FuzzyPointLocator.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Point.h> // for Point upcast
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Location.h> // for Location::Value enum
#include <geos/util.h>
#include <cassert>
#include <functional>
#include <vector>
#include <sstream>
#include <memory> // for unique_ptr
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
#define COMPUTE_Z 1
#define USE_ELEVATION_MATRIX 1
#define USE_INPUT_AVGZ 0
using namespace geos::geom;
using namespace geos::algorithm;
namespace geos {
namespace operation { // geos.operation
namespace overlay { // geos.operation.overlay
namespace validate { // geos.operation.overlay.validate
FuzzyPointLocator::FuzzyPointLocator(const geom::Geometry& geom,
double nTolerance)
:
g(geom),
tolerance(nTolerance),
ptLocator(),
linework(extractLineWork(g))
{
}
/*private*/
std::unique_ptr<Geometry>
FuzzyPointLocator::extractLineWork(const geom::Geometry& geom)
{
::geos::ignore_unused_variable_warning(geom);
std::vector<std::unique_ptr<Geometry>> lineGeoms;
for(size_t i = 0, n = g.getNumGeometries(); i < n; ++i) {
const Geometry* gComp = g.getGeometryN(i);
// only get linework for polygonal components
if(gComp->getDimension() == Dimension::A) {
lineGeoms.push_back(gComp->getBoundary());
}
}
return g.getFactory()->buildGeometry(std::move(lineGeoms));
}
/*private*/
std::unique_ptr<Geometry>
FuzzyPointLocator::getLineWork(const geom::Geometry& geom)
{
::geos::ignore_unused_variable_warning(geom);
std::vector<std::unique_ptr<Geometry>> lineGeoms;
for(size_t i = 0, n = g.getNumGeometries(); i < n; ++i) {
const Geometry* gComp = g.getGeometryN(i);
if(gComp->getDimension() == 2) {
lineGeoms.push_back(gComp->getBoundary());
} else {
lineGeoms.push_back(gComp->clone());
}
}
return g.getFactory()->buildGeometry(std::move(lineGeoms));
}
/* public */
Location
FuzzyPointLocator::getLocation(const Coordinate& pt)
{
std::unique_ptr<Geometry> point(g.getFactory()->createPoint(pt));
double dist = linework->distance(point.get());
// if point is close to boundary, it is considered
// to be on the boundary
if(dist < tolerance) {
return Location::BOUNDARY;
}
// now we know point must be clearly inside or outside geometry,
// so return actual location value
return ptLocator.locate(pt, &g);
}
} // namespace geos.operation.overlay.validate
} // namespace geos.operation.overlay
} // namespace geos.operation
} // namespace geos
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2016 Alice Margatroid <loveoverwhelming@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "WavImporter.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Debug.h>
#include <Corrade/Utility/Endianness.h>
#include "MagnumPlugins/WavAudioImporter/WavHeader.h"
namespace Magnum { namespace Audio {
WavImporter::WavImporter() = default;
WavImporter::WavImporter(PluginManager::AbstractManager& manager, std::string plugin): AbstractImporter(manager, std::move(plugin)) {}
auto WavImporter::doFeatures() const -> Features { return Feature::OpenData; }
bool WavImporter::doIsOpened() const { return _data; }
void WavImporter::doOpenData(Containers::ArrayView<const char> data) {
/* Check file size */
if(data.size() < sizeof(WavHeaderChunk) + sizeof(WavFormatChunk) + sizeof(RiffChunk)) {
Error() << "Audio::WavImporter::openData(): the file is too short:" << data.size() << "bytes";
return;
}
/* Get the RIFF/WAV header */
WavHeaderChunk header(*reinterpret_cast<const WavHeaderChunk*>(data.begin()));
/* Check RIFF/WAV file signature */
if(std::strncmp(header.chunk.chunkId, "RIFF", 4) != 0 ||
std::strncmp(header.format, "WAVE", 4) != 0) {
Error() << "Audio::WavImporter::openData(): the file signature is invalid";
return;
}
Utility::Endianness::littleEndianInPlace(header.chunk.chunkSize);
/* Check file size */
if(header.chunk.chunkSize < 36 || header.chunk.chunkSize + 8 != data.size()) {
Error() << "Audio::WavImporter::openData(): the file has improper size, expected"
<< header.chunk.chunkSize + 8 << "but got" << data.size();
return;
}
const RiffChunk* dataChunk = nullptr;
const WavFormatChunk* formatChunk = nullptr;
UnsignedInt dataChunkSize = 0;
const UnsignedInt headerSize = sizeof(WavHeaderChunk);
UnsignedInt offset = 0;
/* Skip any chunks that aren't the format or data chunk */
while(headerSize + offset <= header.chunk.chunkSize) {
const RiffChunk* currChunk = reinterpret_cast<const RiffChunk*>(data.begin() + headerSize + offset);
offset += Utility::Endianness::littleEndian(currChunk->chunkSize) + sizeof(RiffChunk);
if(std::strncmp(currChunk->chunkId, "fmt ", 4) == 0) {
if(formatChunk != nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains too many format chunks";
return;
}
formatChunk = reinterpret_cast<const WavFormatChunk*>(currChunk);
} else if(std::strncmp(currChunk->chunkId, "data", 4) == 0) {
if(dataChunk != nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains too many data chunks";
return;
}
dataChunk = currChunk;
dataChunkSize = Utility::Endianness::littleEndian(currChunk->chunkSize);
break;
}
}
/* Make sure we actually got a format chunk */
if(formatChunk == nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains no format chunk";
return;
}
/* Make sure we actually got a data chunk */
if(dataChunk == nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains no data chunk";
return;
}
/* Fix endianness on Format chunk */
Utility::Endianness::littleEndianInPlace(
formatChunk->chunk.chunkSize, formatChunk->audioFormat, formatChunk->numChannels,
formatChunk->sampleRate, formatChunk->byteRate, formatChunk->blockAlign,
formatChunk->bitsPerSample);
/* Check PCM format */
if(formatChunk->audioFormat == WavAudioFormat::Pcm) {
/* Decide about format */
if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 8)
_format = Buffer::Format::Mono8;
else if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 16)
_format = Buffer::Format::Mono16;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 8)
_format = Buffer::Format::Stereo8;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 16)
_format = Buffer::Format::Stereo16;
else {
Error() << "Audio::WavImporter::openData(): PCM with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check IEEE Float format */
} else if(formatChunk->audioFormat == WavAudioFormat::IeeeFloat) {
if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 32)
_format = Buffer::Format::MonoFloat;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 32)
_format = Buffer::Format::StereoFloat;
else if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 64)
_format = Buffer::Format::MonoDouble;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 64)
_format = Buffer::Format::StereoDouble;
else {
Error() << "Audio::WavImporter::openData(): IEEE with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check A-Law format */
} else if(formatChunk->audioFormat == WavAudioFormat::ALaw) {
if(formatChunk->numChannels == 1)
_format = Buffer::Format::MonoALaw;
else if(formatChunk->numChannels == 2)
_format = Buffer::Format::StereoALaw;
else {
Error() << "Audio::WavImporter::openData(): ALaw with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check μ-Law format */
} else if(formatChunk->audioFormat == WavAudioFormat::MuLaw) {
if(formatChunk->numChannels == 1)
_format = Buffer::Format::MonoMuLaw;
else if(formatChunk->numChannels == 2)
_format = Buffer::Format::StereoMuLaw;
else {
Error() << "Audio::WavImporter::openData(): ULaw with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Unknown/unimplemented format */
} else {
Error() << "Audio::WavImporter::openData(): unsupported format" << formatChunk->audioFormat;
return;
}
/* Size sanity checks */
if(headerSize + offset > data.size()) {
Error() << "Audio::WavImporter::openData(): file size doesn't match computed size";
return;
}
/* Format sanity checks */
if(formatChunk->blockAlign != formatChunk->numChannels * formatChunk->bitsPerSample / 8 ||
formatChunk->byteRate != formatChunk->sampleRate * formatChunk->blockAlign) {
Error() << "Audio::WavImporter::openData(): the file is corrupted";
return;
}
/* Save frequency */
_frequency = formatChunk->sampleRate;
/** @todo Convert the data from little endian too */
CORRADE_INTERNAL_ASSERT(!Utility::Endianness::isBigEndian());
/* Copy the data */
const char* dataChunkPtr = reinterpret_cast<const char*>(dataChunk + 1);
_data = Containers::Array<char>(dataChunkSize);
std::copy(dataChunkPtr, dataChunkPtr+dataChunkSize, _data.begin());
return;
}
void WavImporter::doClose() { _data = nullptr; }
Buffer::Format WavImporter::doFormat() const { return _format; }
UnsignedInt WavImporter::doFrequency() const { return _frequency; }
Containers::Array<char> WavImporter::doData() {
Containers::Array<char> copy(_data.size());
std::copy(_data.begin(), _data.end(), copy.begin());
return copy;
}
}}
<commit_msg>WavAudioImporter: use MuLaw consistently.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <mosra@centrum.cz>
Copyright © 2016 Alice Margatroid <loveoverwhelming@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "WavImporter.h"
#include <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Debug.h>
#include <Corrade/Utility/Endianness.h>
#include "MagnumPlugins/WavAudioImporter/WavHeader.h"
namespace Magnum { namespace Audio {
WavImporter::WavImporter() = default;
WavImporter::WavImporter(PluginManager::AbstractManager& manager, std::string plugin): AbstractImporter(manager, std::move(plugin)) {}
auto WavImporter::doFeatures() const -> Features { return Feature::OpenData; }
bool WavImporter::doIsOpened() const { return _data; }
void WavImporter::doOpenData(Containers::ArrayView<const char> data) {
/* Check file size */
if(data.size() < sizeof(WavHeaderChunk) + sizeof(WavFormatChunk) + sizeof(RiffChunk)) {
Error() << "Audio::WavImporter::openData(): the file is too short:" << data.size() << "bytes";
return;
}
/* Get the RIFF/WAV header */
WavHeaderChunk header(*reinterpret_cast<const WavHeaderChunk*>(data.begin()));
/* Check RIFF/WAV file signature */
if(std::strncmp(header.chunk.chunkId, "RIFF", 4) != 0 ||
std::strncmp(header.format, "WAVE", 4) != 0) {
Error() << "Audio::WavImporter::openData(): the file signature is invalid";
return;
}
Utility::Endianness::littleEndianInPlace(header.chunk.chunkSize);
/* Check file size */
if(header.chunk.chunkSize < 36 || header.chunk.chunkSize + 8 != data.size()) {
Error() << "Audio::WavImporter::openData(): the file has improper size, expected"
<< header.chunk.chunkSize + 8 << "but got" << data.size();
return;
}
const RiffChunk* dataChunk = nullptr;
const WavFormatChunk* formatChunk = nullptr;
UnsignedInt dataChunkSize = 0;
const UnsignedInt headerSize = sizeof(WavHeaderChunk);
UnsignedInt offset = 0;
/* Skip any chunks that aren't the format or data chunk */
while(headerSize + offset <= header.chunk.chunkSize) {
const RiffChunk* currChunk = reinterpret_cast<const RiffChunk*>(data.begin() + headerSize + offset);
offset += Utility::Endianness::littleEndian(currChunk->chunkSize) + sizeof(RiffChunk);
if(std::strncmp(currChunk->chunkId, "fmt ", 4) == 0) {
if(formatChunk != nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains too many format chunks";
return;
}
formatChunk = reinterpret_cast<const WavFormatChunk*>(currChunk);
} else if(std::strncmp(currChunk->chunkId, "data", 4) == 0) {
if(dataChunk != nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains too many data chunks";
return;
}
dataChunk = currChunk;
dataChunkSize = Utility::Endianness::littleEndian(currChunk->chunkSize);
break;
}
}
/* Make sure we actually got a format chunk */
if(formatChunk == nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains no format chunk";
return;
}
/* Make sure we actually got a data chunk */
if(dataChunk == nullptr) {
Error() << "Audio::WavImporter::openData(): the file contains no data chunk";
return;
}
/* Fix endianness on Format chunk */
Utility::Endianness::littleEndianInPlace(
formatChunk->chunk.chunkSize, formatChunk->audioFormat, formatChunk->numChannels,
formatChunk->sampleRate, formatChunk->byteRate, formatChunk->blockAlign,
formatChunk->bitsPerSample);
/* Check PCM format */
if(formatChunk->audioFormat == WavAudioFormat::Pcm) {
/* Decide about format */
if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 8)
_format = Buffer::Format::Mono8;
else if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 16)
_format = Buffer::Format::Mono16;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 8)
_format = Buffer::Format::Stereo8;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 16)
_format = Buffer::Format::Stereo16;
else {
Error() << "Audio::WavImporter::openData(): PCM with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check IEEE Float format */
} else if(formatChunk->audioFormat == WavAudioFormat::IeeeFloat) {
if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 32)
_format = Buffer::Format::MonoFloat;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 32)
_format = Buffer::Format::StereoFloat;
else if(formatChunk->numChannels == 1 && formatChunk->bitsPerSample == 64)
_format = Buffer::Format::MonoDouble;
else if(formatChunk->numChannels == 2 && formatChunk->bitsPerSample == 64)
_format = Buffer::Format::StereoDouble;
else {
Error() << "Audio::WavImporter::openData(): IEEE with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check A-Law format */
} else if(formatChunk->audioFormat == WavAudioFormat::ALaw) {
if(formatChunk->numChannels == 1)
_format = Buffer::Format::MonoALaw;
else if(formatChunk->numChannels == 2)
_format = Buffer::Format::StereoALaw;
else {
Error() << "Audio::WavImporter::openData(): ALaw with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Check μ-Law format */
} else if(formatChunk->audioFormat == WavAudioFormat::MuLaw) {
if(formatChunk->numChannels == 1)
_format = Buffer::Format::MonoMuLaw;
else if(formatChunk->numChannels == 2)
_format = Buffer::Format::StereoMuLaw;
else {
Error() << "Audio::WavImporter::openData(): MuLaw with unsupported channel count"
<< formatChunk->numChannels << "with" << formatChunk->bitsPerSample
<< "bits per sample";
return;
}
/* Unknown/unimplemented format */
} else {
Error() << "Audio::WavImporter::openData(): unsupported format" << formatChunk->audioFormat;
return;
}
/* Size sanity checks */
if(headerSize + offset > data.size()) {
Error() << "Audio::WavImporter::openData(): file size doesn't match computed size";
return;
}
/* Format sanity checks */
if(formatChunk->blockAlign != formatChunk->numChannels * formatChunk->bitsPerSample / 8 ||
formatChunk->byteRate != formatChunk->sampleRate * formatChunk->blockAlign) {
Error() << "Audio::WavImporter::openData(): the file is corrupted";
return;
}
/* Save frequency */
_frequency = formatChunk->sampleRate;
/** @todo Convert the data from little endian too */
CORRADE_INTERNAL_ASSERT(!Utility::Endianness::isBigEndian());
/* Copy the data */
const char* dataChunkPtr = reinterpret_cast<const char*>(dataChunk + 1);
_data = Containers::Array<char>(dataChunkSize);
std::copy(dataChunkPtr, dataChunkPtr+dataChunkSize, _data.begin());
return;
}
void WavImporter::doClose() { _data = nullptr; }
Buffer::Format WavImporter::doFormat() const { return _format; }
UnsignedInt WavImporter::doFrequency() const { return _frequency; }
Containers::Array<char> WavImporter::doData() {
Containers::Array<char> copy(_data.size());
std::copy(_data.begin(), _data.end(), copy.begin());
return copy;
}
}}
<|endoftext|>
|
<commit_before>#include "r_functionwhitelist.h"
#include "stringutils.h"
//The following functions (and keywords that can be followed by a '(') will be allowed in user-entered R-code, such as filters or computed columns. This is for security because otherwise JASP-files could become a vector of attack and that doesn't refer to an R-datatype.
const std::set<std::string> R_FunctionWhiteList::functionWhiteList {
"AIC",
"Arg",
"Conj",
"Im",
"Mod",
"NCOL",
"Re",
"abs",
"acos",
"aggregate",
"anova",
"aov",
"apply",
"approx",
"array",
"as.Date",
"as.POSIXct",
"as.array",
"as.character",
"as.complex",
"as.data.frame",
"as.logical",
"as.numeric",
"as.factor",
"as.list",
"as.integer",
"asin",
"atan",
"atanh",
"atan2",
"attr",
"attributes",
"binom.test",
"by",
"c",
"cat",
"cbind",
"choose",
"class",
"coef",
"colMeans",
"colSums",
"colsum",
"convolve",
"cor",
"cos",
"cummax",
"cummin",
"cumprod",
"cumsum",
"cut",
"data.frame",
"density",
"deviance",
"df.residual",
"diag",
"diff",
"dim",
"dimnames",
"exp",
"expand.grid",
"factor",
"fft",
"filter",
"fitted",
"fishZ",
"for",
"format",
"function",
"gl",
"glm",
"grep",
"gsub",
"if",
"ifelse",
"ifElse",
"intersect",
"invFishZ",
"is.array",
"is.character",
"is.complex",
"is.data.frame",
"is.element",
"is.logical",
"is.na",
"is.null",
"is.numeric",
"lag",
"lapply",
"length",
"library",
"list",
"local",
"lm",
"loess",
"log",
"log10",
"logLik",
"ls",
"ls.srt",
"match",
"matrix",
"max",
"mean",
"median",
"merge",
"methods",
"min",
"mvfft",
"na.fail",
"na.omit",
"nchar",
"ncol",
"nlm",
"nls",
"nrow",
"optim",
"pairwise.t.test",
"paste",
"paste0",
"pmatch",
"pmax",
"pmin",
"power.t.test",
"predict",
"print",
"prod",
"prop.table",
"prop.test",
"quantile",
"range",
"rank",
"rbeta",
"rbind",
"rbinom",
"rcauchy",
"rchisq",
"rep",
"replicate",
"reshape",
"residuals",
"return",
"rev",
"rexp",
"rf",
"rgamma",
"rgeom",
"rhyper",
"rlnorm",
"rlogis",
"rnbinom",
"rnorm",
"round",
"rowMeans",
"rowSums",
"rowsum",
"rpois",
"rt",
"runif",
"rweibull",
"rwilcox",
"sample",
"scale",
"sd",
"seq",
"setdiff",
"setequal",
"sin",
"solve",
"sort",
"spline",
"sqrt",
"stack",
"str",
"strsplit",
"subset",
"substr",
"sum",
"summary",
"t",
"t.test",
"table",
"tan",
"tanh",
"tapply",
"tolower",
"toString",
"toupper",
"trimws",
"unclass",
"union",
"unique",
"unstack",
"var",
"weighted.mean",
"which",
"which.max",
"which.min",
"xtabs",
".setColumnDataAsScale", ".setColumnDataAsOrdinal", ".setColumnDataAsNominal", ".setColumnDataAsNominalText", "function", "stop",
"normalDist", "tDist", "chiSqDist", "fDist", "binomDist", "negBinomDist", "geomDist", "poisDist", "integerDist", "betaDist", "unifDist", "gammaDist", "expDist", "logNormDist", "weibullDist",
"replaceNA",
//Some distribution related stuff:
"dbeta", "pbeta", "qbeta", "rbeta",
"dbinom", "pbinom", "qbinom", "rbinom",
"dcauchy", "pcauchy", "qcauchy", "rcauchy",
"dchisq", "pchisq", "qchisq", "rchisq",
"dexp", "pexp", "qexp", "rexp",
"df", "pf", "qf", "rf",
"dgamma", "pgamma", "qgamma", "rgamma",
"dgeom", "pgeom", "qgeom", "rgeom",
"dhyper", "phyper", "qhyper", "rhyper",
"dlnorm", "plnorm", "qlnorm", "rlnorm",
"dmultinom", "pmultinom", "qmultinom", "rmultinom",
"dnbinom", "pnbinom", "qnbinom", "rnbinom",
"dnorm", "pnorm", "qnorm", "rnorm",
"dpois", "ppois", "qpois", "rpois",
"dt", "pt", "qt", "rt",
"dunif", "punif", "qunif", "runif",
"dweibull", "pweibull", "qweibull", "rweibull",
"dsignrank", "psignrank", "qsignrank", "rsignrank",
"pbirthday",
"ptukey",
"dwilcox"
#ifdef JASP_DEBUG
,"Sys.sleep", ".crashPlease", "stringi::stri_enc_mark", "stringi::stri_enc_toutf8", "Encoding"
#endif
};
std::string R_FunctionWhiteList::returnOrderedWhiteList()
{
std::stringstream out;
for(auto & s : functionWhiteList)
out << "\"" << s << "\"," << std::endl;
out << std::flush;
return out.str();
}
const std::string R_FunctionWhiteList::functionStartDelimit("(?:[;\\s\\(\"\\[\\+\\-\\=\\*\\%\\/\\{\\|&!]|^)"); //These should be all possible non-funtion-name-characters that could be right in front of any function-name in R.
const std::string R_FunctionWhiteList::functionNameStart("(?:\\.?[[:alpha:]])");
const std::string R_FunctionWhiteList::functionNameBody("(?:\\w|\\.|::)+");
const std::regex R_FunctionWhiteList::functionNameMatcher(functionStartDelimit + "(" + functionNameStart + functionNameBody + ")(?=[\\t \\r]*\\()");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctions(std::string const & script)
{
std::set<std::string> blackListedFunctionsFound;
auto foundFunctionsBegin = std::sregex_iterator(script.begin(), script.end(), functionNameMatcher);
auto foundFunctionsEnd = std::sregex_iterator();
for(auto foundFunctionIter = foundFunctionsBegin; foundFunctionIter != foundFunctionsEnd; foundFunctionIter++ )
{
std::string foundFunction((*foundFunctionIter)[1].str());
bool whiteListed = functionWhiteList.count(foundFunction) > 0;
if(!whiteListed && blackListedFunctionsFound.count(foundFunction) == 0)
blackListedFunctionsFound.insert(foundFunction);
}
return blackListedFunctionsFound;
}
const std::string R_FunctionWhiteList::operatorsR("`(?:\\+|-|\\*|/|%(?:/|\\*|in)?%|\\^|<=?|>=?|==?|!=?|<?<-|->>?|\\|\\|?|&&?|:|\\$)`");
const std::regex R_FunctionWhiteList::assignmentWhiteListedRightMatcher( "(" + functionNameStart + functionNameBody + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentWhiteListedLeftMatcher( "(?:->>?)\\s*(" + functionNameStart + functionNameBody + ")");
const std::regex R_FunctionWhiteList::assignmentOperatorRightMatcher( "(" + operatorsR + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentOperatorLeftMatcher( "(?:->>?)\\s*(" + operatorsR + ")");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctionsAliases(std::string const & script)
{
//Log::log() << "findIllegalFunctionsAliases with " << script << std::endl;
std::set<std::string> illegalAliasesFound;
auto aliasSearcher = [&illegalAliasesFound, &script](std::regex aliasAssignmentMatcher, bool (*lambdaMatchChecker)(std::string) )
{
auto foundAliasesBegin = std::sregex_iterator(script.begin(), script.end(), aliasAssignmentMatcher);
auto foundAliasesEnd = std::sregex_iterator();
for(auto foundAliasesIter = foundAliasesBegin; foundAliasesIter != foundAliasesEnd; foundAliasesIter++ )
{
std::string foundAlias((*foundAliasesIter)[1].str());
bool allowed = (*lambdaMatchChecker)(foundAlias);
//Log::log() << "I found alias assignment: " << foundAlias << " which is " << (allowed ? "allowed" : "not allowed") << ".." << std::endl;
if(!allowed)
illegalAliasesFound.insert(foundAlias);
}
};
aliasSearcher(assignmentOperatorLeftMatcher, [](std::string alias) { return false; }); //operators are never allowed
aliasSearcher(assignmentOperatorRightMatcher, [](std::string alias) { return false; });
aliasSearcher(assignmentWhiteListedLeftMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; }); //only allowed when the token being assigned to is not in whitelist
aliasSearcher(assignmentWhiteListedRightMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; });
//Log::log() << std::flush;
return illegalAliasesFound;
}
void R_FunctionWhiteList::scriptIsSafe(const std::string &script)
{
std::string commentFree = stringUtils::stripRComments(script);
static std::string errorMsg;
std::set<std::string> blackListedFunctions = findIllegalFunctions(commentFree);
if(blackListedFunctions.size() > 0)
{
bool moreThanOne = blackListedFunctions.size() > 1;
std::stringstream ssm;
ssm << "Non-whitelisted function" << (moreThanOne ? "s" : "") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & black : blackListedFunctions)
ssm << black << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
std::set<std::string> illegalAliasesFound = findIllegalFunctionsAliases(commentFree);
if(illegalAliasesFound.size() > 0)
{
bool moreThanOne = illegalAliasesFound.size() > 1;
std::stringstream ssm;
ssm << "Illegal assignment to " << (moreThanOne ? "operators or whitelisted functions" : "an operator or whitelisted function") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & alias : illegalAliasesFound)
ssm << alias << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
}
<commit_msg>Add switch to whitelist<commit_after>#include "r_functionwhitelist.h"
#include "stringutils.h"
//The following functions (and keywords that can be followed by a '(') will be allowed in user-entered R-code, such as filters or computed columns. This is for security because otherwise JASP-files could become a vector of attack and that doesn't refer to an R-datatype.
const std::set<std::string> R_FunctionWhiteList::functionWhiteList {
"AIC",
"Arg",
"Conj",
"Im",
"Mod",
"NCOL",
"Re",
"abs",
"acos",
"aggregate",
"anova",
"aov",
"apply",
"approx",
"array",
"as.Date",
"as.POSIXct",
"as.array",
"as.character",
"as.complex",
"as.data.frame",
"as.logical",
"as.numeric",
"as.factor",
"as.list",
"as.integer",
"asin",
"atan",
"atanh",
"atan2",
"attr",
"attributes",
"binom.test",
"by",
"c",
"cat",
"cbind",
"choose",
"class",
"coef",
"colMeans",
"colSums",
"colsum",
"convolve",
"cor",
"cos",
"cummax",
"cummin",
"cumprod",
"cumsum",
"cut",
"data.frame",
"density",
"deviance",
"df.residual",
"diag",
"diff",
"dim",
"dimnames",
"exp",
"expand.grid",
"factor",
"fft",
"filter",
"fitted",
"fishZ",
"for",
"format",
"function",
"gl",
"glm",
"grep",
"gsub",
"if",
"ifelse",
"ifElse",
"intersect",
"invFishZ",
"is.array",
"is.character",
"is.complex",
"is.data.frame",
"is.element",
"is.logical",
"is.na",
"is.null",
"is.numeric",
"lag",
"lapply",
"length",
"library",
"list",
"local",
"lm",
"loess",
"log",
"log10",
"logLik",
"ls",
"ls.srt",
"match",
"matrix",
"max",
"mean",
"median",
"merge",
"methods",
"min",
"mvfft",
"na.fail",
"na.omit",
"nchar",
"ncol",
"nlm",
"nls",
"nrow",
"optim",
"pairwise.t.test",
"paste",
"paste0",
"pmatch",
"pmax",
"pmin",
"power.t.test",
"predict",
"print",
"prod",
"prop.table",
"prop.test",
"quantile",
"range",
"rank",
"rbeta",
"rbind",
"rbinom",
"rcauchy",
"rchisq",
"rep",
"replicate",
"reshape",
"residuals",
"return",
"rev",
"rexp",
"rf",
"rgamma",
"rgeom",
"rhyper",
"rlnorm",
"rlogis",
"rnbinom",
"rnorm",
"round",
"rowMeans",
"rowSums",
"rowsum",
"rpois",
"rt",
"runif",
"rweibull",
"rwilcox",
"sample",
"scale",
"sd",
"seq",
"setdiff",
"setequal",
"sin",
"solve",
"sort",
"spline",
"sqrt",
"stack",
"str",
"strsplit",
"subset",
"substr",
"sum",
"summary",
"t",
"t.test",
"table",
"tan",
"tanh",
"tapply",
"tolower",
"toString",
"toupper",
"trimws",
"unclass",
"union",
"unique",
"unstack",
"var",
"weighted.mean",
"which",
"which.max",
"which.min",
"xtabs",
".setColumnDataAsScale", ".setColumnDataAsOrdinal", ".setColumnDataAsNominal", ".setColumnDataAsNominalText", "function", "stop",
"normalDist", "tDist", "chiSqDist", "fDist", "binomDist", "negBinomDist", "geomDist", "poisDist", "integerDist", "betaDist", "unifDist", "gammaDist", "expDist", "logNormDist", "weibullDist",
"replaceNA",
//Some distribution related stuff:
"dbeta", "pbeta", "qbeta", "rbeta",
"dbinom", "pbinom", "qbinom", "rbinom",
"dcauchy", "pcauchy", "qcauchy", "rcauchy",
"dchisq", "pchisq", "qchisq", "rchisq",
"dexp", "pexp", "qexp", "rexp",
"df", "pf", "qf", "rf",
"dgamma", "pgamma", "qgamma", "rgamma",
"dgeom", "pgeom", "qgeom", "rgeom",
"dhyper", "phyper", "qhyper", "rhyper",
"dlnorm", "plnorm", "qlnorm", "rlnorm",
"dmultinom", "pmultinom", "qmultinom", "rmultinom",
"dnbinom", "pnbinom", "qnbinom", "rnbinom",
"dnorm", "pnorm", "qnorm", "rnorm",
"dpois", "ppois", "qpois", "rpois",
"dt", "pt", "qt", "rt",
"dunif", "punif", "qunif", "runif",
"dweibull", "pweibull", "qweibull", "rweibull",
"dsignrank", "psignrank", "qsignrank", "rsignrank",
"pbirthday",
"ptukey",
"dwilcox",
"switch"
#ifdef JASP_DEBUG
,"Sys.sleep", ".crashPlease", "stringi::stri_enc_mark", "stringi::stri_enc_toutf8", "Encoding"
#endif
};
std::string R_FunctionWhiteList::returnOrderedWhiteList()
{
std::stringstream out;
for(auto & s : functionWhiteList)
out << "\"" << s << "\"," << std::endl;
out << std::flush;
return out.str();
}
const std::string R_FunctionWhiteList::functionStartDelimit("(?:[;\\s\\(\"\\[\\+\\-\\=\\*\\%\\/\\{\\|&!]|^)"); //These should be all possible non-funtion-name-characters that could be right in front of any function-name in R.
const std::string R_FunctionWhiteList::functionNameStart("(?:\\.?[[:alpha:]])");
const std::string R_FunctionWhiteList::functionNameBody("(?:\\w|\\.|::)+");
const std::regex R_FunctionWhiteList::functionNameMatcher(functionStartDelimit + "(" + functionNameStart + functionNameBody + ")(?=[\\t \\r]*\\()");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctions(std::string const & script)
{
std::set<std::string> blackListedFunctionsFound;
auto foundFunctionsBegin = std::sregex_iterator(script.begin(), script.end(), functionNameMatcher);
auto foundFunctionsEnd = std::sregex_iterator();
for(auto foundFunctionIter = foundFunctionsBegin; foundFunctionIter != foundFunctionsEnd; foundFunctionIter++ )
{
std::string foundFunction((*foundFunctionIter)[1].str());
bool whiteListed = functionWhiteList.count(foundFunction) > 0;
if(!whiteListed && blackListedFunctionsFound.count(foundFunction) == 0)
blackListedFunctionsFound.insert(foundFunction);
}
return blackListedFunctionsFound;
}
const std::string R_FunctionWhiteList::operatorsR("`(?:\\+|-|\\*|/|%(?:/|\\*|in)?%|\\^|<=?|>=?|==?|!=?|<?<-|->>?|\\|\\|?|&&?|:|\\$)`");
const std::regex R_FunctionWhiteList::assignmentWhiteListedRightMatcher( "(" + functionNameStart + functionNameBody + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentWhiteListedLeftMatcher( "(?:->>?)\\s*(" + functionNameStart + functionNameBody + ")");
const std::regex R_FunctionWhiteList::assignmentOperatorRightMatcher( "(" + operatorsR + ")\\s*(?:<?<-|=)");
const std::regex R_FunctionWhiteList::assignmentOperatorLeftMatcher( "(?:->>?)\\s*(" + operatorsR + ")");
std::set<std::string> R_FunctionWhiteList::findIllegalFunctionsAliases(std::string const & script)
{
//Log::log() << "findIllegalFunctionsAliases with " << script << std::endl;
std::set<std::string> illegalAliasesFound;
auto aliasSearcher = [&illegalAliasesFound, &script](std::regex aliasAssignmentMatcher, bool (*lambdaMatchChecker)(std::string) )
{
auto foundAliasesBegin = std::sregex_iterator(script.begin(), script.end(), aliasAssignmentMatcher);
auto foundAliasesEnd = std::sregex_iterator();
for(auto foundAliasesIter = foundAliasesBegin; foundAliasesIter != foundAliasesEnd; foundAliasesIter++ )
{
std::string foundAlias((*foundAliasesIter)[1].str());
bool allowed = (*lambdaMatchChecker)(foundAlias);
//Log::log() << "I found alias assignment: " << foundAlias << " which is " << (allowed ? "allowed" : "not allowed") << ".." << std::endl;
if(!allowed)
illegalAliasesFound.insert(foundAlias);
}
};
aliasSearcher(assignmentOperatorLeftMatcher, [](std::string alias) { return false; }); //operators are never allowed
aliasSearcher(assignmentOperatorRightMatcher, [](std::string alias) { return false; });
aliasSearcher(assignmentWhiteListedLeftMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; }); //only allowed when the token being assigned to is not in whitelist
aliasSearcher(assignmentWhiteListedRightMatcher, [](std::string alias) { return functionWhiteList.count(alias) == 0; });
//Log::log() << std::flush;
return illegalAliasesFound;
}
void R_FunctionWhiteList::scriptIsSafe(const std::string &script)
{
std::string commentFree = stringUtils::stripRComments(script);
static std::string errorMsg;
std::set<std::string> blackListedFunctions = findIllegalFunctions(commentFree);
if(blackListedFunctions.size() > 0)
{
bool moreThanOne = blackListedFunctions.size() > 1;
std::stringstream ssm;
ssm << "Non-whitelisted function" << (moreThanOne ? "s" : "") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & black : blackListedFunctions)
ssm << black << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
std::set<std::string> illegalAliasesFound = findIllegalFunctionsAliases(commentFree);
if(illegalAliasesFound.size() > 0)
{
bool moreThanOne = illegalAliasesFound.size() > 1;
std::stringstream ssm;
ssm << "Illegal assignment to " << (moreThanOne ? "operators or whitelisted functions" : "an operator or whitelisted function") << " used:" << (moreThanOne ? "\n" : " ");
for(auto & alias : illegalAliasesFound)
ssm << alias << "\n";
errorMsg = ssm.str();
throw filterException(errorMsg);
}
}
<|endoftext|>
|
<commit_before>#include "IPAddress.h"
#include "InternetAddress.h"
#include "Util.h"
#include <iostream>
#include <fstream>
#include <iomanip>
void displayHelp ();
int main () {
// Indicates whether the program should exit
bool exit = false;
std::string option;
std::cout << "IP Calculator v1.0" << std::endl << std::endl;
std::cout << "Type \"help\" to display all available options." << std::endl;
while (!exit) {
std::cout << std::endl << ">> ";
std::cin >> option; std::cin.ignore();
if (option == "help") {
displayHelp();
} else if (option == "identify") {
IPAddress ip, mask;
std::cout << "Enter IP address: "; std::cin >> ip;
std::cout << "Enter subnet mask: "; std::cin >> mask;
switch (Util::identifyAddress(InternetAddress(ip, mask))) {
case 0: std::cout << "This is a network address." << std::endl; break;
case 1: std::cout << "This is a broadcast address." << std::endl; break;
case 2: std::cout << "This is a host address." << std::endl; break;
}
} else if (option == "subnet") {
int input_mode, output_mode;
std::cout << "Choose input mode (0 - keyboard; 1 - file): ";
std::cin >> input_mode; std::cin.ignore();
std::cout << "Choose output mode (0 - console; 1 - file): ";
std::cin >> output_mode; std::cin.ignore();
if (input_mode) { // File input
std::string input_filename;
std::cout << "Enter input filename: ";
std::cin >> input_filename; std::cin.ignore();
if (output_mode) { // File input + File output
std::string output_filename;
std::cout << "Enter output filename: ";
std::cin >> output_filename; std::cin.ignore();
Util::subnetNetwork(input_filename, output_filename);
} else { // File input + Console output
std::vector<InternetAddress> subnetworks;
subnetworks = Util::subnetNetwork(input_filename);
if (subnetworks.size() == 0) {
std::cout << "Invalid input!" << std::endl;
std::cout << "Original network cannot be split into this many subnetworks." << std::endl;
} else {
std::cout << std::endl;
for (unsigned int i = 0; i < subnetworks.size(); i++) {
std::cout << "Subnetwork #" << (i + 1) << std::endl;
std::cout << subnetworks[i] << std::endl;
}
}
}
} else { // Keyboard input
IPAddress ip, mask;
int nr_subnetworks;
std::vector<int> nr_hosts;
std::cout << std::endl;
std::cout << "Enter original network details:" << std::endl;
std::cout << " - IP address: "; std::cin >> ip;
std::cout << " - Subnet mask: "; std::cin >> mask;
std::cout << std::endl;
std::cout << "Enter number of subnetworks: "; std::cin >> nr_subnetworks;
nr_hosts.resize(nr_subnetworks);
std::cout << std::endl;
std::cout << "Enter number of host IPs required by each subnetwork:" << std::endl;
for (int i = 0; i < nr_subnetworks; i++) {
std::cout << " - subnetwork " << (i + 1) << ": ";
std::cin >> nr_hosts[i];
}
if (output_mode) { // Keyboard input + File output
std::string output_filename;
std::cout << "Enter output filename: ";
std::cin >> output_filename; std::cin.ignore();
Util::subnetNetwork(InternetAddress(ip, mask), nr_hosts, output_filename);
} else { // Keyboard input + Console output
std::vector<InternetAddress> subnetworks;
subnetworks = Util::subnetNetwork(InternetAddress(ip, mask), nr_hosts);
if (subnetworks.size() == 0) {
std::cout << "Invalid input!" << std::endl;
std::cout << "Original network cannot be split into this many subnetworks." << std::endl;
} else {
std::cout << std::endl;
std::cout << "Original network" << std::endl;
std::cout << InternetAddress(ip, mask) << std::endl;
std::cout << "--------------------" << std::endl << std::endl;
for (unsigned int i = 0; i < subnetworks.size(); i++) {
std::cout << "Subnetwork #" << (i + 1) << std::endl;
std::cout << subnetworks[i] << std::endl;
}
}
}
}
} else if (option == "exit") {
std::cout << "Exiting..." << std::endl;
exit = true;
} else {
std::cout << "Invalid option. Try again..." << std::endl;
}
}
return 0;
}
void displayHelp () {
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "help";
std::cout << "Display all available options." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "identify";
std::cout << "Identify the type of an IP address" << std::endl;
std::cout << "\t" << std::setw(16) << " ";
std::cout << "(network / broadcast / host)." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "subnet";
std::cout << "Subnet a larger network into multiple" << std::endl;
std::cout << "\t" << std::setw(16) << " ";
std::cout << "smaller ones." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "exit";
std::cout << "Exit the program." << std::endl;
}<commit_msg>Include license option<commit_after>#include "IPAddress.h"
#include "InternetAddress.h"
#include "Util.h"
#include <iostream>
#include <fstream>
#include <iomanip>
void displayHelp ();
void displayLicense ();
int main () {
// Indicates whether the program should exit
bool exit = false;
std::string option;
std::cout << "IP Calculator v1.0" << std::endl << std::endl;
std::cout << "Type \"help\" to display all available options." << std::endl;
while (!exit) {
std::cout << std::endl << ">> ";
std::cin >> option; std::cin.ignore();
if (option == "help") {
displayHelp();
} else if (option == "identify") {
IPAddress ip, mask;
std::cout << "Enter IP address: "; std::cin >> ip;
std::cout << "Enter subnet mask: "; std::cin >> mask;
switch (Util::identifyAddress(InternetAddress(ip, mask))) {
case 0: std::cout << "This is a network address." << std::endl; break;
case 1: std::cout << "This is a broadcast address." << std::endl; break;
case 2: std::cout << "This is a host address." << std::endl; break;
}
} else if (option == "subnet") {
int input_mode, output_mode;
std::cout << "Choose input mode (0 - keyboard; 1 - file): ";
std::cin >> input_mode; std::cin.ignore();
std::cout << "Choose output mode (0 - console; 1 - file): ";
std::cin >> output_mode; std::cin.ignore();
if (input_mode) { // File input
std::string input_filename;
std::cout << "Enter input filename: ";
std::cin >> input_filename; std::cin.ignore();
if (output_mode) { // File input + File output
std::string output_filename;
std::cout << "Enter output filename: ";
std::cin >> output_filename; std::cin.ignore();
Util::subnetNetwork(input_filename, output_filename);
} else { // File input + Console output
std::vector<InternetAddress> subnetworks;
subnetworks = Util::subnetNetwork(input_filename);
if (subnetworks.size() == 0) {
std::cout << "Invalid input!" << std::endl;
std::cout << "Original network cannot be split into this many subnetworks." << std::endl;
} else {
std::cout << std::endl;
for (unsigned int i = 0; i < subnetworks.size(); i++) {
std::cout << "Subnetwork #" << (i + 1) << std::endl;
std::cout << subnetworks[i] << std::endl;
}
}
}
} else { // Keyboard input
IPAddress ip, mask;
int nr_subnetworks;
std::vector<int> nr_hosts;
std::cout << std::endl;
std::cout << "Enter original network details:" << std::endl;
std::cout << " - IP address: "; std::cin >> ip;
std::cout << " - Subnet mask: "; std::cin >> mask;
std::cout << std::endl;
std::cout << "Enter number of subnetworks: "; std::cin >> nr_subnetworks;
nr_hosts.resize(nr_subnetworks);
std::cout << std::endl;
std::cout << "Enter number of host IPs required by each subnetwork:" << std::endl;
for (int i = 0; i < nr_subnetworks; i++) {
std::cout << " - subnetwork " << (i + 1) << ": ";
std::cin >> nr_hosts[i];
}
if (output_mode) { // Keyboard input + File output
std::string output_filename;
std::cout << "Enter output filename: ";
std::cin >> output_filename; std::cin.ignore();
Util::subnetNetwork(InternetAddress(ip, mask), nr_hosts, output_filename);
} else { // Keyboard input + Console output
std::vector<InternetAddress> subnetworks;
subnetworks = Util::subnetNetwork(InternetAddress(ip, mask), nr_hosts);
if (subnetworks.size() == 0) {
std::cout << "Invalid input!" << std::endl;
std::cout << "Original network cannot be split into this many subnetworks." << std::endl;
} else {
std::cout << std::endl;
std::cout << "Original network" << std::endl;
std::cout << InternetAddress(ip, mask) << std::endl;
std::cout << "--------------------" << std::endl << std::endl;
for (unsigned int i = 0; i < subnetworks.size(); i++) {
std::cout << "Subnetwork #" << (i + 1) << std::endl;
std::cout << subnetworks[i] << std::endl;
}
}
}
}
} else if (option == "license") {
displayLicense();
} else if (option == "exit") {
std::cout << "Exiting..." << std::endl;
exit = true;
} else {
std::cout << "Invalid option. Try again..." << std::endl;
}
}
return 0;
}
void displayHelp () {
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "help";
std::cout << "Display all available options." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "identify";
std::cout << "Identify the type of an IP address" << std::endl;
std::cout << "\t" << std::setw(16) << " ";
std::cout << "(network / broadcast / host)." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "license";
std::cout << "Display license information." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "subnet";
std::cout << "Subnet a larger network into multiple" << std::endl;
std::cout << "\t" << std::setw(16) << " ";
std::cout << "smaller ones." << std::endl;
std::cout << std::endl;
std::cout << "\t" << std::setw(16) << std::left << "exit";
std::cout << "Exit the program." << std::endl;
}
void displayLicense () {
std::cout << "The MIT License (MIT)" << std::endl << std::endl;
std::cout << "Copyright (c) 2015 PODARIU Ovidiu" << std::endl << std::endl;
std::cout << "Permission is hereby granted, free of charge, to any person " << std::endl
<< "obtaining a copy of this software and associated documentation " << std::endl
<< "files (the \"Software\"), to deal in the Software without " << std::endl
<< "restriction, including without limitation the rights to use, " << std::endl
<< "copy, modify, merge, publish, distribute, sublicense, and/or " << std::endl
<< "sell copies of the Software, and to permit persons to whom " << std::endl
<< "the Software is furnished to do so, subject to the following " << std::endl
<< "conditions:" << std::endl << std::endl;
std::cout << "The above copyright notice and this permission notice shall " << std::endl
<< "be included in all copies or substantial portions of the " << std::endl
<< "Software." << std::endl << std::endl;
std::cout << "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY " << std::endl
<< "KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE " << std::endl
<< "WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR " << std::endl
<< "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS " << std::endl
<< "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR " << std::endl
<< "OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR " << std::endl
<< "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE " << std::endl
<< "SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." << std::endl;
}<|endoftext|>
|
<commit_before>// Test for cross-vendor C++ ABI's __cxa_demangle function.
#include <cxxabi.h>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <typeinfo>
int main()
{
int status = 0;
char *name = abi::__cxa_demangle(
typeid(10).name(), nullptr, nullptr, &status);
if (status != 0)
throw std::runtime_error("Demangle failed!");
int result = std::strcmp(name, "int");
std::free(name);
return result;
}
<commit_msg>Cosmetic.<commit_after>// Test for cross-vendor C++ ABI's __cxa_demangle function.
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <typeinfo>
#include <cxxabi.h>
int main()
{
int status = 0;
char *name =
abi::__cxa_demangle(typeid(10).name(), nullptr, nullptr, &status);
if (status != 0)
throw std::runtime_error("Demangle failed!");
int result = std::strcmp(name, "int");
std::free(name);
return result;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/offline/offline_load_page.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/test_tab_contents.h"
#include "content/test/test_browser_thread.h"
using content::BrowserThread;
static const char* kURL1 = "http://www.google.com/";
static const char* kURL2 = "http://www.gmail.com/";
namespace chromeos {
class OfflineLoadPageTest;
namespace {
// An OfflineLoadPage class that does not create windows.
class TestOfflineLoadPage : public chromeos::OfflineLoadPage {
public:
TestOfflineLoadPage(TabContents* tab_contents,
const GURL& url,
OfflineLoadPageTest* test_page)
: chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()),
test_page_(test_page) {
interstitial_page_->DontCreateViewForTesting();
}
// chromeos::OfflineLoadPage override.
virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE;
private:
OfflineLoadPageTest* test_page_;
DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage);
};
} // namespace
class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness {
public:
// The decision the user made.
enum UserResponse {
PENDING,
OK,
CANCEL
};
OfflineLoadPageTest()
: ui_thread_(BrowserThread::UI, MessageLoop::current()),
io_thread_(BrowserThread::IO, MessageLoop::current()) {
}
virtual void SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
user_response_ = PENDING;
}
void OnBlockingPageComplete(bool proceed) {
if (proceed)
user_response_ = OK;
else
user_response_ = CANCEL;
}
void Navigate(const char* url, int page_id) {
contents()->TestDidNavigate(
contents()->GetRenderViewHost(), page_id, GURL(url),
content::PAGE_TRANSITION_TYPED);
}
void ShowInterstitial(const char* url) {
new TestOfflineLoadPage(contents(), GURL(url), this);
}
// Returns the OfflineLoadPage currently showing or NULL if none is
// showing.
InterstitialPage* GetOfflineLoadPage() {
return InterstitialPage::GetInterstitialPage(contents());
}
UserResponse user_response() const { return user_response_; }
private:
UserResponse user_response_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread io_thread_;
// Initializes / shuts down a stub CrosLibrary.
chromeos::ScopedStubCrosEnabler stub_cros_enabler_;
DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest);
};
void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) {
test_page_->OnBlockingPageComplete(proceed);
}
TEST_F(OfflineLoadPageTest, OfflinePageProceed) {
// Start a load.
Navigate(kURL1, 1);
// Load next page.
controller().LoadURL(GURL(kURL2), content::Referrer(),
content::PAGE_TRANSITION_TYPED, std::string());
// Simulate the load causing an offline browsing interstitial page
// to be shown.
ShowInterstitial(kURL2);
InterstitialPage* interstitial = GetOfflineLoadPage();
ASSERT_TRUE(interstitial);
MessageLoop::current()->RunAllPending();
// Simulate the user clicking "proceed".
interstitial->Proceed();
MessageLoop::current()->RunAllPending();
EXPECT_EQ(OK, user_response());
// The URL remains to be URL2.
EXPECT_EQ(kURL2, contents()->GetURL().spec());
// Commit navigation and the interstitial page is gone.
Navigate(kURL2, 2);
EXPECT_FALSE(GetOfflineLoadPage());
}
// Tests showing an offline page and not proceeding.
TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) {
// Start a load.
Navigate(kURL1, 1);
controller().LoadURL(GURL(kURL2), content::Referrer(),
content::PAGE_TRANSITION_TYPED, std::string());
// Simulate the load causing an offline interstitial page to be shown.
ShowInterstitial(kURL2);
InterstitialPage* interstitial = GetOfflineLoadPage();
ASSERT_TRUE(interstitial);
MessageLoop::current()->RunAllPending();
// Simulate the user clicking "don't proceed".
interstitial->DontProceed();
// The interstitial should be gone.
EXPECT_EQ(CANCEL, user_response());
EXPECT_FALSE(GetOfflineLoadPage());
// We did not proceed, the pending entry should be gone.
EXPECT_FALSE(controller().GetPendingEntry());
// the URL is set back to kURL1.
EXPECT_EQ(kURL1, contents()->GetURL().spec());
}
} // namespace chromeos
<commit_msg>fix cros again<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/offline/offline_load_page.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/test_tab_contents.h"
#include "content/test/test_browser_thread.h"
using content::BrowserThread;
static const char* kURL1 = "http://www.google.com/";
static const char* kURL2 = "http://www.gmail.com/";
namespace chromeos {
class OfflineLoadPageTest;
// An OfflineLoadPage class that does not create windows.
class TestOfflineLoadPage : public chromeos::OfflineLoadPage {
public:
TestOfflineLoadPage(TabContents* tab_contents,
const GURL& url,
OfflineLoadPageTest* test_page)
: chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()),
test_page_(test_page) {
interstitial_page_->DontCreateViewForTesting();
}
// chromeos::OfflineLoadPage override.
virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE;
private:
OfflineLoadPageTest* test_page_;
DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage);
};
class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness {
public:
// The decision the user made.
enum UserResponse {
PENDING,
OK,
CANCEL
};
OfflineLoadPageTest()
: ui_thread_(BrowserThread::UI, MessageLoop::current()),
io_thread_(BrowserThread::IO, MessageLoop::current()) {
}
virtual void SetUp() {
ChromeRenderViewHostTestHarness::SetUp();
user_response_ = PENDING;
}
void OnBlockingPageComplete(bool proceed) {
if (proceed)
user_response_ = OK;
else
user_response_ = CANCEL;
}
void Navigate(const char* url, int page_id) {
contents()->TestDidNavigate(
contents()->GetRenderViewHost(), page_id, GURL(url),
content::PAGE_TRANSITION_TYPED);
}
void ShowInterstitial(const char* url) {
new TestOfflineLoadPage(contents(), GURL(url), this);
}
// Returns the OfflineLoadPage currently showing or NULL if none is
// showing.
InterstitialPage* GetOfflineLoadPage() {
return InterstitialPage::GetInterstitialPage(contents());
}
UserResponse user_response() const { return user_response_; }
private:
UserResponse user_response_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread io_thread_;
// Initializes / shuts down a stub CrosLibrary.
chromeos::ScopedStubCrosEnabler stub_cros_enabler_;
DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest);
};
void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) {
test_page_->OnBlockingPageComplete(proceed);
}
TEST_F(OfflineLoadPageTest, OfflinePageProceed) {
// Start a load.
Navigate(kURL1, 1);
// Load next page.
controller().LoadURL(GURL(kURL2), content::Referrer(),
content::PAGE_TRANSITION_TYPED, std::string());
// Simulate the load causing an offline browsing interstitial page
// to be shown.
ShowInterstitial(kURL2);
InterstitialPage* interstitial = GetOfflineLoadPage();
ASSERT_TRUE(interstitial);
MessageLoop::current()->RunAllPending();
// Simulate the user clicking "proceed".
interstitial->Proceed();
MessageLoop::current()->RunAllPending();
EXPECT_EQ(OK, user_response());
// The URL remains to be URL2.
EXPECT_EQ(kURL2, contents()->GetURL().spec());
// Commit navigation and the interstitial page is gone.
Navigate(kURL2, 2);
EXPECT_FALSE(GetOfflineLoadPage());
}
// Tests showing an offline page and not proceeding.
TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) {
// Start a load.
Navigate(kURL1, 1);
controller().LoadURL(GURL(kURL2), content::Referrer(),
content::PAGE_TRANSITION_TYPED, std::string());
// Simulate the load causing an offline interstitial page to be shown.
ShowInterstitial(kURL2);
InterstitialPage* interstitial = GetOfflineLoadPage();
ASSERT_TRUE(interstitial);
MessageLoop::current()->RunAllPending();
// Simulate the user clicking "don't proceed".
interstitial->DontProceed();
// The interstitial should be gone.
EXPECT_EQ(CANCEL, user_response());
EXPECT_FALSE(GetOfflineLoadPage());
// We did not proceed, the pending entry should be gone.
EXPECT_FALSE(controller().GetPendingEntry());
// the URL is set back to kURL1.
EXPECT_EQ(kURL1, contents()->GetURL().spec());
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/time/Time.h>
#include <stdio.h>
#include <stingraykit/exception.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/string/StringUtils.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/log/Logger.h>
namespace stingray
{
static const int SecondsPerMinute = 60;
static const int MillisecondsPerMinute = SecondsPerMinute * 1000;
static const int MinutesPerHour = 60;
static const int SecondsPerHour = MinutesPerHour * SecondsPerMinute;
static const int SecondsPerDay = 24 * SecondsPerHour;
static const int DaysSinceMjd = 40587;
void TimeDuration::Serialize(ObjectOStream & ar) const
{ ar.Serialize("us", _microseconds); }
void TimeDuration::Deserialize(ObjectIStream & ar)
{
optional<s64> microseconds;
ar.Deserialize("us", microseconds);
if (microseconds)
{
_microseconds = *microseconds;
return;
}
s64 milliseconds = 0;
ar.Deserialize("ms", milliseconds);
_microseconds = milliseconds * 1000;
}
std::string TimeDuration::ToString(const std::string& format) const
{
std::string result = format.empty() ? "hh:mm:ss.lll" : format;
if (GetMilliseconds() < 0)
result.insert(0, "-");
std::string hours_placeholder = "hh";
bool has_hours = std::search(format.begin(), format.end(), hours_placeholder.begin(), hours_placeholder.end()) != format.end();
s64 abs_ms = Absolute().GetMilliseconds();
s64 hours = has_hours ? abs_ms / Hour().GetMilliseconds() : 0;
s64 minutes = (abs_ms - hours * Hour().GetMilliseconds()) / Minute().GetMilliseconds();
s64 seconds = abs_ms % Minute().GetMilliseconds() / Second().GetMilliseconds();
s64 milliseconds = abs_ms % Second().GetMilliseconds();
if (has_hours)
ReplaceAll(result, "hh", StringFormat("%1$2%", hours));
else
ReplaceAll(result, "hh", "");
ReplaceAll(result, "mm", StringFormat("%1$2%", minutes));
ReplaceAll(result, "ss", StringFormat("%1$2%", seconds));
ReplaceAll(result, "lll", StringFormat("%1$3%", milliseconds));
return result;
}
TimeDuration TimeDuration::FromString(const std::string& s)
{
int n;
char c = 0;
int components = sscanf(s.c_str(), "%d%c", &n, &c);
if (components < 1)
STINGRAYKIT_THROW("Invalid time duration format");
switch (c)
{
case 'H':
case 'h':
return FromHours(n);
case 'M':
case 'm':
return FromMinutes(n);
case 'S':
case 's':
return FromSeconds(n);
case 0:
return TimeDuration(n);
};
STINGRAYKIT_THROW("Could not parse TimeDuration!");
}
Time::Time()
: _milliseconds(0)
{ }
Time::Time(s64 milliseconds)
: _milliseconds(milliseconds)
{ }
Time Time::Now() { return Time(TimeEngine::GetMillisecondsSinceEpoch()); }
BrokenDownTime Time::BreakDown(TimeKind kind) const
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return TimeEngine::BrokenDownFromMilliseconds(_milliseconds + offset);
}
Time Time::FromBrokenDownTime(const BrokenDownTime& bdt, TimeKind kind)
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return Time(TimeEngine::MillisecondsFromBrokenDown(bdt) - offset);
}
std::string Time::ToString(const std::string& format, TimeKind kind) const
{ return BreakDown(kind).ToString(format); }
Time Time::FromString(const std::string& s, TimeKind kind)
{
if (s == "now")
return Time::Now();
if (s.size() > 4 && s.substr(0, 4) == "now+")
return Time::Now() + TimeDuration::FromString(s.substr(4));
s16 year, month, day;
s16 hour, minute, second;
char utcSign;
s16 utcHour, utcMinute;
bool haveDate = false;
bool haveTime = false;
bool haveSeconds = false;
bool haveUtcSign = false;
bool haveUtcHours = false;
bool haveUtcMinutes = false;
int components = sscanf(s.c_str(), "%hd.%hd.%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd/%hd/%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd:%hd:%hd", &hour, &minute, &second);
if (components >= 2)
{
haveTime = true;
if (components >= 3)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd-%hd-%hdT%hd:%hd:%hd%c%hd:%hd", &year, &month, &day, &hour, &minute, &second, &utcSign, &utcHour, &utcMinute);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
if (components >= 7)
haveUtcSign = true;
if (components >= 8)
haveUtcHours = true;
if (components >= 9)
haveUtcMinutes = true;
}
else
STINGRAYKIT_THROW("Unknown time format!");
}
}
}
STINGRAYKIT_CHECK((haveDate || haveTime), "Could not parse Time!");
STINGRAYKIT_CHECK(!(!haveTime && haveSeconds), "Have seconds without hours and minutes!");
STINGRAYKIT_CHECK(!haveUtcSign || ((utcSign == 'Z' && !haveUtcHours && !haveUtcMinutes) || ((utcSign == '+' || utcSign == '-') && haveUtcHours && !(!haveUtcHours && haveUtcMinutes))), "Malformed UTC suffix");
if (haveUtcSign)
Logger::Debug() << "Time::FromString: time kind parameter will be ignored because time string have UTC sign";
BrokenDownTime bdt;
if (haveDate)
{
bdt.MonthDay = day;
bdt.Month = month;
bdt.Year = (year > 100 ? year : (year > 30 ? 1900 + year : 2000 + year));
}
else
{
bdt = Time::Now().BreakDown();
bdt.Seconds = 0;
bdt.Milliseconds = 0;
}
if (haveTime)
{
bdt.Hours = hour;
bdt.Minutes = minute;
}
if (haveSeconds)
bdt.Seconds = second;
if (haveUtcSign)
{
kind = TimeKind::Utc;
if ((utcSign == '+') || (utcSign == '-'))
{
s16 minutesFromUtc = (haveUtcHours ? (utcHour * MinutesPerHour) : 0) + (haveUtcMinutes ? utcMinute : 0);
if (utcSign == '-')
bdt.Minutes += minutesFromUtc;
else
bdt.Minutes -= minutesFromUtc;
}
else if (utcSign != 'Z')
STINGRAYKIT_THROW("Unknown UTC sign!");
}
return FromBrokenDownTime(bdt, kind);
}
void Time::Serialize(ObjectOStream & ar) const { ar.Serialize("ms", _milliseconds); }
void Time::Deserialize(ObjectIStream & ar) { ar.Deserialize("ms", _milliseconds); }
TimeZone::TimeZone()
: _minutesFromUtc()
{ }
TimeZone::TimeZone(s16 minutes)
: _minutesFromUtc(minutes)
{ STINGRAYKIT_CHECK(_minutesFromUtc >= -12 * MinutesPerHour && _minutesFromUtc <= 14 * MinutesPerHour, IndexOutOfRangeException()); }
TimeZone TimeZone::Current()
{ return TimeZone(TimeEngine::GetMinutesFromUtc()); }
std::string TimeZone::ToString() const
{
const std::string sign = _minutesFromUtc > 0? "+" : _minutesFromUtc < 0? "-" : "";
return StringBuilder() % sign % (_minutesFromUtc / MinutesPerHour) % ":" % (_minutesFromUtc % MinutesPerHour);
}
TimeZone TimeZone::FromString(const std::string& str)
{
char sign;
int hours, minutes;
STINGRAYKIT_CHECK(sscanf(str.c_str(), "%c%d:%d", &sign, &hours, &minutes) == 3, FormatException());
const int value = hours * MinutesPerHour + minutes;
return TimeZone(sign == '+'? value : -value);
}
void TimeZone::Serialize(ObjectOStream & ar) const { ar.Serialize("offset", _minutesFromUtc); }
void TimeZone::Deserialize(ObjectIStream & ar) { ar.Deserialize("offset", _minutesFromUtc); }
const s64 SecondsBetweenNtpAndUnixEpochs = 2208988800ll;
u64 Time::ToNtpTimestamp() const
{
return GetMilliseconds() / 1000 + SecondsBetweenNtpAndUnixEpochs;
}
Time Time::FromNtpTimestamp(u64 timestamp)
{
return Time((timestamp - SecondsBetweenNtpAndUnixEpochs) * 1000);
}
static inline u8 bcdValue(u8 byte)
{ return ((byte >> 4) & 0x0f) * 10 + (byte & 0x0f); }
static inline u8 bcdEncode(u8 value)
{ return ((value / 10) << 4) + value % 10; }
Time Time::MJDtoEpoch(int mjd, u32 bcdTime)
{ return Time(s64(mjd - DaysSinceMjd) * SecondsPerDay * 1000) + BCDDurationToTimeDuration(bcdTime); }
TimeDuration Time::BCDDurationToTimeDuration(u32 bcdTime)
{
return TimeDuration(s64(1000) * (SecondsPerHour * bcdValue((bcdTime >> 16) & 0xff) +
SecondsPerMinute * bcdValue((bcdTime >> 8) & 0xff) +
bcdValue(bcdTime & 0xff)));
}
int Time::GetMJD() const
{
return DaysSinceMjd + _milliseconds / (1000 * SecondsPerDay);
}
u32 Time::GetBCDTime(TimeKind kind) const
{
BrokenDownTime bdt(this->BreakDown(kind));
return (bcdEncode(bdt.Hours) << 16) + (bcdEncode(bdt.Minutes) << 8) + bcdEncode(bdt.Seconds);
}
int Time::DaysTo(const Time& endTime)
{
return (Time::FromBrokenDownTime((*this).BreakDown().GetDayStart()).GetMilliseconds() - Time::FromBrokenDownTime(endTime.BreakDown().GetDayStart()).GetMilliseconds()) / 86400000; // 1000 * 60 * 60 * 24 = 86400000
}
}
<commit_msg>use STINGRAYKIT_CHECK_RANGE to ensure that time zone is in valid range<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/time/Time.h>
#include <stdio.h>
#include <stingraykit/exception.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/string/StringUtils.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/log/Logger.h>
namespace stingray
{
static const int SecondsPerMinute = 60;
static const int MillisecondsPerMinute = SecondsPerMinute * 1000;
static const int MinutesPerHour = 60;
static const int SecondsPerHour = MinutesPerHour * SecondsPerMinute;
static const int SecondsPerDay = 24 * SecondsPerHour;
static const int DaysSinceMjd = 40587;
void TimeDuration::Serialize(ObjectOStream & ar) const
{ ar.Serialize("us", _microseconds); }
void TimeDuration::Deserialize(ObjectIStream & ar)
{
optional<s64> microseconds;
ar.Deserialize("us", microseconds);
if (microseconds)
{
_microseconds = *microseconds;
return;
}
s64 milliseconds = 0;
ar.Deserialize("ms", milliseconds);
_microseconds = milliseconds * 1000;
}
std::string TimeDuration::ToString(const std::string& format) const
{
std::string result = format.empty() ? "hh:mm:ss.lll" : format;
if (GetMilliseconds() < 0)
result.insert(0, "-");
std::string hours_placeholder = "hh";
bool has_hours = std::search(format.begin(), format.end(), hours_placeholder.begin(), hours_placeholder.end()) != format.end();
s64 abs_ms = Absolute().GetMilliseconds();
s64 hours = has_hours ? abs_ms / Hour().GetMilliseconds() : 0;
s64 minutes = (abs_ms - hours * Hour().GetMilliseconds()) / Minute().GetMilliseconds();
s64 seconds = abs_ms % Minute().GetMilliseconds() / Second().GetMilliseconds();
s64 milliseconds = abs_ms % Second().GetMilliseconds();
if (has_hours)
ReplaceAll(result, "hh", StringFormat("%1$2%", hours));
else
ReplaceAll(result, "hh", "");
ReplaceAll(result, "mm", StringFormat("%1$2%", minutes));
ReplaceAll(result, "ss", StringFormat("%1$2%", seconds));
ReplaceAll(result, "lll", StringFormat("%1$3%", milliseconds));
return result;
}
TimeDuration TimeDuration::FromString(const std::string& s)
{
int n;
char c = 0;
int components = sscanf(s.c_str(), "%d%c", &n, &c);
if (components < 1)
STINGRAYKIT_THROW("Invalid time duration format");
switch (c)
{
case 'H':
case 'h':
return FromHours(n);
case 'M':
case 'm':
return FromMinutes(n);
case 'S':
case 's':
return FromSeconds(n);
case 0:
return TimeDuration(n);
};
STINGRAYKIT_THROW("Could not parse TimeDuration!");
}
Time::Time()
: _milliseconds(0)
{ }
Time::Time(s64 milliseconds)
: _milliseconds(milliseconds)
{ }
Time Time::Now() { return Time(TimeEngine::GetMillisecondsSinceEpoch()); }
BrokenDownTime Time::BreakDown(TimeKind kind) const
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return TimeEngine::BrokenDownFromMilliseconds(_milliseconds + offset);
}
Time Time::FromBrokenDownTime(const BrokenDownTime& bdt, TimeKind kind)
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return Time(TimeEngine::MillisecondsFromBrokenDown(bdt) - offset);
}
std::string Time::ToString(const std::string& format, TimeKind kind) const
{ return BreakDown(kind).ToString(format); }
Time Time::FromString(const std::string& s, TimeKind kind)
{
if (s == "now")
return Time::Now();
if (s.size() > 4 && s.substr(0, 4) == "now+")
return Time::Now() + TimeDuration::FromString(s.substr(4));
s16 year, month, day;
s16 hour, minute, second;
char utcSign;
s16 utcHour, utcMinute;
bool haveDate = false;
bool haveTime = false;
bool haveSeconds = false;
bool haveUtcSign = false;
bool haveUtcHours = false;
bool haveUtcMinutes = false;
int components = sscanf(s.c_str(), "%hd.%hd.%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd/%hd/%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd:%hd:%hd", &hour, &minute, &second);
if (components >= 2)
{
haveTime = true;
if (components >= 3)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd-%hd-%hdT%hd:%hd:%hd%c%hd:%hd", &year, &month, &day, &hour, &minute, &second, &utcSign, &utcHour, &utcMinute);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
if (components >= 7)
haveUtcSign = true;
if (components >= 8)
haveUtcHours = true;
if (components >= 9)
haveUtcMinutes = true;
}
else
STINGRAYKIT_THROW("Unknown time format!");
}
}
}
STINGRAYKIT_CHECK((haveDate || haveTime), "Could not parse Time!");
STINGRAYKIT_CHECK(!(!haveTime && haveSeconds), "Have seconds without hours and minutes!");
STINGRAYKIT_CHECK(!haveUtcSign || ((utcSign == 'Z' && !haveUtcHours && !haveUtcMinutes) || ((utcSign == '+' || utcSign == '-') && haveUtcHours && !(!haveUtcHours && haveUtcMinutes))), "Malformed UTC suffix");
if (haveUtcSign)
Logger::Debug() << "Time::FromString: time kind parameter will be ignored because time string have UTC sign";
BrokenDownTime bdt;
if (haveDate)
{
bdt.MonthDay = day;
bdt.Month = month;
bdt.Year = (year > 100 ? year : (year > 30 ? 1900 + year : 2000 + year));
}
else
{
bdt = Time::Now().BreakDown();
bdt.Seconds = 0;
bdt.Milliseconds = 0;
}
if (haveTime)
{
bdt.Hours = hour;
bdt.Minutes = minute;
}
if (haveSeconds)
bdt.Seconds = second;
if (haveUtcSign)
{
kind = TimeKind::Utc;
if ((utcSign == '+') || (utcSign == '-'))
{
s16 minutesFromUtc = (haveUtcHours ? (utcHour * MinutesPerHour) : 0) + (haveUtcMinutes ? utcMinute : 0);
if (utcSign == '-')
bdt.Minutes += minutesFromUtc;
else
bdt.Minutes -= minutesFromUtc;
}
else if (utcSign != 'Z')
STINGRAYKIT_THROW("Unknown UTC sign!");
}
return FromBrokenDownTime(bdt, kind);
}
void Time::Serialize(ObjectOStream & ar) const { ar.Serialize("ms", _milliseconds); }
void Time::Deserialize(ObjectIStream & ar) { ar.Deserialize("ms", _milliseconds); }
TimeZone::TimeZone()
: _minutesFromUtc()
{ }
TimeZone::TimeZone(s16 minutes)
: _minutesFromUtc(minutes)
{ STINGRAYKIT_CHECK_RANGE(_minutesFromUtc, -12 * MinutesPerHour, 14 * MinutesPerHour + 1); }
TimeZone TimeZone::Current()
{ return TimeZone(TimeEngine::GetMinutesFromUtc()); }
std::string TimeZone::ToString() const
{
const std::string sign = _minutesFromUtc > 0? "+" : _minutesFromUtc < 0? "-" : "";
return StringBuilder() % sign % (_minutesFromUtc / MinutesPerHour) % ":" % (_minutesFromUtc % MinutesPerHour);
}
TimeZone TimeZone::FromString(const std::string& str)
{
char sign;
int hours, minutes;
STINGRAYKIT_CHECK(sscanf(str.c_str(), "%c%d:%d", &sign, &hours, &minutes) == 3, FormatException());
const int value = hours * MinutesPerHour + minutes;
return TimeZone(sign == '+'? value : -value);
}
void TimeZone::Serialize(ObjectOStream & ar) const { ar.Serialize("offset", _minutesFromUtc); }
void TimeZone::Deserialize(ObjectIStream & ar) { ar.Deserialize("offset", _minutesFromUtc); }
const s64 SecondsBetweenNtpAndUnixEpochs = 2208988800ll;
u64 Time::ToNtpTimestamp() const
{
return GetMilliseconds() / 1000 + SecondsBetweenNtpAndUnixEpochs;
}
Time Time::FromNtpTimestamp(u64 timestamp)
{
return Time((timestamp - SecondsBetweenNtpAndUnixEpochs) * 1000);
}
static inline u8 bcdValue(u8 byte)
{ return ((byte >> 4) & 0x0f) * 10 + (byte & 0x0f); }
static inline u8 bcdEncode(u8 value)
{ return ((value / 10) << 4) + value % 10; }
Time Time::MJDtoEpoch(int mjd, u32 bcdTime)
{ return Time(s64(mjd - DaysSinceMjd) * SecondsPerDay * 1000) + BCDDurationToTimeDuration(bcdTime); }
TimeDuration Time::BCDDurationToTimeDuration(u32 bcdTime)
{
return TimeDuration(s64(1000) * (SecondsPerHour * bcdValue((bcdTime >> 16) & 0xff) +
SecondsPerMinute * bcdValue((bcdTime >> 8) & 0xff) +
bcdValue(bcdTime & 0xff)));
}
int Time::GetMJD() const
{
return DaysSinceMjd + _milliseconds / (1000 * SecondsPerDay);
}
u32 Time::GetBCDTime(TimeKind kind) const
{
BrokenDownTime bdt(this->BreakDown(kind));
return (bcdEncode(bdt.Hours) << 16) + (bcdEncode(bdt.Minutes) << 8) + bcdEncode(bdt.Seconds);
}
int Time::DaysTo(const Time& endTime)
{
return (Time::FromBrokenDownTime((*this).BreakDown().GetDayStart()).GetMilliseconds() - Time::FromBrokenDownTime(endTime.BreakDown().GetDayStart()).GetMilliseconds()) / 86400000; // 1000 * 60 * 60 * 24 = 86400000
}
}
<|endoftext|>
|
<commit_before>/*
* Using Sundaram' sieve, print the first 2,000,000 numbers
* darkturo 2014
*/
#include <iostream>
#include <fstream>
#include <bitset>
#include <ctime>
#include <limits>
#include <boost/spirit/include/karma.hpp>
#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC
#define MAX 32452843
#define MAXPRIMES 2000000
#define BUFFER_SIZE 8l * MAX
class SundaramSieve
{
std::bitset<MAX> N;
std::ofstream output;
int counter;
char * buffer;
char * p_input;
public:
SundaramSieve() :
output("primesEveryWhere.txt", std::ios::out | std::ios::trunc),
counter(0)
{
buffer = new char[BUFFER_SIZE];
p_input = buffer;
N.set();
}
~SundaramSieve()
{
if (p_input != buffer)
output.write(buffer, p_input - buffer); // flush
output.close();
}
void sieve()
{
print( 2 );
for (long i = 1; (2*i + 2*(i^2)) <= 2*sqrt(MAX); i++)
{
for (long j = i; (i + j + 2*i*j) <= (MAX - 2)/2; j++)
{
N.set((i + j + 2*i*j) - 1, false);
}
}
for (int i = 1; counter < MAXPRIMES; i++)
{
if (N[i-1])
{
print( 2*i + 1 );
}
}
}
int printedPrimes()
{
return counter;
}
private:
inline void print(int number)
{
doPrint(number);
counter ++;
}
inline void doPrint(int number)
{
boost::spirit::karma::generate(p_input, boost::spirit::int_, number);
*p_input++ = '\n';
}
};
int main(int argc, char ** argv)
{
clock_t t1, t2;
t1 = std::clock();
SundaramSieve siever;
siever.sieve();
t2 = std::clock();
// Summary
std::cout.precision(std::numeric_limits<double>::digits10);
std::cerr << "Used " << std::fixed << TIMEDIFF(t1, t2)
<< " msecs to calculate " << siever.printedPrimes()
<< " primes." << std::endl;
}
<commit_msg>Add some comments to make it clearer<commit_after>/*
* Using Sundaram' sieve, print the first 2,000,000 numbers
* darkturo 2014
*/
#include <iostream>
#include <fstream>
#include <bitset>
#include <ctime>
#include <limits>
#include <boost/spirit/include/karma.hpp>
#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC
#define MAX 32452843
#define MAXPRIMES 2000000
#define BUFFER_SIZE 8l * MAX
class SundaramSieve
{
std::bitset<MAX> N;
std::ofstream output;
int counter;
char * buffer;
char * p_input;
public:
SundaramSieve() :
output("primesEveryWhere.txt", std::ios::out | std::ios::trunc),
counter(0)
{
buffer = new char[BUFFER_SIZE];
p_input = buffer;
N.set();
}
~SundaramSieve()
{
if (p_input != buffer)
output.write(buffer, p_input - buffer); // flush
output.close();
}
void sieve()
{
// Given i,j ∈ ℕ, 1 ≤ i ≤ j
// Sieve all the x ∈ ℕ, x = i + j + 2ij ≤ MAX
for (long i = 1; (2*i + 2*(i^2)) <= 2*sqrt(MAX); i++)
{
for (long j = i; (i + j + 2*i*j) <= (MAX - 2)/2; j++)
{
N.set((i + j + 2*i*j) - 1, false);
}
}
// Generate the primes from the sieved list.
print( 2 );
for (int i = 1; counter < MAXPRIMES; i++)
{
if (N[i-1])
{
print( 2*i + 1 );
}
}
}
int printedPrimes()
{
return counter;
}
private:
inline void print(int number)
{
doPrint(number);
counter ++;
}
inline void doPrint(int number)
{
boost::spirit::karma::generate(p_input, boost::spirit::int_, number);
*p_input++ = '\n';
}
};
int main(int argc, char ** argv)
{
clock_t t1, t2;
t1 = std::clock();
SundaramSieve siever;
siever.sieve();
t2 = std::clock();
// Summary
std::cout.precision(std::numeric_limits<double>::digits10);
std::cerr << "Used " << std::fixed << TIMEDIFF(t1, t2)
<< " msecs to calculate " << siever.printedPrimes()
<< " primes." << std::endl;
}
<|endoftext|>
|
<commit_before>//===-- WatchpointLocation.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Breakpoint/WatchpointLocation.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Stream.h"
using namespace lldb;
using namespace lldb_private;
WatchpointLocation::WatchpointLocation (lldb::addr_t addr, size_t size, bool hardware) :
StoppointLocation (GetNextID(), addr, size, hardware),
m_enabled(0),
m_watch_read(0),
m_watch_write(0),
m_watch_was_read(0),
m_watch_was_written(0),
m_ignore_count(0),
m_callback(NULL),
m_callback_baton(NULL)
{
}
WatchpointLocation::~WatchpointLocation()
{
}
break_id_t
WatchpointLocation::GetNextID()
{
static break_id_t g_next_ID = 0;
return ++g_next_ID;
}
bool
WatchpointLocation::SetCallback (WatchpointHitCallback callback, void *callback_baton)
{
m_callback = callback;
m_callback_baton = callback_baton;
return true;
}
// RETURNS - true if we should stop at this breakpoint, false if we
// should continue.
bool
WatchpointLocation::BreakpointWasHit (StoppointCallbackContext *context)
{
m_hit_count++;
if (m_hit_count > m_ignore_count)
{
uint32_t access = 0;
if (m_watch_was_read)
access |= LLDB_WATCH_TYPE_READ;
if (m_watch_was_written)
access |= LLDB_WATCH_TYPE_WRITE;
return m_callback(m_callback_baton, context, GetID(), access);
}
return false;
}
void
WatchpointLocation::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
// FIXME: Add implmentation of GetDescription().
return;
}
void
WatchpointLocation::Dump(Stream *s) const
{
if (s == NULL)
return;
s->Printf("WatchpointLocation %u: tid = %4.4x addr = 0x%8.8llx size = %zu state = %s type = %s watchpoint (%s%s) hw_index = %i hit_count = %-4u ignore_count = %-4u callback = %8p baton = %8p",
GetID(),
(uint64_t)m_addr,
m_byte_size,
m_enabled ? "enabled " : "disabled",
IsHardware() ? "hardware" : "software",
m_watch_read ? "r" : "",
m_watch_write ? "w" : "",
GetHardwareIndex(),
GetHitCount(),
GetIgnoreCount(),
m_callback,
m_callback_baton);
}
bool
WatchpointLocation::IsEnabled() const
{
return m_enabled;
}
void
WatchpointLocation::SetEnabled(bool enabled)
{
if (!enabled)
SetHardwareIndex(LLDB_INVALID_INDEX32);
m_enabled = enabled;
}
void
WatchpointLocation::SetWatchpointType (uint32_t type)
{
m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0;
m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0;
}
bool
WatchpointLocation::WatchpointRead () const
{
return m_watch_read != 0;
}
bool
WatchpointLocation::WatchpointWrite () const
{
return m_watch_write != 0;
}
uint32_t
WatchpointLocation::GetIgnoreCount () const
{
return m_ignore_count;
}
void
WatchpointLocation::SetIgnoreCount (uint32_t n)
{
m_ignore_count = n;
}
<commit_msg>Add trivial implementation for GetDescription().<commit_after>//===-- WatchpointLocation.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Breakpoint/WatchpointLocation.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Stream.h"
using namespace lldb;
using namespace lldb_private;
WatchpointLocation::WatchpointLocation (lldb::addr_t addr, size_t size, bool hardware) :
StoppointLocation (GetNextID(), addr, size, hardware),
m_enabled(0),
m_watch_read(0),
m_watch_write(0),
m_watch_was_read(0),
m_watch_was_written(0),
m_ignore_count(0),
m_callback(NULL),
m_callback_baton(NULL)
{
}
WatchpointLocation::~WatchpointLocation()
{
}
break_id_t
WatchpointLocation::GetNextID()
{
static break_id_t g_next_ID = 0;
return ++g_next_ID;
}
bool
WatchpointLocation::SetCallback (WatchpointHitCallback callback, void *callback_baton)
{
m_callback = callback;
m_callback_baton = callback_baton;
return true;
}
// RETURNS - true if we should stop at this breakpoint, false if we
// should continue.
bool
WatchpointLocation::BreakpointWasHit (StoppointCallbackContext *context)
{
m_hit_count++;
if (m_hit_count > m_ignore_count)
{
uint32_t access = 0;
if (m_watch_was_read)
access |= LLDB_WATCH_TYPE_READ;
if (m_watch_was_written)
access |= LLDB_WATCH_TYPE_WRITE;
return m_callback(m_callback_baton, context, GetID(), access);
}
return false;
}
void
WatchpointLocation::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
s->Printf(" ");
Dump(s);
return;
}
void
WatchpointLocation::Dump(Stream *s) const
{
if (s == NULL)
return;
s->Printf("WatchpointLocation %u: tid = %4.4x addr = 0x%8.8llx size = %zu state = %s type = %s watchpoint (%s%s) hw_index = %i hit_count = %-4u ignore_count = %-4u callback = %8p baton = %8p",
GetID(),
(uint64_t)m_addr,
m_byte_size,
m_enabled ? "enabled " : "disabled",
IsHardware() ? "hardware" : "software",
m_watch_read ? "r" : "",
m_watch_write ? "w" : "",
GetHardwareIndex(),
GetHitCount(),
GetIgnoreCount(),
m_callback,
m_callback_baton);
}
bool
WatchpointLocation::IsEnabled() const
{
return m_enabled;
}
void
WatchpointLocation::SetEnabled(bool enabled)
{
if (!enabled)
SetHardwareIndex(LLDB_INVALID_INDEX32);
m_enabled = enabled;
}
void
WatchpointLocation::SetWatchpointType (uint32_t type)
{
m_watch_read = (type & LLDB_WATCH_TYPE_READ) != 0;
m_watch_write = (type & LLDB_WATCH_TYPE_WRITE) != 0;
}
bool
WatchpointLocation::WatchpointRead () const
{
return m_watch_read != 0;
}
bool
WatchpointLocation::WatchpointWrite () const
{
return m_watch_write != 0;
}
uint32_t
WatchpointLocation::GetIgnoreCount () const
{
return m_ignore_count;
}
void
WatchpointLocation::SetIgnoreCount (uint32_t n)
{
m_ignore_count = n;
}
<|endoftext|>
|
<commit_before>//===-- PythonDataObjects.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// In order to guarantee correct working with Python, Python.h *MUST* be
// the *FIRST* header file included here.
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#include <stdio.h>
#include "lldb/Core/Stream.h"
#include "lldb/Host/File.h"
#include "lldb/Interpreter/PythonDataObjects.h"
#include "lldb/Interpreter/ScriptInterpreter.h"
#include "lldb/Interpreter/ScriptInterpreterPython.h"
using namespace lldb_private;
using namespace lldb;
void
StructuredPythonObject::Dump(Stream &s) const
{
s << "Python Obj: 0x" << GetValue();
}
//----------------------------------------------------------------------
// PythonObject
//----------------------------------------------------------------------
void
PythonObject::Dump (Stream &strm) const
{
if (m_py_obj)
{
FILE *file = ::tmpfile();
if (file)
{
::PyObject_Print (m_py_obj, file, 0);
const long length = ftell (file);
if (length)
{
::rewind(file);
std::vector<char> file_contents (length,'\0');
const size_t length_read = ::fread (file_contents.data(), 1, file_contents.size(), file);
if (length_read > 0)
strm.Write (file_contents.data(), length_read);
}
::fclose (file);
}
}
else
strm.PutCString ("NULL");
}
PyObjectType
PythonObject::GetObjectType() const
{
if (IsNULLOrNone())
return PyObjectType::None;
if (PyList_Check(m_py_obj))
return PyObjectType::List;
if (PyDict_Check(m_py_obj))
return PyObjectType::Dictionary;
if (PyString_Check(m_py_obj))
return PyObjectType::String;
if (PyInt_Check(m_py_obj) || PyLong_Check(m_py_obj))
return PyObjectType::Integer;
return PyObjectType::Unknown;
}
PythonString
PythonObject::Repr ()
{
if (!m_py_obj)
return PythonString ();
PyObject *repr = PyObject_Repr(m_py_obj);
if (!repr)
return PythonString ();
return PythonString(repr);
}
PythonString
PythonObject::Str ()
{
if (!m_py_obj)
return PythonString ();
PyObject *str = PyObject_Str(m_py_obj);
if (!str)
return PythonString ();
return PythonString(str);
}
bool
PythonObject::IsNULLOrNone () const
{
return ((m_py_obj == nullptr) || (m_py_obj == Py_None));
}
StructuredData::ObjectSP
PythonObject::CreateStructuredObject() const
{
switch (GetObjectType())
{
case PyObjectType::Dictionary:
return PythonDictionary(m_py_obj).CreateStructuredDictionary();
case PyObjectType::Integer:
return PythonInteger(m_py_obj).CreateStructuredInteger();
case PyObjectType::List:
return PythonList(m_py_obj).CreateStructuredArray();
case PyObjectType::String:
return PythonString(m_py_obj).CreateStructuredString();
case PyObjectType::None:
return StructuredData::ObjectSP();
default:
return StructuredData::ObjectSP(new StructuredPythonObject(m_py_obj));
}
}
//----------------------------------------------------------------------
// PythonString
//----------------------------------------------------------------------
PythonString::PythonString (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a string
}
PythonString::PythonString (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a string
}
PythonString::PythonString (llvm::StringRef string) :
PythonObject(PyString_FromStringAndSize(string.data(), string.size()))
{
}
PythonString::PythonString(const char *string) :
PythonObject(PyString_FromString(string))
{
}
PythonString::PythonString () :
PythonObject()
{
}
PythonString::~PythonString ()
{
}
bool
PythonString::Reset (PyObject *py_obj)
{
if (py_obj && PyString_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
llvm::StringRef
PythonString::GetString() const
{
if (m_py_obj)
return llvm::StringRef(PyString_AsString(m_py_obj), GetSize());
return llvm::StringRef();
}
size_t
PythonString::GetSize() const
{
if (m_py_obj)
return PyString_Size(m_py_obj);
return 0;
}
void
PythonString::SetString (llvm::StringRef string)
{
PythonObject::Reset(PyString_FromStringAndSize(string.data(), string.size()));
}
StructuredData::StringSP
PythonString::CreateStructuredString() const
{
StructuredData::StringSP result(new StructuredData::String);
result->SetValue(GetString());
return result;
}
//----------------------------------------------------------------------
// PythonInteger
//----------------------------------------------------------------------
PythonInteger::PythonInteger (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a integer type
}
PythonInteger::PythonInteger (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a integer type
}
PythonInteger::PythonInteger (int64_t value) :
PythonObject()
{
SetInteger (value);
}
PythonInteger::~PythonInteger ()
{
}
bool
PythonInteger::Reset (PyObject *py_obj)
{
if (py_obj)
{
if (PyInt_Check (py_obj) || PyLong_Check(py_obj))
return PythonObject::Reset(py_obj);
}
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
int64_t
PythonInteger::GetInteger() const
{
if (m_py_obj)
{
if (PyInt_Check(m_py_obj))
return PyInt_AsLong(m_py_obj);
else if (PyLong_Check(m_py_obj))
return PyLong_AsLongLong(m_py_obj);
}
return UINT64_MAX;
}
void
PythonInteger::SetInteger (int64_t value)
{
PythonObject::Reset(PyLong_FromLongLong(value));
}
StructuredData::IntegerSP
PythonInteger::CreateStructuredInteger() const
{
StructuredData::IntegerSP result(new StructuredData::Integer);
result->SetValue(GetInteger());
return result;
}
//----------------------------------------------------------------------
// PythonList
//----------------------------------------------------------------------
PythonList::PythonList (bool create_empty) :
PythonObject(create_empty ? PyList_New(0) : nullptr)
{
}
PythonList::PythonList (uint32_t count) :
PythonObject(PyList_New(count))
{
}
PythonList::PythonList (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a list
}
PythonList::PythonList (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a list
}
PythonList::~PythonList ()
{
}
bool
PythonList::Reset (PyObject *py_obj)
{
if (py_obj && PyList_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
uint32_t
PythonList::GetSize() const
{
if (m_py_obj)
return PyList_GET_SIZE(m_py_obj);
return 0;
}
PythonObject
PythonList::GetItemAtIndex(uint32_t index) const
{
if (m_py_obj)
return PythonObject(PyList_GetItem(m_py_obj, index));
return PythonObject();
}
void
PythonList::SetItemAtIndex (uint32_t index, const PythonObject & object)
{
if (m_py_obj && object)
PyList_SetItem(m_py_obj, index, object.get());
}
void
PythonList::AppendItem (const PythonObject &object)
{
if (m_py_obj && object)
PyList_Append(m_py_obj, object.get());
}
StructuredData::ArraySP
PythonList::CreateStructuredArray() const
{
StructuredData::ArraySP result(new StructuredData::Array);
uint32_t count = GetSize();
for (uint32_t i = 0; i < count; ++i)
{
PythonObject obj = GetItemAtIndex(i);
result->AddItem(obj.CreateStructuredObject());
}
return result;
}
//----------------------------------------------------------------------
// PythonDictionary
//----------------------------------------------------------------------
PythonDictionary::PythonDictionary (bool create_empty) :
PythonObject(create_empty ? PyDict_New() : nullptr)
{
}
PythonDictionary::PythonDictionary (PyObject *py_obj) :
PythonObject(py_obj)
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a dictionary
}
PythonDictionary::PythonDictionary (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a dictionary
}
PythonDictionary::~PythonDictionary ()
{
}
bool
PythonDictionary::Reset (PyObject *py_obj)
{
if (py_obj && PyDict_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
uint32_t
PythonDictionary::GetSize() const
{
if (m_py_obj)
return PyDict_Size(m_py_obj);
return 0;
}
PythonObject
PythonDictionary::GetItemForKey (const char *key) const
{
if (key && key[0])
{
PythonString python_key(key);
return GetItemForKey(python_key);
}
return PythonObject();
}
PythonObject
PythonDictionary::GetItemForKey (const PythonString &key) const
{
if (m_py_obj && key)
return PythonObject(PyDict_GetItem(m_py_obj, key.get()));
return PythonObject();
}
const char *
PythonDictionary::GetItemForKeyAsString (const PythonString &key, const char *fail_value) const
{
if (m_py_obj && key)
{
PyObject *py_obj = PyDict_GetItem(m_py_obj, key.get());
if (py_obj && PyString_Check(py_obj))
return PyString_AsString(py_obj);
}
return fail_value;
}
int64_t
PythonDictionary::GetItemForKeyAsInteger (const PythonString &key, int64_t fail_value) const
{
if (m_py_obj && key)
{
PyObject *py_obj = PyDict_GetItem(m_py_obj, key.get());
if (py_obj)
{
if (PyInt_Check(py_obj))
return PyInt_AsLong(py_obj);
if (PyLong_Check(py_obj))
return PyLong_AsLong(py_obj);
}
}
return fail_value;
}
PythonList
PythonDictionary::GetKeys () const
{
if (m_py_obj)
return PythonList(PyDict_Keys(m_py_obj));
return PythonList(true);
}
PythonString
PythonDictionary::GetKeyAtPosition (uint32_t pos) const
{
PyObject *key, *value;
Py_ssize_t pos_iter = 0;
if (m_py_obj)
{
while (PyDict_Next(m_py_obj, &pos_iter, &key, &value))
{
if (pos-- == 0)
return PythonString(key);
}
}
return PythonString();
}
PythonObject
PythonDictionary::GetValueAtPosition (uint32_t pos) const
{
PyObject *key, *value;
Py_ssize_t pos_iter = 0;
if (!m_py_obj)
return PythonObject();
while (PyDict_Next(m_py_obj, &pos_iter, &key, &value)) {
if (pos-- == 0)
return PythonObject(value);
}
return PythonObject();
}
void
PythonDictionary::SetItemForKey (const PythonString &key, PyObject *value)
{
if (m_py_obj && key && value)
PyDict_SetItem(m_py_obj, key.get(), value);
}
void
PythonDictionary::SetItemForKey (const PythonString &key, const PythonObject &value)
{
if (m_py_obj && key && value)
PyDict_SetItem(m_py_obj, key.get(), value.get());
}
StructuredData::DictionarySP
PythonDictionary::CreateStructuredDictionary() const
{
StructuredData::DictionarySP result(new StructuredData::Dictionary);
PythonList keys(GetKeys());
uint32_t num_keys = keys.GetSize();
for (uint32_t i = 0; i < num_keys; ++i)
{
PythonObject key = keys.GetItemAtIndex(i);
PythonString key_str = key.Str();
PythonObject value = GetItemForKey(key);
StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
result->AddItem(key_str.GetString(), structured_value);
}
return result;
}
#endif
<commit_msg>Unbreak mac build.<commit_after>//===-- PythonDataObjects.cpp ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// In order to guarantee correct working with Python, Python.h *MUST* be
// the *FIRST* header file included here.
#ifdef LLDB_DISABLE_PYTHON
// Python is disabled in this build
#else
#include "lldb/lldb-python.h"
#include <stdio.h>
#include "lldb/Core/Stream.h"
#include "lldb/Host/File.h"
#include "lldb/Interpreter/PythonDataObjects.h"
#include "lldb/Interpreter/ScriptInterpreter.h"
#include "lldb/Interpreter/ScriptInterpreterPython.h"
using namespace lldb_private;
using namespace lldb;
void
StructuredPythonObject::Dump(Stream &s) const
{
s << "Python Obj: 0x" << GetValue();
}
//----------------------------------------------------------------------
// PythonObject
//----------------------------------------------------------------------
void
PythonObject::Dump (Stream &strm) const
{
if (m_py_obj)
{
FILE *file = ::tmpfile();
if (file)
{
::PyObject_Print (m_py_obj, file, 0);
const long length = ftell (file);
if (length)
{
::rewind(file);
std::vector<char> file_contents (length,'\0');
const size_t length_read = ::fread (file_contents.data(), 1, file_contents.size(), file);
if (length_read > 0)
strm.Write (file_contents.data(), length_read);
}
::fclose (file);
}
}
else
strm.PutCString ("NULL");
}
PyObjectType
PythonObject::GetObjectType() const
{
if (IsNULLOrNone())
return PyObjectType::None;
if (PyList_Check(m_py_obj))
return PyObjectType::List;
if (PyDict_Check(m_py_obj))
return PyObjectType::Dictionary;
if (PyString_Check(m_py_obj))
return PyObjectType::String;
if (PyInt_Check(m_py_obj) || PyLong_Check(m_py_obj))
return PyObjectType::Integer;
return PyObjectType::Unknown;
}
PythonString
PythonObject::Repr ()
{
if (!m_py_obj)
return PythonString ();
PyObject *repr = PyObject_Repr(m_py_obj);
if (!repr)
return PythonString ();
return PythonString(repr);
}
PythonString
PythonObject::Str ()
{
if (!m_py_obj)
return PythonString ();
PyObject *str = PyObject_Str(m_py_obj);
if (!str)
return PythonString ();
return PythonString(str);
}
bool
PythonObject::IsNULLOrNone () const
{
return ((m_py_obj == nullptr) || (m_py_obj == Py_None));
}
StructuredData::ObjectSP
PythonObject::CreateStructuredObject() const
{
switch (GetObjectType())
{
case PyObjectType::Dictionary:
return PythonDictionary(m_py_obj).CreateStructuredDictionary();
case PyObjectType::Integer:
return PythonInteger(m_py_obj).CreateStructuredInteger();
case PyObjectType::List:
return PythonList(m_py_obj).CreateStructuredArray();
case PyObjectType::String:
return PythonString(m_py_obj).CreateStructuredString();
case PyObjectType::None:
return StructuredData::ObjectSP();
default:
return StructuredData::ObjectSP(new StructuredPythonObject(m_py_obj));
}
}
//----------------------------------------------------------------------
// PythonString
//----------------------------------------------------------------------
PythonString::PythonString (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a string
}
PythonString::PythonString (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a string
}
PythonString::PythonString (llvm::StringRef string) :
PythonObject(PyString_FromStringAndSize(string.data(), string.size()))
{
}
PythonString::PythonString(const char *string) :
PythonObject(PyString_FromString(string))
{
}
PythonString::PythonString () :
PythonObject()
{
}
PythonString::~PythonString ()
{
}
bool
PythonString::Reset (PyObject *py_obj)
{
if (py_obj && PyString_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
llvm::StringRef
PythonString::GetString() const
{
if (m_py_obj)
return llvm::StringRef(PyString_AsString(m_py_obj), GetSize());
return llvm::StringRef();
}
size_t
PythonString::GetSize() const
{
if (m_py_obj)
return PyString_Size(m_py_obj);
return 0;
}
void
PythonString::SetString (llvm::StringRef string)
{
PythonObject::Reset(PyString_FromStringAndSize(string.data(), string.size()));
}
StructuredData::StringSP
PythonString::CreateStructuredString() const
{
StructuredData::StringSP result(new StructuredData::String);
result->SetValue(GetString());
return result;
}
//----------------------------------------------------------------------
// PythonInteger
//----------------------------------------------------------------------
PythonInteger::PythonInteger (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a integer type
}
PythonInteger::PythonInteger (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a integer type
}
PythonInteger::PythonInteger (int64_t value) :
PythonObject()
{
SetInteger (value);
}
PythonInteger::~PythonInteger ()
{
}
bool
PythonInteger::Reset (PyObject *py_obj)
{
if (py_obj)
{
if (PyInt_Check (py_obj) || PyLong_Check(py_obj))
return PythonObject::Reset(py_obj);
}
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
int64_t
PythonInteger::GetInteger() const
{
if (m_py_obj)
{
if (PyInt_Check(m_py_obj))
return PyInt_AsLong(m_py_obj);
else if (PyLong_Check(m_py_obj))
return PyLong_AsLongLong(m_py_obj);
}
return UINT64_MAX;
}
void
PythonInteger::SetInteger (int64_t value)
{
PythonObject::Reset(PyLong_FromLongLong(value));
}
StructuredData::IntegerSP
PythonInteger::CreateStructuredInteger() const
{
StructuredData::IntegerSP result(new StructuredData::Integer);
result->SetValue(GetInteger());
return result;
}
//----------------------------------------------------------------------
// PythonList
//----------------------------------------------------------------------
PythonList::PythonList (bool create_empty) :
PythonObject(create_empty ? PyList_New(0) : nullptr)
{
}
PythonList::PythonList (uint32_t count) :
PythonObject(PyList_New(count))
{
}
PythonList::PythonList (PyObject *py_obj) :
PythonObject()
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a list
}
PythonList::PythonList (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a list
}
PythonList::~PythonList ()
{
}
bool
PythonList::Reset (PyObject *py_obj)
{
if (py_obj && PyList_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
uint32_t
PythonList::GetSize() const
{
if (m_py_obj)
return PyList_GET_SIZE(m_py_obj);
return 0;
}
PythonObject
PythonList::GetItemAtIndex(uint32_t index) const
{
if (m_py_obj)
return PythonObject(PyList_GetItem(m_py_obj, index));
return PythonObject();
}
void
PythonList::SetItemAtIndex (uint32_t index, const PythonObject & object)
{
if (m_py_obj && object)
PyList_SetItem(m_py_obj, index, object.get());
}
void
PythonList::AppendItem (const PythonObject &object)
{
if (m_py_obj && object)
PyList_Append(m_py_obj, object.get());
}
StructuredData::ArraySP
PythonList::CreateStructuredArray() const
{
StructuredData::ArraySP result(new StructuredData::Array);
uint32_t count = GetSize();
for (uint32_t i = 0; i < count; ++i)
{
PythonObject obj = GetItemAtIndex(i);
result->AddItem(obj.CreateStructuredObject());
}
return result;
}
//----------------------------------------------------------------------
// PythonDictionary
//----------------------------------------------------------------------
PythonDictionary::PythonDictionary (bool create_empty) :
PythonObject(create_empty ? PyDict_New() : nullptr)
{
}
PythonDictionary::PythonDictionary (PyObject *py_obj) :
PythonObject(py_obj)
{
Reset(py_obj); // Use "Reset()" to ensure that py_obj is a dictionary
}
PythonDictionary::PythonDictionary (const PythonObject &object) :
PythonObject()
{
Reset(object.get()); // Use "Reset()" to ensure that py_obj is a dictionary
}
PythonDictionary::~PythonDictionary ()
{
}
bool
PythonDictionary::Reset (PyObject *py_obj)
{
if (py_obj && PyDict_Check(py_obj))
return PythonObject::Reset(py_obj);
PythonObject::Reset(nullptr);
return py_obj == nullptr;
}
uint32_t
PythonDictionary::GetSize() const
{
if (m_py_obj)
return PyDict_Size(m_py_obj);
return 0;
}
PythonObject
PythonDictionary::GetItemForKey (const char *key) const
{
if (key && key[0])
{
PythonString python_key(key);
return GetItemForKey(python_key);
}
return PythonObject();
}
PythonObject
PythonDictionary::GetItemForKey (const PythonString &key) const
{
if (m_py_obj && key)
return PythonObject(PyDict_GetItem(m_py_obj, key.get()));
return PythonObject();
}
const char *
PythonDictionary::GetItemForKeyAsString (const PythonString &key, const char *fail_value) const
{
if (m_py_obj && key)
{
PyObject *py_obj = PyDict_GetItem(m_py_obj, key.get());
if (py_obj && PyString_Check(py_obj))
return PyString_AsString(py_obj);
}
return fail_value;
}
int64_t
PythonDictionary::GetItemForKeyAsInteger (const PythonString &key, int64_t fail_value) const
{
if (m_py_obj && key)
{
PyObject *py_obj = PyDict_GetItem(m_py_obj, key.get());
if (py_obj)
{
if (PyInt_Check(py_obj))
return PyInt_AsLong(py_obj);
if (PyLong_Check(py_obj))
return PyLong_AsLong(py_obj);
}
}
return fail_value;
}
PythonList
PythonDictionary::GetKeys () const
{
if (m_py_obj)
return PythonList(PyDict_Keys(m_py_obj));
return PythonList(true);
}
PythonString
PythonDictionary::GetKeyAtPosition (uint32_t pos) const
{
PyObject *key, *value;
Py_ssize_t pos_iter = 0;
if (m_py_obj)
{
while (PyDict_Next(m_py_obj, &pos_iter, &key, &value))
{
if (pos-- == 0)
return PythonString(key);
}
}
return PythonString();
}
PythonObject
PythonDictionary::GetValueAtPosition (uint32_t pos) const
{
PyObject *key, *value;
Py_ssize_t pos_iter = 0;
if (!m_py_obj)
return PythonObject();
while (PyDict_Next(m_py_obj, &pos_iter, &key, &value)) {
if (pos-- == 0)
return PythonObject(value);
}
return PythonObject();
}
void
PythonDictionary::SetItemForKey (const PythonString &key, PyObject *value)
{
if (m_py_obj && key && value)
PyDict_SetItem(m_py_obj, key.get(), value);
}
void
PythonDictionary::SetItemForKey (const PythonString &key, const PythonObject &value)
{
if (m_py_obj && key && value)
PyDict_SetItem(m_py_obj, key.get(), value.get());
}
StructuredData::DictionarySP
PythonDictionary::CreateStructuredDictionary() const
{
StructuredData::DictionarySP result(new StructuredData::Dictionary);
PythonList keys(GetKeys());
uint32_t num_keys = keys.GetSize();
for (uint32_t i = 0; i < num_keys; ++i)
{
PythonObject key = keys.GetItemAtIndex(i);
PythonString key_str = key.Str();
PythonObject value = GetItemForKey(key);
StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
result->AddItem(key_str.GetString(), structured_value);
}
return result;
}
#endif
<|endoftext|>
|
<commit_before>//
// JSONEventSerializer.h
//
// $Id: //poco/1.4/JS/Bridge/src/JSONEventSerializer.cpp#3 $
//
// Library: JSBridge
// Package: Bridge
// Module: JSONEventSerializer
//
// Definition of the JSONEventSerializser class.
//
// Copyright (c) 2013-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/JS/Bridge/JSONEventSerializer.h"
#include "Poco/Base64Encoder.h"
#include <sstream>
namespace Poco {
namespace JS {
namespace Bridge {
const std::string JSONEventSerializer::JSON_TRUE("true");
const std::string JSONEventSerializer::JSON_FALSE("false");
const std::string JSONEventSerializer::JSON_NULL("null");
JSONEventSerializer::JSONEventSerializer():
_pStream(0),
_indent(0)
{
}
JSONEventSerializer::~JSONEventSerializer()
{
}
void JSONEventSerializer::setupImpl(std::ostream& out)
{
resetImpl();
_pStream = &out;
}
void JSONEventSerializer::serializeMessageBegin(const std::string& name, Poco::RemotingNG::SerializerBase::MessageType type)
{
poco_assert_dbg(_pStream);
poco_assert_dbg(type == Poco::RemotingNG::SerializerBase::MESSAGE_EVENT);
*_pStream << "{\n";
_indent = 1;
_state.push_back(ST_OBJECT_FIRST);
}
void JSONEventSerializer::serializeMessageEnd(const std::string& name, Poco::RemotingNG::SerializerBase::MessageType type)
{
poco_assert_dbg(_pStream);
poco_assert_dbg(type == Poco::RemotingNG::SerializerBase::MESSAGE_EVENT);
_state.pop_back();
_indent = 0;
*_pStream <<
"\n" <<
"}\n";
_pStream->flush();
_pStream = 0;
}
void JSONEventSerializer::serializeFaultMessage(const std::string& methodName, Poco::Exception& e)
{
}
void JSONEventSerializer::serializeStructBegin(const std::string& name)
{
writeSeparator();
if (_state.back() != ST_ARRAY)
{
*_pStream << std::string(_indent, '\t') << "\"" << name << "\":\n";
}
*_pStream << std::string(_indent, '\t') << "{";
++_indent;
_state.push_back(ST_OBJECT_FIRST);
}
void JSONEventSerializer::serializeStructEnd(const std::string& name)
{
_state.pop_back();
--_indent;
*_pStream <<
"\n" <<
std::string(_indent, '\t') << "}";
}
void JSONEventSerializer::serializeSequenceBegin(const std::string& name, Poco::UInt32 numElems)
{
writeSeparator();
if (_state.back() != ST_ARRAY)
{
*_pStream << std::string(_indent, '\t') << "\"" << name << "\":\n";
}
*_pStream << std::string(_indent, '\t') << "[";
++_indent;
_state.push_back(ST_ARRAY_FIRST);
}
void JSONEventSerializer::serializeSequenceEnd(const std::string& name)
{
_state.pop_back();
--_indent;
*_pStream <<
"\n" <<
std::string(_indent, '\t') << "]";
}
void JSONEventSerializer::serializeNullableBegin(const std::string& name, bool isNull)
{
if (isNull)
{
serializeData(name, JSON_NULL);
}
}
void JSONEventSerializer::serializeNullableEnd(const std::string&)
{
}
void JSONEventSerializer::serialize(const std::string& name, char val)
{
std::string tmp("\"");
tmp += val;
tmp += '\"';
serializeData(name, tmp);
}
void JSONEventSerializer::serialize(const std::string& name, const std::vector<char>& val)
{
std::stringstream base64;
base64 << '\"';
Poco::Base64Encoder encoder(base64);
encoder.write(&val[0], static_cast<std::streamsize>(val.size()));
encoder.close();
base64 << '\"';
serializeData(name, base64.str());
}
void JSONEventSerializer::serialize(const std::string& name, const std::string& val)
{
std::string str("\"");
for (std::string::const_iterator it = val.begin(); it != val.end(); ++it)
{
switch (*it)
{
case '\f':
str += "\\f";
break;
case '\t':
str += "\\t";
break;
case '\r':
str += "\\r";
break;
case '\n':
str += "\\n";
break;
case '\b':
str += "\\b";
break;
case '"':
str += "\\\"";
break;
case '\\':
str += "\\\\";
break;
default:
str += *it;
}
}
str.append("\"");
serializeData(name, str);
}
void JSONEventSerializer::serializeData(const std::string& name, const std::string& val)
{
writeSeparator();
*_pStream << std::string(_indent, '\t');
if (_state.back() != ST_ARRAY)
{
*_pStream << "\"" << name << "\": ";
}
*_pStream << val;
}
void JSONEventSerializer::writeSeparator()
{
switch (_state.back())
{
case ST_OBJECT_FIRST:
*_pStream << "\n";
_state.back() = ST_OBJECT;
break;
case ST_ARRAY_FIRST:
*_pStream << "\n";
_state.back() = ST_ARRAY;
break;
default:
*_pStream << ",\n";
break;
}
}
void JSONEventSerializer::resetImpl()
{
_indent = 0;
_state.clear();
}
} } } // namespace Poco::JS::Bridge
<commit_msg>bugfix: correctly handle control characters in strings<commit_after>//
// JSONEventSerializer.h
//
// $Id: //poco/1.4/JS/Bridge/src/JSONEventSerializer.cpp#3 $
//
// Library: JSBridge
// Package: Bridge
// Module: JSONEventSerializer
//
// Definition of the JSONEventSerializser class.
//
// Copyright (c) 2013-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "Poco/JS/Bridge/JSONEventSerializer.h"
#include "Poco/Base64Encoder.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
namespace Poco {
namespace JS {
namespace Bridge {
const std::string JSONEventSerializer::JSON_TRUE("true");
const std::string JSONEventSerializer::JSON_FALSE("false");
const std::string JSONEventSerializer::JSON_NULL("null");
JSONEventSerializer::JSONEventSerializer():
_pStream(0),
_indent(0)
{
}
JSONEventSerializer::~JSONEventSerializer()
{
}
void JSONEventSerializer::setupImpl(std::ostream& out)
{
resetImpl();
_pStream = &out;
}
void JSONEventSerializer::serializeMessageBegin(const std::string& name, Poco::RemotingNG::SerializerBase::MessageType type)
{
poco_assert_dbg(_pStream);
poco_assert_dbg(type == Poco::RemotingNG::SerializerBase::MESSAGE_EVENT);
*_pStream << "{\n";
_indent = 1;
_state.push_back(ST_OBJECT_FIRST);
}
void JSONEventSerializer::serializeMessageEnd(const std::string& name, Poco::RemotingNG::SerializerBase::MessageType type)
{
poco_assert_dbg(_pStream);
poco_assert_dbg(type == Poco::RemotingNG::SerializerBase::MESSAGE_EVENT);
_state.pop_back();
_indent = 0;
*_pStream <<
"\n" <<
"}\n";
_pStream->flush();
_pStream = 0;
}
void JSONEventSerializer::serializeFaultMessage(const std::string& methodName, Poco::Exception& e)
{
}
void JSONEventSerializer::serializeStructBegin(const std::string& name)
{
writeSeparator();
if (_state.back() != ST_ARRAY)
{
*_pStream << std::string(_indent, '\t') << "\"" << name << "\":\n";
}
*_pStream << std::string(_indent, '\t') << "{";
++_indent;
_state.push_back(ST_OBJECT_FIRST);
}
void JSONEventSerializer::serializeStructEnd(const std::string& name)
{
_state.pop_back();
--_indent;
*_pStream <<
"\n" <<
std::string(_indent, '\t') << "}";
}
void JSONEventSerializer::serializeSequenceBegin(const std::string& name, Poco::UInt32 numElems)
{
writeSeparator();
if (_state.back() != ST_ARRAY)
{
*_pStream << std::string(_indent, '\t') << "\"" << name << "\":\n";
}
*_pStream << std::string(_indent, '\t') << "[";
++_indent;
_state.push_back(ST_ARRAY_FIRST);
}
void JSONEventSerializer::serializeSequenceEnd(const std::string& name)
{
_state.pop_back();
--_indent;
*_pStream <<
"\n" <<
std::string(_indent, '\t') << "]";
}
void JSONEventSerializer::serializeNullableBegin(const std::string& name, bool isNull)
{
if (isNull)
{
serializeData(name, JSON_NULL);
}
}
void JSONEventSerializer::serializeNullableEnd(const std::string&)
{
}
void JSONEventSerializer::serialize(const std::string& name, char val)
{
std::string tmp("\"");
tmp += val;
tmp += '\"';
serializeData(name, tmp);
}
void JSONEventSerializer::serialize(const std::string& name, const std::vector<char>& val)
{
std::stringstream base64;
base64 << '\"';
Poco::Base64Encoder encoder(base64);
encoder.write(&val[0], static_cast<std::streamsize>(val.size()));
encoder.close();
base64 << '\"';
serializeData(name, base64.str());
}
void JSONEventSerializer::serialize(const std::string& name, const std::string& val)
{
std::string str("\"");
for (std::string::const_iterator it = val.begin(); it != val.end(); ++it)
{
switch (*it)
{
case '\f':
str += "\\f";
break;
case '\t':
str += "\\t";
break;
case '\r':
str += "\\r";
break;
case '\n':
str += "\\n";
break;
case '\b':
str += "\\b";
break;
case '"':
str += "\\\"";
break;
case '\\':
str += "\\\\";
break;
default:
if (*it >= 0 && *it < ' ')
{
str += "\\u";
Poco::NumberFormatter::appendHex(str, *it, 4);
}
else str += *it;
}
}
str.append("\"");
serializeData(name, str);
}
void JSONEventSerializer::serializeData(const std::string& name, const std::string& val)
{
writeSeparator();
*_pStream << std::string(_indent, '\t');
if (_state.back() != ST_ARRAY)
{
*_pStream << "\"" << name << "\": ";
}
*_pStream << val;
}
void JSONEventSerializer::writeSeparator()
{
switch (_state.back())
{
case ST_OBJECT_FIRST:
*_pStream << "\n";
_state.back() = ST_OBJECT;
break;
case ST_ARRAY_FIRST:
*_pStream << "\n";
_state.back() = ST_ARRAY;
break;
default:
*_pStream << ",\n";
break;
}
}
void JSONEventSerializer::resetImpl()
{
_indent = 0;
_state.clear();
}
} } } // namespace Poco::JS::Bridge
<|endoftext|>
|
<commit_before>//! \file
//! \brief GPIO device interface for STM32 platform
//! \todo Detailed explanation.
#ifndef PLATFORM_GPIO_DEVICE_HPP
#define PLATFORM_GPIO_DEVICE_HPP
namespace ecl
{
// GPIO numbers
enum class gpio_num
{
pin0,
pin1,
pin2,
pin3,
pin4,
pin5,
pin6,
pin7,
pin8,
pin9,
pin10,
pin11,
pin12,
pin13,
pin14,
pin15,
};
// GPIO ports
enum class gpio_port
{
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k
};
// Encapsulates pin usage
//! GPIO class incapsulates pin usage.
//! \tparam Port GPIO port on STM32 device.
//! \tparam Pin Pin within given port.
template< gpio_port Port, gpio_num Pin >
class gpio
{
public:
static constexpr auto port = Port;
static constexpr auto pin = Pin;
//! Sets output pin level to high.
static void set();
//! Sets output pin level to low.
static void reset();
//! Toggles pin level.
static void toggle();
//! Gets level on a pin.
//! \return True if level is high, false if level is low.
static bool get();
private:
//! \brief Returns STM32 representation of the port
static constexpr auto pick_port();
//! \brief Returns STM32 representation of the pin
static constexpr auto pick_pin();
};
//------------------------------------------------------------------------------
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::set()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_WriteBit(hw_port, hw_pin, Bit_SET);
}
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::reset()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_WriteBit(hw_port, hw_pin, Bit_RESET);
}
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::toggle()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_ToggleBits(hw_port, hw_pin);
}
template< gpio_port Port, gpio_num Pin >
bool gpio< Port, Pin >::get()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
return GPIO_ReadInputDataBit(hw_port, hw_pin) == Bit_SET;
}
//------------------------------------------------------------------------------
template< gpio_port Port, gpio_num Pin >
constexpr auto gpio< Port, Pin >::pick_port()
{
switch (Port) {
case gpio_port::a:
return GPIOA;
case gpio_port::b:
return GPIOB;
case gpio_port::c:
return GPIOC;
case gpio_port::d:
return GPIOD;
case gpio_port::e:
return GPIOE;
case gpio_port::f:
return GPIOF;
case gpio_port::g:
return GPIOG;
case gpio_port::h:
return GPIOH;
case gpio_port::i:
return GPIOI;
case gpio_port::j:
return GPIOJ;
case gpio_port::k:
return GPIOK;
}
}
template< gpio_port Port, gpio_num Pin >
constexpr auto gpio< Port, Pin >::pick_pin()
{
switch (Pin) {
case gpio_num::pin0:
return GPIO_Pin_0;
case gpio_num::pin1:
return GPIO_Pin_1;
case gpio_num::pin2:
return GPIO_Pin_2;
case gpio_num::pin3:
return GPIO_Pin_3;
case gpio_num::pin4:
return GPIO_Pin_4;
case gpio_num::pin5:
return GPIO_Pin_5;
case gpio_num::pin6:
return GPIO_Pin_6;
case gpio_num::pin7:
return GPIO_Pin_7;
case gpio_num::pin8:
return GPIO_Pin_8;
case gpio_num::pin9:
return GPIO_Pin_9;
case gpio_num::pin10:
return GPIO_Pin_10;
case gpio_num::pin11:
return GPIO_Pin_11;
case gpio_num::pin12:
return GPIO_Pin_12;
case gpio_num::pin13:
return GPIO_Pin_13;
case gpio_num::pin14:
return GPIO_Pin_14;
case gpio_num::pin15:
return GPIO_Pin_15;
}
}
} // namespace ecl
#endif
<commit_msg>stm32: protect GPIO driver from non-existing buses<commit_after>//! \file
//! \brief GPIO device interface for STM32 platform
//! \todo Detailed explanation.
#ifndef PLATFORM_GPIO_DEVICE_HPP
#define PLATFORM_GPIO_DEVICE_HPP
namespace ecl
{
// GPIO numbers
enum class gpio_num
{
pin0,
pin1,
pin2,
pin3,
pin4,
pin5,
pin6,
pin7,
pin8,
pin9,
pin10,
pin11,
pin12,
pin13,
pin14,
pin15,
};
// GPIO ports
enum class gpio_port
{
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k
};
// Encapsulates pin usage
//! GPIO class incapsulates pin usage.
//! \tparam Port GPIO port on STM32 device.
//! \tparam Pin Pin within given port.
template< gpio_port Port, gpio_num Pin >
class gpio
{
public:
static constexpr auto port = Port;
static constexpr auto pin = Pin;
//! Sets output pin level to high.
static void set();
//! Sets output pin level to low.
static void reset();
//! Toggles pin level.
static void toggle();
//! Gets level on a pin.
//! \return True if level is high, false if level is low.
static bool get();
private:
//! \brief Returns STM32 representation of the port
static constexpr auto pick_port();
//! \brief Returns STM32 representation of the pin
static constexpr auto pick_pin();
};
//------------------------------------------------------------------------------
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::set()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_WriteBit(hw_port, hw_pin, Bit_SET);
}
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::reset()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_WriteBit(hw_port, hw_pin, Bit_RESET);
}
template< gpio_port Port, gpio_num Pin >
void gpio< Port, Pin >::toggle()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
GPIO_ToggleBits(hw_port, hw_pin);
}
template< gpio_port Port, gpio_num Pin >
bool gpio< Port, Pin >::get()
{
constexpr auto hw_port = pick_port();
constexpr auto hw_pin = pick_pin();
return GPIO_ReadInputDataBit(hw_port, hw_pin) == Bit_SET;
}
//------------------------------------------------------------------------------
template< gpio_port Port, gpio_num Pin >
constexpr auto gpio< Port, Pin >::pick_port()
{
switch (Port) {
case gpio_port::a:
return GPIOA;
case gpio_port::b:
return GPIOB;
case gpio_port::c:
return GPIOC;
case gpio_port::d:
return GPIOD;
case gpio_port::e:
return GPIOE;
case gpio_port::f:
return GPIOF;
case gpio_port::g:
return GPIOG;
case gpio_port::h:
return GPIOH;
#ifdef GPIOI
case gpio_port::i:
return GPIOI;
#endif
#ifdef GPIOJ
case gpio_port::j:
return GPIOJ;
#endif
#ifdef GPIOK
case gpio_port::k:
return GPIOK;
#endif
}
}
template< gpio_port Port, gpio_num Pin >
constexpr auto gpio< Port, Pin >::pick_pin()
{
switch (Pin) {
case gpio_num::pin0:
return GPIO_Pin_0;
case gpio_num::pin1:
return GPIO_Pin_1;
case gpio_num::pin2:
return GPIO_Pin_2;
case gpio_num::pin3:
return GPIO_Pin_3;
case gpio_num::pin4:
return GPIO_Pin_4;
case gpio_num::pin5:
return GPIO_Pin_5;
case gpio_num::pin6:
return GPIO_Pin_6;
case gpio_num::pin7:
return GPIO_Pin_7;
case gpio_num::pin8:
return GPIO_Pin_8;
case gpio_num::pin9:
return GPIO_Pin_9;
case gpio_num::pin10:
return GPIO_Pin_10;
case gpio_num::pin11:
return GPIO_Pin_11;
case gpio_num::pin12:
return GPIO_Pin_12;
case gpio_num::pin13:
return GPIO_Pin_13;
case gpio_num::pin14:
return GPIO_Pin_14;
case gpio_num::pin15:
return GPIO_Pin_15;
}
}
} // namespace ecl
#endif
<|endoftext|>
|
<commit_before>#ifndef DOUBLE_HPP
#define DOUBLE_HPP
#include <cmath>
static const double EPS = 1.0e-9;
template<int PRECISION>
static inline bool
eq(double a, double b)
{
return std::abs(a - b) < std::pow(10.0, -PRECISION);
}
static inline bool
eq(double a, double b)
{
return std::abs(a - b) < EPS;
}
template<int PRECISION>
static inline bool
neq(double a, double b)
{
return std::abs(a - b) >= std::pow(10.0, -PRECISION);
}
static inline bool
neq(double a, double b)
{
return std::abs(a - b) >= EPS;
}
template<int PRECISION>
static inline bool
lt(double a, double b)
{
return a < b - std::pow(10.0, -PRECISION);
}
static inline bool
lt(double a, double b)
{
return a < b - EPS;
}
template<int PRECISION>
static inline bool
leq(double a, double b)
{
return a < b + std::pow(10.0, -PRECISION);
}
static inline bool
leq(double a, double b)
{
return a < b + EPS;
}
template<int PRECISION>
static inline bool
gt(double a, double b)
{
return a > b - std::pow(10.0, -PRECISION);
}
static inline bool
gt(double a, double b)
{
return a > b - EPS;
}
template<int PRECISION>
static inline bool
geq(double a, double b)
{
return a > b + std::pow(10.0, -PRECISION);
}
static inline bool
geq(double a, double b)
{
return a > b + EPS;
}
template<int PRECISION>
static inline bool
isin(double x, double a, double b)
{
return a - std::pow(10.0, -PRECISION) <= x && x <= b + std::pow(10.0, -PRECISION);
}
static inline bool
isin(double x, double a, double b)
{
return a - EPS <= x && x <= b + EPS;
}
#endif // DOUBLE_HPP
<commit_msg>Use template<commit_after>#ifndef DOUBLE_HPP
#define DOUBLE_HPP
#include <cmath>
#include <type_traits>
template<typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline constexpr double
geteps(int prec=9)
{
return std::pow(static_cast<FType>(1.0), -prec - 1);
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
eq(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return std::abs(a - b) < eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
neq(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return std::abs(a - b) >= eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
lt(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return a < b - eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
leq(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return a < b + eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
gt(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return a > b - eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
geq(FType a, FType b)
{
constexpr FType eps = geteps<FType>(PRECISION);
return a > b + eps;
}
template<int PRECISION=9, typename FType=double, typename std::enable_if<std::is_floating_point<FType>::value, std::nullptr_t>::type = nullptr>
static inline bool
isin(FType x, FType a, FType b)
{
return geq(x, a) && leq(x, b);
}
#endif // DOUBLE_HPP
<|endoftext|>
|
<commit_before>/*
* EDeNseq.cc
*
* Created on: 26.02.2015
* Author: heyne
*/
#include <iostream>
#include "BaseManager.h"
#include "Data.h"
#include "Parameters.h"
#include "SeqClusterManager.h"
#include "SeqClassifyManager.h"
#include "MinHashEncoder.h"
using namespace std;
class Dispatcher {
protected:
Parameters mParameters;
Data mData;
public:
Dispatcher() {
}
void Init(int argc, const char **argv) {
mParameters.Init(argc, argv);
srand(mParameters.mRandomSeed);
mData.Init(&mParameters);
omp_set_num_threads(mParameters.mNumThreads);
}
void Exec() {
ProgressBar pb(100);
cout << SEP << endl << PROG_NAME << endl << "Version: " << PROG_VERSION << endl << "Last Update: " << PROG_DATE << endl << PROG_CREDIT << endl << SEP << endl;
switch (mParameters.mActionCode) {
case CLASSIFY:{
SeqClassifyManager seq_classify_manager(&mParameters, &mData);
seq_classify_manager.Exec();
}
break;
case CLUSTER:{
SeqClusterManager cluster_manager(&mParameters, &mData);
cluster_manager.Exec();
}
break;
default:
throw range_error("ERROR: Unknown action parameter: " + mParameters.mAction);
}
pb.Count(1);
cout << "Total run-time:" << endl;
}
};
int main(int argc, const char **argv) {
try {
Eigen::initParallel();
Dispatcher myDispatcher;
myDispatcher.Init(argc,argv);
myDispatcher.Exec();
} catch (exception& e) {
cerr << e.what() << endl;
}
return 0;
}
<commit_msg>add action TEST<commit_after>/*
* EDeNseq.cc
*
* Created on: 26.02.2015
* Author: heyne
*/
#include <iostream>
#include "BaseManager.h"
#include "Data.h"
#include "Parameters.h"
#include "SeqClusterManager.h"
#include "SeqClassifyManager.h"
#include "TestManager.h"
#include "MinHashEncoder.h"
using namespace std;
class Dispatcher {
protected:
Parameters mParameters;
Data mData;
public:
Dispatcher() {
}
void Init(int argc, const char **argv) {
mParameters.Init(argc, argv);
srand(mParameters.mRandomSeed);
mData.Init(&mParameters);
omp_set_num_threads(mParameters.mNumThreads);
}
void Exec() {
ProgressBar pb(100);
cout << SEP << endl << PROG_NAME << endl << "Version: " << PROG_VERSION << endl << "Last Update: " << PROG_DATE << endl << PROG_CREDIT << endl << SEP << endl;
switch (mParameters.mActionCode) {
case CLASSIFY:{
SeqClassifyManager seq_classify_manager(&mParameters, &mData);
seq_classify_manager.Exec();
}
break;
case CLUSTER:{
SeqClusterManager cluster_manager(&mParameters, &mData);
cluster_manager.Exec();
}
break;
case TEST:{
TestManager test_manager(&mParameters, &mData);
test_manager.Exec();
}
break;
default:
throw range_error("ERROR: Unknown action parameter: " + mParameters.mAction);
}
pb.Count(1);
cout << "Total run-time:" << endl;
}
};
int main(int argc, const char **argv) {
try {
Eigen::initParallel();
Dispatcher myDispatcher;
myDispatcher.Init(argc,argv);
myDispatcher.Exec();
} catch (exception& e) {
cerr << e.what() << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "Editor.h"
Editor::Editor() {
mode_ = MODE_NOTHING;
floors_.push_back(Floor(Vector(0, 0), Vector(3, 0)));
}
void Editor::DrawHandle() {
glBegin(GL_POLYGON);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.03 * cos(ang), 0.03 * sin(ang));
}
glEnd();
glBegin(GL_LINE_LOOP);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.2 * cos(ang), 0.2 * sin(ang));
}
glEnd();
}
void Editor::Update() {
if(mode_ == MODE_NOTHING) {
if(Mouse::I().Pressed(0)) {
for(size_t i=0; i<floors_.size(); ++i) {
if((floors_[i].l_ - Mouse::I().WorldPos()).Len() < 0.2) {
grabbed_pt_ = &floors_[i].l_;
mode_ = MODE_MOVE_POINT;
} else if((floors_[i].r_ - Mouse::I().WorldPos()).Len() < 0.2) {
grabbed_pt_ = &floors_[i].r_;
mode_ = MODE_MOVE_POINT;
}
}
} else if(Mouse::I().Pressed(1)) {
pan_start_ = Mouse::I().WorldPos();
mode_ = MODE_PAN;
} else if(Key::I().Pressed('F')) {
mode_ = MODE_ADD_FLOOR_1;
}
} else if(mode_ == MODE_MOVE_POINT) {
if(!Mouse::I().Pressed(0)) {
mode_ = MODE_NOTHING;
} else {
if(Key::I().Pressed(GLFW_KEY_LSHIFT) ||
Key::I().Pressed(GLFW_KEY_RSHIFT)) {
Vector new_pos = Mouse::I().WorldPos();
new_pos.i = floor(new_pos.i + 0.5);
new_pos.j = floor(new_pos.j + 0.5);
*grabbed_pt_ = new_pos;
} else {
*grabbed_pt_ = Mouse::I().WorldPos();
}
}
} else if(mode_ == MODE_PAN) {
if(!Mouse::I().Pressed(1)) {
mode_ = MODE_NOTHING;
} else {
cam_pos_ += pan_start_ - Mouse::I().WorldPos();
}
} else if(mode_ == MODE_ADD_FLOOR_1) {
if(Mouse::I().Pressed(0)) {
store_pt_ = Mouse::I().WorldPos();
mode_ = MODE_ADD_FLOOR_WAIT;
}
} else if(mode_ == MODE_ADD_FLOOR_WAIT) {
if(!Mouse::I().Pressed(0)) {
mode_ = MODE_ADD_FLOOR_2;
}
} else if(mode_ == MODE_ADD_FLOOR_2) {
if(Mouse::I().Pressed(0)) {
floors_.push_back(Floor(store_pt_, Mouse::I().WorldPos()));
mode_ = MODE_NOTHING;
}
}
}
void Editor::Draw() {
Cam::I().SetPos(cam_pos_);
for(size_t i=0; i<floors_.size(); ++i) {
floors_[i].Draw();
glPushMatrix();
glTranslatef(floors_[i].l_.i, floors_[i].l_.j, 0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
glPushMatrix();
glTranslatef(floors_[i].r_.i, floors_[i].r_.j, 0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
}
/*
if(mode_ == MODE_ADD_POINT) {
glPushMatrix();
glTranslatef(Mouse::I().WorldPos().i,
Mouse::I().WorldPos().j,
0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
}*/
}
<commit_msg>Used better mouse button support to fix floors<commit_after>#include "Editor.h"
Editor::Editor() {
mode_ = MODE_NOTHING;
floors_.push_back(Floor(Vector(0, 0), Vector(3, 0)));
}
void Editor::DrawHandle() {
glBegin(GL_POLYGON);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.03 * cos(ang), 0.03 * sin(ang));
}
glEnd();
glBegin(GL_LINE_LOOP);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.2 * cos(ang), 0.2 * sin(ang));
}
glEnd();
}
void Editor::Update() {
if(mode_ == MODE_NOTHING) {
if(Mouse::I().Pressed(0)) {
for(size_t i=0; i<floors_.size(); ++i) {
if((floors_[i].l_ - Mouse::I().WorldPos()).Len() < 0.2) {
grabbed_pt_ = &floors_[i].l_;
mode_ = MODE_MOVE_POINT;
} else if((floors_[i].r_ - Mouse::I().WorldPos()).Len() < 0.2) {
grabbed_pt_ = &floors_[i].r_;
mode_ = MODE_MOVE_POINT;
}
}
} else if(Mouse::I().Pressed(1)) {
pan_start_ = Mouse::I().WorldPos();
mode_ = MODE_PAN;
} else if(Key::I().Pressed('F')) {
mode_ = MODE_ADD_FLOOR_1;
}
} else if(mode_ == MODE_MOVE_POINT) {
if(!Mouse::I().Pressed(0)) {
mode_ = MODE_NOTHING;
} else {
if(Key::I().Pressed(GLFW_KEY_LSHIFT) ||
Key::I().Pressed(GLFW_KEY_RSHIFT)) {
Vector new_pos = Mouse::I().WorldPos();
new_pos.i = floor(new_pos.i + 0.5);
new_pos.j = floor(new_pos.j + 0.5);
*grabbed_pt_ = new_pos;
} else {
*grabbed_pt_ = Mouse::I().WorldPos();
}
}
} else if(mode_ == MODE_PAN) {
if(!Mouse::I().Pressed(1)) {
mode_ = MODE_NOTHING;
} else {
cam_pos_ += pan_start_ - Mouse::I().WorldPos();
}
} else if(mode_ == MODE_ADD_FLOOR_1) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
store_pt_ = Mouse::I().WorldPos();
mode_ = MODE_ADD_FLOOR_2
}
} else if(mode_ == MODE_ADD_FLOOR_2) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
floors_.push_back(Floor(store_pt_, Mouse::I().WorldPos()));
mode_ = MODE_NOTHING;
}
}
}
void Editor::Draw() {
Cam::I().SetPos(cam_pos_);
for(size_t i=0; i<floors_.size(); ++i) {
floors_[i].Draw();
glPushMatrix();
glTranslatef(floors_[i].l_.i, floors_[i].l_.j, 0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
glPushMatrix();
glTranslatef(floors_[i].r_.i, floors_[i].r_.j, 0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
}
/*
if(mode_ == MODE_ADD_POINT) {
glPushMatrix();
glTranslatef(Mouse::I().WorldPos().i,
Mouse::I().WorldPos().j,
0);
glColor3f(0, 0, 0);
DrawHandle();
glPopMatrix();
}*/
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgdefaultimagenode_p.h"
#include <private/qsgtextureprovider_p.h>
#include <QtCore/qvarlengtharray.h>
#include <QtCore/qmath.h>
#include <QtOpenGL/qglfunctions.h>
QT_BEGIN_NAMESPACE
QSGDefaultImageNode::QSGDefaultImageNode()
: m_sourceRect(0, 0, 1, 1)
, m_dirtyGeometry(false)
, m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
setMaterial(&m_materialO);
setOpaqueMaterial(&m_material);
setGeometry(&m_geometry);
#ifdef QML_RUNTIME_TESTING
description = QLatin1String("image");
#endif
}
void QSGDefaultImageNode::setTargetRect(const QRectF &rect)
{
if (rect == m_targetRect)
return;
m_targetRect = rect;
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::setSourceRect(const QRectF &rect)
{
if (rect == m_sourceRect)
return;
m_sourceRect = rect;
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::setFiltering(QSGTexture::Filtering filtering)
{
if (m_material.filtering() == filtering)
return;
m_material.setFiltering(filtering);
m_materialO.setFiltering(filtering);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setMipmapFiltering(QSGTexture::Filtering filtering)
{
if (m_material.mipmapFiltering() == filtering)
return;
m_material.setMipmapFiltering(filtering);
m_materialO.setMipmapFiltering(filtering);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setVerticalWrapMode(QSGTexture::WrapMode wrapMode)
{
if (m_material.verticalWrapMode() == wrapMode)
return;
m_material.setVerticalWrapMode(wrapMode);
m_materialO.setVerticalWrapMode(wrapMode);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setHorizontalWrapMode(QSGTexture::WrapMode wrapMode)
{
if (m_material.horizontalWrapMode() == wrapMode)
return;
m_material.setHorizontalWrapMode(wrapMode);
m_materialO.setHorizontalWrapMode(wrapMode);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setTexture(QSGTexture *texture)
{
if (texture == m_material.texture())
return;
m_material.setTexture(texture);
m_materialO.setTexture(texture);
// Texture cleanup
// if (!texture.isNull())
// m_material.setBlending(texture->hasAlphaChannel());
markDirty(DirtyMaterial);
// Because the texture can be a different part of the atlas, we need to update it...
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::update()
{
if (m_dirtyGeometry)
updateGeometry();
}
void QSGDefaultImageNode::preprocess()
{
bool doDirty = false;
QSGDynamicTexture *t = qobject_cast<QSGDynamicTexture *>(m_material.texture());
if (t) {
doDirty = t->updateTexture();
updateGeometry();
}
// ### texture cleanup
// bool alpha = m_material.blending();
// if (!m_material->texture().isNull() && alpha != m_material.texture()->hasAlphaChannel()) {
// m_material.setBlending(!alpha);
// doDirty = true;
// }
if (doDirty)
markDirty(DirtyMaterial);
}
inline static bool isPowerOfTwo(int x)
{
// Assumption: x >= 1
return x == (x & -x);
}
void QSGDefaultImageNode::updateGeometry()
{
const QSGTexture *t = m_material.texture();
if (!t) {
m_geometry.allocate(4);
m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
QSGGeometry::updateTexturedRectGeometry(&m_geometry, QRectF(), QRectF());
} else {
QRectF textureRect = t->textureSubRect();
bool isSubRect = textureRect != QRectF(0, 0, 1, 1);
const int ceilRight = qCeil(m_sourceRect.right());
const int floorLeft = qFloor(m_sourceRect.left());
const int ceilBottom = qCeil(m_sourceRect.bottom());
const int floorTop = qFloor(m_sourceRect.top());
const int hCells = ceilRight - floorLeft;
const int vCells = ceilBottom - floorTop;
bool isRepeating = hCells > 1 || vCells > 1;
#ifdef QT_OPENGL_ES_2
const QGLContext *ctx = QGLContext::currentContext();
bool npotSupported = ctx->functions()->hasOpenGLFeature(QGLFunctions::NPOTTextures);
QSize size = t->textureSize();
bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
if (isRepeating && (isSubRect || (isNpot && !npotSupported))) {
#else
if (isRepeating && isSubRect) {
#endif
m_geometry.allocate(hCells * vCells * 4, hCells * vCells * 6);
m_geometry.setDrawingMode(GL_TRIANGLES);
struct X { float x, tx; };
struct Y { float y, ty; };
QVarLengthArray<X, 32> xData(2 * hCells);
QVarLengthArray<Y, 32> yData(2 * vCells);
X *xs = xData.data();
Y *ys = yData.data();
xs->x = m_targetRect.left();
xs->tx = textureRect.x() + (m_sourceRect.left() - floorLeft) * textureRect.width();
++xs;
ys->y = m_targetRect.top();
ys->ty = textureRect.y() + (m_sourceRect.top() - floorTop) * textureRect.height();
++ys;
float a, b;
b = m_targetRect.width() / m_sourceRect.width();
a = m_targetRect.x() - m_sourceRect.x() * b;
for (int i = floorLeft + 1; i <= ceilRight - 1; ++i) {
xs[0].x = xs[1].x = a + b * i;
xs[0].tx = 1;
xs[1].tx = 0;
xs += 2;
}
b = m_targetRect.height() / m_sourceRect.height();
a = m_targetRect.y() - m_sourceRect.y() * b;
for (int i = floorTop + 1; i <= ceilBottom - 1; ++i) {
ys[0].y = ys[1].y = a + b * i;
ys[0].ty = 1;
ys[1].ty = 0;
ys += 2;
}
xs->x = m_targetRect.right();
xs->tx = textureRect.x() + (m_sourceRect.right() - ceilRight + 1) * textureRect.width();
ys->y = m_targetRect.bottom();
ys->ty = textureRect.y() + (m_sourceRect.bottom() - ceilBottom + 1) * textureRect.height();
QSGGeometry::TexturedPoint2D *vertices = m_geometry.vertexDataAsTexturedPoint2D();
ys = yData.data();
for (int j = 0; j < vCells; ++j, ys += 2) {
xs = xData.data();
for (int i = 0; i < hCells; ++i, xs += 2) {
vertices[0].x = vertices[2].x = xs[0].x;
vertices[0].tx = vertices[2].tx = xs[0].tx;
vertices[1].x = vertices[3].x = xs[1].x;
vertices[1].tx = vertices[3].tx = xs[1].tx;
vertices[0].y = vertices[1].y = ys[0].y;
vertices[0].ty = vertices[1].ty = ys[0].ty;
vertices[2].y = vertices[3].y = ys[1].y;
vertices[2].ty = vertices[3].ty = ys[1].ty;
vertices += 4;
}
}
quint16 *indices = m_geometry.indexDataAsUShort();
for (int i = 0; i < 4 * vCells * hCells; i += 4) {
*indices++ = i;
*indices++ = i + 2;
*indices++ = i + 3;
*indices++ = i + 3;
*indices++ = i + 1;
*indices++ = i;
}
} else {
QRectF sr(textureRect.x() + m_sourceRect.x() * textureRect.width(),
textureRect.y() + m_sourceRect.y() * textureRect.height(),
m_sourceRect.width() * textureRect.width(),
m_sourceRect.height() * textureRect.height());
m_geometry.allocate(4);
m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_targetRect, sr);
}
}
markDirty(DirtyGeometry);
m_dirtyGeometry = false;
}
QT_END_NAMESPACE
<commit_msg>Compile.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgdefaultimagenode_p.h"
#include <private/qsgtextureprovider_p.h>
#include <QtCore/qvarlengtharray.h>
#include <QtCore/qmath.h>
#include <QtOpenGL/qglfunctions.h>
QT_BEGIN_NAMESPACE
QSGDefaultImageNode::QSGDefaultImageNode()
: m_sourceRect(0, 0, 1, 1)
, m_dirtyGeometry(false)
, m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
setMaterial(&m_materialO);
setOpaqueMaterial(&m_material);
setGeometry(&m_geometry);
#ifdef QML_RUNTIME_TESTING
description = QLatin1String("image");
#endif
}
void QSGDefaultImageNode::setTargetRect(const QRectF &rect)
{
if (rect == m_targetRect)
return;
m_targetRect = rect;
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::setSourceRect(const QRectF &rect)
{
if (rect == m_sourceRect)
return;
m_sourceRect = rect;
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::setFiltering(QSGTexture::Filtering filtering)
{
if (m_material.filtering() == filtering)
return;
m_material.setFiltering(filtering);
m_materialO.setFiltering(filtering);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setMipmapFiltering(QSGTexture::Filtering filtering)
{
if (m_material.mipmapFiltering() == filtering)
return;
m_material.setMipmapFiltering(filtering);
m_materialO.setMipmapFiltering(filtering);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setVerticalWrapMode(QSGTexture::WrapMode wrapMode)
{
if (m_material.verticalWrapMode() == wrapMode)
return;
m_material.setVerticalWrapMode(wrapMode);
m_materialO.setVerticalWrapMode(wrapMode);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setHorizontalWrapMode(QSGTexture::WrapMode wrapMode)
{
if (m_material.horizontalWrapMode() == wrapMode)
return;
m_material.setHorizontalWrapMode(wrapMode);
m_materialO.setHorizontalWrapMode(wrapMode);
markDirty(DirtyMaterial);
}
void QSGDefaultImageNode::setTexture(QSGTexture *texture)
{
if (texture == m_material.texture())
return;
m_material.setTexture(texture);
m_materialO.setTexture(texture);
// Texture cleanup
// if (!texture.isNull())
// m_material.setBlending(texture->hasAlphaChannel());
markDirty(DirtyMaterial);
// Because the texture can be a different part of the atlas, we need to update it...
m_dirtyGeometry = true;
}
void QSGDefaultImageNode::update()
{
if (m_dirtyGeometry)
updateGeometry();
}
void QSGDefaultImageNode::preprocess()
{
bool doDirty = false;
QSGDynamicTexture *t = qobject_cast<QSGDynamicTexture *>(m_material.texture());
if (t) {
doDirty = t->updateTexture();
updateGeometry();
}
// ### texture cleanup
// bool alpha = m_material.blending();
// if (!m_material->texture().isNull() && alpha != m_material.texture()->hasAlphaChannel()) {
// m_material.setBlending(!alpha);
// doDirty = true;
// }
if (doDirty)
markDirty(DirtyMaterial);
}
inline static bool isPowerOfTwo(int x)
{
// Assumption: x >= 1
return x == (x & -x);
}
namespace {
struct X { float x, tx; };
struct Y { float y, ty; };
}
void QSGDefaultImageNode::updateGeometry()
{
const QSGTexture *t = m_material.texture();
if (!t) {
m_geometry.allocate(4);
m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
QSGGeometry::updateTexturedRectGeometry(&m_geometry, QRectF(), QRectF());
} else {
QRectF textureRect = t->textureSubRect();
bool isSubRect = textureRect != QRectF(0, 0, 1, 1);
const int ceilRight = qCeil(m_sourceRect.right());
const int floorLeft = qFloor(m_sourceRect.left());
const int ceilBottom = qCeil(m_sourceRect.bottom());
const int floorTop = qFloor(m_sourceRect.top());
const int hCells = ceilRight - floorLeft;
const int vCells = ceilBottom - floorTop;
bool isRepeating = hCells > 1 || vCells > 1;
#ifdef QT_OPENGL_ES_2
const QGLContext *ctx = QGLContext::currentContext();
bool npotSupported = ctx->functions()->hasOpenGLFeature(QGLFunctions::NPOTTextures);
QSize size = t->textureSize();
bool isNpot = !isPowerOfTwo(size.width()) || !isPowerOfTwo(size.height());
if (isRepeating && (isSubRect || (isNpot && !npotSupported))) {
#else
if (isRepeating && isSubRect) {
#endif
m_geometry.allocate(hCells * vCells * 4, hCells * vCells * 6);
m_geometry.setDrawingMode(GL_TRIANGLES);
QVarLengthArray<X, 32> xData(2 * hCells);
QVarLengthArray<Y, 32> yData(2 * vCells);
X *xs = xData.data();
Y *ys = yData.data();
xs->x = m_targetRect.left();
xs->tx = textureRect.x() + (m_sourceRect.left() - floorLeft) * textureRect.width();
++xs;
ys->y = m_targetRect.top();
ys->ty = textureRect.y() + (m_sourceRect.top() - floorTop) * textureRect.height();
++ys;
float a, b;
b = m_targetRect.width() / m_sourceRect.width();
a = m_targetRect.x() - m_sourceRect.x() * b;
for (int i = floorLeft + 1; i <= ceilRight - 1; ++i) {
xs[0].x = xs[1].x = a + b * i;
xs[0].tx = 1;
xs[1].tx = 0;
xs += 2;
}
b = m_targetRect.height() / m_sourceRect.height();
a = m_targetRect.y() - m_sourceRect.y() * b;
for (int i = floorTop + 1; i <= ceilBottom - 1; ++i) {
ys[0].y = ys[1].y = a + b * i;
ys[0].ty = 1;
ys[1].ty = 0;
ys += 2;
}
xs->x = m_targetRect.right();
xs->tx = textureRect.x() + (m_sourceRect.right() - ceilRight + 1) * textureRect.width();
ys->y = m_targetRect.bottom();
ys->ty = textureRect.y() + (m_sourceRect.bottom() - ceilBottom + 1) * textureRect.height();
QSGGeometry::TexturedPoint2D *vertices = m_geometry.vertexDataAsTexturedPoint2D();
ys = yData.data();
for (int j = 0; j < vCells; ++j, ys += 2) {
xs = xData.data();
for (int i = 0; i < hCells; ++i, xs += 2) {
vertices[0].x = vertices[2].x = xs[0].x;
vertices[0].tx = vertices[2].tx = xs[0].tx;
vertices[1].x = vertices[3].x = xs[1].x;
vertices[1].tx = vertices[3].tx = xs[1].tx;
vertices[0].y = vertices[1].y = ys[0].y;
vertices[0].ty = vertices[1].ty = ys[0].ty;
vertices[2].y = vertices[3].y = ys[1].y;
vertices[2].ty = vertices[3].ty = ys[1].ty;
vertices += 4;
}
}
quint16 *indices = m_geometry.indexDataAsUShort();
for (int i = 0; i < 4 * vCells * hCells; i += 4) {
*indices++ = i;
*indices++ = i + 2;
*indices++ = i + 3;
*indices++ = i + 3;
*indices++ = i + 1;
*indices++ = i;
}
} else {
QRectF sr(textureRect.x() + m_sourceRect.x() * textureRect.width(),
textureRect.y() + m_sourceRect.y() * textureRect.height(),
m_sourceRect.width() * textureRect.width(),
m_sourceRect.height() * textureRect.height());
m_geometry.allocate(4);
m_geometry.setDrawingMode(GL_TRIANGLE_STRIP);
QSGGeometry::updateTexturedRectGeometry(&m_geometry, m_targetRect, sr);
}
}
markDirty(DirtyGeometry);
m_dirtyGeometry = false;
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
int f();
int g();
// CHECK: @a = thread_local global i32 0
thread_local int a = f();
extern thread_local int b;
// CHECK: @c = global i32 0
int c = b;
// CHECK: @_ZL1d = internal thread_local global i32 0
static thread_local int d = g();
struct U { static thread_local int m; };
// CHECK: @_ZN1U1mE = thread_local global i32 0
thread_local int U::m = f();
template<typename T> struct V { static thread_local int m; };
template<typename T> thread_local int V<T>::m = g();
// CHECK: @e = global i32 0
int e = V<int>::m;
// CHECK: @_ZN1VIiE1mE = weak_odr thread_local global i32 0
// CHECK: @_ZZ1fvE1n = internal thread_local global i32 0
// CHECK: @_ZGVZ1fvE1n = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1s = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1s = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1t = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1t = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1u = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1u = internal thread_local global i8 0
// CHECK: @_ZGRZ8tls_dtorvE1u = internal thread_local global
// CHECK: @_ZGVN1VIiE1mE = weak_odr thread_local global i64 0
// CHECK: @__tls_guard = internal thread_local global i8 0
// CHECK: @llvm.global_ctors = appending global {{.*}} @[[GLOBAL_INIT:[^ ]*]]
// CHECK: @_ZTH1a = alias void ()* @__tls_init
// CHECK: @_ZTHL1d = alias internal void ()* @__tls_init
// CHECK: @_ZTHN1U1mE = alias void ()* @__tls_init
// CHECK: @_ZTHN1VIiE1mE = alias weak_odr void ()* @__tls_init
// Individual variable initialization functions:
// CHECK: define {{.*}} @[[A_INIT:.*]]()
// CHECK: call i32 @_Z1fv()
// CHECK-NEXT: store i32 {{.*}}, i32* @a, align 4
// CHECK: define i32 @_Z1fv()
int f() {
// CHECK: %[[GUARD:.*]] = load i8* @_ZGVZ1fvE1n, align 1
// CHECK: %[[NEED_INIT:.*]] = icmp eq i8 %[[GUARD]], 0
// CHECK: br i1 %[[NEED_INIT]]
// CHECK: %[[CALL:.*]] = call i32 @_Z1gv()
// CHECK: store i32 %[[CALL]], i32* @_ZZ1fvE1n, align 4
// CHECK: store i8 1, i8* @_ZGVZ1fvE1n
// CHECK: br label
static thread_local int n = g();
// CHECK: load i32* @_ZZ1fvE1n, align 4
return n;
}
// CHECK: define {{.*}} @[[C_INIT:.*]]()
// CHECK: call i32* @_ZTW1b()
// CHECK-NEXT: load i32* %{{.*}}, align 4
// CHECK-NEXT: store i32 %{{.*}}, i32* @c, align 4
// CHECK: define weak_odr hidden i32* @_ZTW1b()
// CHECK: br i1 icmp ne (void ()* @_ZTH1b, void ()* null),
// not null:
// CHECK: call void @_ZTH1b()
// CHECK: br label
// finally:
// CHECK: ret i32* @b
// CHECK: define {{.*}} @[[D_INIT:.*]]()
// CHECK: call i32 @_Z1gv()
// CHECK-NEXT: store i32 %{{.*}}, i32* @_ZL1d, align 4
// CHECK: define {{.*}} @[[U_M_INIT:.*]]()
// CHECK: call i32 @_Z1fv()
// CHECK-NEXT: store i32 %{{.*}}, i32* @_ZN1U1mE, align 4
// CHECK: define {{.*}} @[[E_INIT:.*]]()
// CHECK: call i32* @_ZTWN1VIiE1mE()
// CHECK-NEXT: load i32* %{{.*}}, align 4
// CHECK-NEXT: store i32 %{{.*}}, i32* @e, align 4
// CHECK: define weak_odr hidden i32* @_ZTWN1VIiE1mE()
// CHECK: call void @_ZTHN1VIiE1mE()
// CHECK: ret i32* @_ZN1VIiE1mE
struct S { S(); ~S(); };
struct T { ~T(); };
// CHECK: define void @_Z8tls_dtorv()
void tls_dtor() {
// CHECK: load i8* @_ZGVZ8tls_dtorvE1s
// CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZZ8tls_dtorvE1s)
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZZ8tls_dtorvE1s{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1s
static thread_local S s;
// CHECK: load i8* @_ZGVZ8tls_dtorvE1t
// CHECK-NOT: _ZN1T
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1TD1Ev {{.*}}@_ZZ8tls_dtorvE1t{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1t
static thread_local T t;
// CHECK: load i8* @_ZGVZ8tls_dtorvE1u
// CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZGRZ8tls_dtorvE1u)
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZGRZ8tls_dtorvE1u{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1u
static thread_local const S &u = S();
}
// CHECK: declare i32 @__cxa_thread_atexit(void (i8*)*, i8*, i8*)
// CHECK: define {{.*}} @[[V_M_INIT:.*]]()
// CHECK: load i8* bitcast (i64* @_ZGVN1VIiE1mE to i8*)
// CHECK: %[[V_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0
// CHECK: br i1 %[[V_M_INITIALIZED]],
// need init:
// CHECK: call i32 @_Z1gv()
// CHECK: store i32 %{{.*}}, i32* @_ZN1VIiE1mE, align 4
// CHECK: store i64 1, i64* @_ZGVN1VIiE1mE
// CHECK: br label
// CHECK: define {{.*}}@[[GLOBAL_INIT:.*]]()
// CHECK: call void @[[C_INIT]]()
// CHECK: call void @[[E_INIT]]()
// CHECK: define {{.*}}@__tls_init()
// CHECK: load i8* @__tls_guard
// CHECK: %[[NEED_TLS_INIT:.*]] = icmp eq i8 %{{.*}}, 0
// CHECK: store i8 1, i8* @__tls_guard
// CHECK: br i1 %[[NEED_TLS_INIT]],
// init:
// CHECK: call void @[[A_INIT]]()
// CHECK: call void @[[D_INIT]]()
// CHECK: call void @[[U_M_INIT]]()
// CHECK: call void @[[V_M_INIT]]()
// CHECK: define weak_odr hidden i32* @_ZTW1a() {
// CHECK: call void @_ZTH1a()
// CHECK: ret i32* @a
// CHECK: }
// CHECK: declare extern_weak void @_ZTH1b()
// CHECK: define internal hidden i32* @_ZTWL1d()
// CHECK: call void @_ZTHL1d()
// CHECK: ret i32* @_ZL1d
// CHECK: define weak_odr hidden i32* @_ZTWN1U1mE()
// CHECK: call void @_ZTHN1U1mE()
// CHECK: ret i32* @_ZN1U1mE
<commit_msg>Add testcase omitted from r181998.<commit_after>// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s
int f();
int g();
// CHECK: @a = thread_local global i32 0
thread_local int a = f();
extern thread_local int b;
// CHECK: @c = global i32 0
int c = b;
// CHECK: @_ZL1d = internal thread_local global i32 0
static thread_local int d = g();
struct U { static thread_local int m; };
// CHECK: @_ZN1U1mE = thread_local global i32 0
thread_local int U::m = f();
template<typename T> struct V { static thread_local int m; };
template<typename T> thread_local int V<T>::m = g();
// CHECK: @e = global i32 0
int e = V<int>::m;
// CHECK: @_ZN1VIiE1mE = weak_odr thread_local global i32 0
// CHECK: @_ZZ1fvE1n = internal thread_local global i32 0
// CHECK: @_ZGVZ1fvE1n = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1s = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1s = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1t = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1t = internal thread_local global i8 0
// CHECK: @_ZZ8tls_dtorvE1u = internal thread_local global
// CHECK: @_ZGVZ8tls_dtorvE1u = internal thread_local global i8 0
// CHECK: @_ZGRZ8tls_dtorvE1u = internal thread_local global
// CHECK: @_ZGVN1VIiE1mE = weak_odr thread_local global i64 0
// CHECK: @__tls_guard = internal thread_local global i8 0
// CHECK: @llvm.global_ctors = appending global {{.*}} @[[GLOBAL_INIT:[^ ]*]]
// CHECK: @_ZTH1a = alias void ()* @__tls_init
// CHECK: @_ZTHL1d = alias internal void ()* @__tls_init
// CHECK: @_ZTHN1U1mE = alias void ()* @__tls_init
// CHECK: @_ZTHN1VIiE1mE = alias weak_odr void ()* @__tls_init
// Individual variable initialization functions:
// CHECK: define {{.*}} @[[A_INIT:.*]]()
// CHECK: call i32 @_Z1fv()
// CHECK-NEXT: store i32 {{.*}}, i32* @a, align 4
// CHECK: define i32 @_Z1fv()
int f() {
// CHECK: %[[GUARD:.*]] = load i8* @_ZGVZ1fvE1n, align 1
// CHECK: %[[NEED_INIT:.*]] = icmp eq i8 %[[GUARD]], 0
// CHECK: br i1 %[[NEED_INIT]]
// CHECK: %[[CALL:.*]] = call i32 @_Z1gv()
// CHECK: store i32 %[[CALL]], i32* @_ZZ1fvE1n, align 4
// CHECK: store i8 1, i8* @_ZGVZ1fvE1n
// CHECK: br label
static thread_local int n = g();
// CHECK: load i32* @_ZZ1fvE1n, align 4
return n;
}
// CHECK: define {{.*}} @[[C_INIT:.*]]()
// CHECK: call i32* @_ZTW1b()
// CHECK-NEXT: load i32* %{{.*}}, align 4
// CHECK-NEXT: store i32 %{{.*}}, i32* @c, align 4
// CHECK: define weak_odr hidden i32* @_ZTW1b()
// CHECK: br i1 icmp ne (void ()* @_ZTH1b, void ()* null),
// not null:
// CHECK: call void @_ZTH1b()
// CHECK: br label
// finally:
// CHECK: ret i32* @b
// CHECK: define {{.*}} @[[D_INIT:.*]]()
// CHECK: call i32 @_Z1gv()
// CHECK-NEXT: store i32 %{{.*}}, i32* @_ZL1d, align 4
// CHECK: define {{.*}} @[[U_M_INIT:.*]]()
// CHECK: call i32 @_Z1fv()
// CHECK-NEXT: store i32 %{{.*}}, i32* @_ZN1U1mE, align 4
// CHECK: define {{.*}} @[[E_INIT:.*]]()
// CHECK: call i32* @_ZTWN1VIiE1mE()
// CHECK-NEXT: load i32* %{{.*}}, align 4
// CHECK-NEXT: store i32 %{{.*}}, i32* @e, align 4
// CHECK: define weak_odr hidden i32* @_ZTWN1VIiE1mE()
// CHECK: call void @_ZTHN1VIiE1mE()
// CHECK: ret i32* @_ZN1VIiE1mE
struct S { S(); ~S(); };
struct T { ~T(); };
// CHECK: define void @_Z8tls_dtorv()
void tls_dtor() {
// CHECK: load i8* @_ZGVZ8tls_dtorvE1s
// CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZZ8tls_dtorvE1s)
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZZ8tls_dtorvE1s{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1s
static thread_local S s;
// CHECK: load i8* @_ZGVZ8tls_dtorvE1t
// CHECK-NOT: _ZN1T
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1TD1Ev {{.*}}@_ZZ8tls_dtorvE1t{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1t
static thread_local T t;
// CHECK: load i8* @_ZGVZ8tls_dtorvE1u
// CHECK: call void @_ZN1SC1Ev(%struct.S* @_ZGRZ8tls_dtorvE1u)
// CHECK: call i32 @__cxa_thread_atexit({{.*}}@_ZN1SD1Ev {{.*}} @_ZGRZ8tls_dtorvE1u{{.*}} @__dso_handle
// CHECK: store i8 1, i8* @_ZGVZ8tls_dtorvE1u
static thread_local const S &u = S();
}
// CHECK: declare i32 @__cxa_thread_atexit(void (i8*)*, i8*, i8*)
// CHECK: define {{.*}} @_Z7PR15991v(
int PR15991() {
thread_local int n;
auto l = [] { return n; };
return l();
}
// CHECK: define {{.*}} @[[V_M_INIT:.*]]()
// CHECK: load i8* bitcast (i64* @_ZGVN1VIiE1mE to i8*)
// CHECK: %[[V_M_INITIALIZED:.*]] = icmp eq i8 %{{.*}}, 0
// CHECK: br i1 %[[V_M_INITIALIZED]],
// need init:
// CHECK: call i32 @_Z1gv()
// CHECK: store i32 %{{.*}}, i32* @_ZN1VIiE1mE, align 4
// CHECK: store i64 1, i64* @_ZGVN1VIiE1mE
// CHECK: br label
// CHECK: define {{.*}}@[[GLOBAL_INIT:.*]]()
// CHECK: call void @[[C_INIT]]()
// CHECK: call void @[[E_INIT]]()
// CHECK: define {{.*}}@__tls_init()
// CHECK: load i8* @__tls_guard
// CHECK: %[[NEED_TLS_INIT:.*]] = icmp eq i8 %{{.*}}, 0
// CHECK: store i8 1, i8* @__tls_guard
// CHECK: br i1 %[[NEED_TLS_INIT]],
// init:
// CHECK: call void @[[A_INIT]]()
// CHECK: call void @[[D_INIT]]()
// CHECK: call void @[[U_M_INIT]]()
// CHECK: call void @[[V_M_INIT]]()
// CHECK: define weak_odr hidden i32* @_ZTW1a() {
// CHECK: call void @_ZTH1a()
// CHECK: ret i32* @a
// CHECK: }
// CHECK: declare extern_weak void @_ZTH1b()
// CHECK: define internal hidden i32* @_ZTWL1d()
// CHECK: call void @_ZTHL1d()
// CHECK: ret i32* @_ZL1d
// CHECK: define weak_odr hidden i32* @_ZTWN1U1mE()
// CHECK: call void @_ZTHN1U1mE()
// CHECK: ret i32* @_ZN1U1mE
<|endoftext|>
|
<commit_before>#include <glowutils/AdaptiveGrid.h>
#include <cmath>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glow/Program.h>
#include <glow/Shader.h>
#include <glow/Buffer.h>
#include <glow/VertexArrayObject.h>
#include <glow/VertexAttributeBinding.h>
#include <glow/StaticStringSource.h>
#include <glowutils/Plane3.h>
#include <glowutils/Camera.h>
#include <glowutils/StringTemplate.h>
using namespace glm;
using namespace glow;
namespace glowutils
{
const char * AdaptiveGrid::s_vsSource = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require
uniform mat4 transform;
uniform vec2 viewPlaneDistance;
layout (location = 0) in vec4 a_vertex;
flat out float v_type;
out vec3 v_vertex;
void main()
{
float m = 1.0 - viewPlaneDistance[1];
float t = a_vertex.w;
vec4 vertex = transform * vec4(a_vertex.xyz, 1.0);
v_vertex = vertex.xyz;
// interpolate minor grid lines alpha based on viewPlaneDistance
v_type = mix(1.0 - t, 1.0 - 2.0 * m * t, step(a_vertex.w, 0.7998));
gl_Position = vertex;
}
)";
const char * AdaptiveGrid::s_fsSource = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require
uniform vec2 viewPlaneDistance;
uniform float znear;
uniform float zfar;
uniform vec3 color;
flat in float v_type;
in vec3 v_vertex;
layout (location = 0) out vec4 fragColor;
void main()
{
float t = v_type;
float z = gl_FragCoord.z;
// complete function
// z = (2.0 * zfar * znear / (zfar + znear - (zfar - znear) * (2.0 * z - 1.0)));
// normalized to [0,1]
// z = (z - znear) / (zfar - znear);
// simplyfied with wolfram alpha
z = - znear * z / (zfar * z - zfar - znear * z);
float g = mix(t, 1.0, z * z);
float l = clamp(8.0 - length(v_vertex) / viewPlaneDistance[0], 0.0, 1.0);
fragColor = vec4(color, l * (1.0 - g * g));
}
)";
AdaptiveGrid::AdaptiveGrid(
unsigned short segments
, const vec3 & location
, const vec3 & normal)
: m_program(new Program())
, m_vao(nullptr)
, m_buffer(nullptr)
, m_camera(nullptr)
, m_location(location)
, m_normal(normal)
, m_size(0)
{
m_transform = transform(m_location, m_normal);
StringTemplate* vertexShaderString = new StringTemplate(new glow::StaticStringSource(s_vsSource));
StringTemplate* fragmentShaderString = new StringTemplate(new glow::StaticStringSource(s_fsSource));
#ifdef MAC_OS
vertexShaderString->replace("#version 140", "#version 150");
fragmentShaderString->replace("#version 140", "#version 150");
#endif
m_program->attach(new Shader(GL_VERTEX_SHADER, vertexShaderString),
new Shader(GL_FRAGMENT_SHADER, fragmentShaderString));
setColor(vec3(.8f));
setupGridLineBuffer(segments);
m_vao = new VertexArrayObject;
auto binding = m_vao->binding(0);
binding->setAttribute(0);
binding->setBuffer(m_buffer, 0, sizeof(vec4));
binding->setFormat(4, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(0);
}
AdaptiveGrid::~AdaptiveGrid()
{
}
void AdaptiveGrid::setupGridLineBuffer(unsigned short segments)
{
std::vector<vec4> points;
float type;
int n = 1;
const float g(static_cast<float>(segments));
type = .2f; // sub gridlines, every 0.125, except every 0.5
for (float f = -g + .125f; f < g; f += .125f)
{
if (n++ % 4)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
}
type = .4f; // grid lines every 1.0 units, offseted by 0.5
for (float f = -g + .5f; f < g; f += 1.f)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
type = .8f; // grid lines every 1.0 units
for (float f = -g + 1.f; f < g; f += 1.f)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
// use hesse normal form and transform each grid line onto the specified plane.
mat4 T; // ToDo;
for (vec4 & point : points)
point = vec4(vec3(T * vec4(point.x, point.y, point.z, 1.f)), point.w);
m_buffer = new Buffer(GL_ARRAY_BUFFER);
m_buffer->setData(points, GL_STATIC_DRAW);
m_size = static_cast<unsigned short>(segments * 64 - 4);
}
void AdaptiveGrid::setCamera(const Camera * camera)
{
m_camera = camera;
update();
}
void AdaptiveGrid::setNearFar(
float zNear
, float zFar)
{
m_program->setUniform("znear", zNear);
m_program->setUniform("zfar", zFar);
}
void AdaptiveGrid::setColor(const vec3 & color)
{
m_program->setUniform("color", color);
}
void AdaptiveGrid::update()
{
if (!m_camera)
return;
setNearFar(m_camera->zNear(), m_camera->zFar());
update(m_camera->eye(), m_camera->viewProjection());
}
void AdaptiveGrid::update(
const vec3 & viewpoint
, const mat4 & modelViewProjection)
{
// Project the camera's eye position onto the grid plane.
bool intersects; // should always intersect.
const vec3 i = intersection(intersects, m_location, m_normal
, viewpoint, viewpoint - m_normal);
// This transforms the horizontal plane vectors u and v onto the actual
// grid plane. Than express the intersection i as a linear combination of
// u and v by solving the linear equation system.
// Finally round the s and t values to get the nearest major grid point.
const float l = length(viewpoint - i);
const float distancelog = log(l * .5f) / log(8.f);
const float viewPlaneDistance = pow(8.f, ceil(distancelog));
mat4 T; // ToDo;
const vec3 u(vec3(T * vec4(viewPlaneDistance, 0.f, 0.f, 1.f)) - m_location);
const vec3 v(vec3(T * vec4(0.f, 0.f, viewPlaneDistance, 1.f)) - m_location);
const size_t j = (u[0] < 0.0f || u[0] > 0.0f) ? 0 : (u[1] < 0.0 || u[1] > 0.0) ? 1 : 2;
const size_t k = (v[0] < 0.0 || v[0] > 0.0) && j != 0 ? 0 : (v[1] < 0.0 || v[1] > 0.0) && j != 1 ? 1 : 2;
const vec3 a(i - m_location);
const float t = v[k] > 0.0 || v[k] < 0.0 ? a[k] / v[k] : 0.f;
const float s = u[j] > 0.0 || u[j] < 0.0 ? (a[j] - t * v[j]) / u[j] : 0.f;
const vec3 irounded = round(s) * u + round(t) * v;
const mat4 offset = translate(irounded) * scale(vec3(viewPlaneDistance));
m_program->setUniform("viewPlaneDistance", vec2(l, mod(distancelog, 1.f)));
m_program->setUniform("transform", modelViewProjection * offset);
}
void AdaptiveGrid::draw()
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
CheckGLError();
glEnable(GL_BLEND);
CheckGLError();
glEnable(GL_DEPTH_TEST);
CheckGLError();
m_program->use();
m_vao->bind();
m_vao->drawArrays(GL_LINES, 0, m_size);
m_vao->unbind();
m_program->release();
glDisable(GL_BLEND);
CheckGLError();
}
} // namespace glowutils
<commit_msg>Fix conversion error (on gcc 4.8.1)<commit_after>#include <glowutils/AdaptiveGrid.h>
#include <cmath>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glow/Program.h>
#include <glow/Shader.h>
#include <glow/Buffer.h>
#include <glow/VertexArrayObject.h>
#include <glow/VertexAttributeBinding.h>
#include <glow/StaticStringSource.h>
#include <glowutils/Plane3.h>
#include <glowutils/Camera.h>
#include <glowutils/StringTemplate.h>
using namespace glm;
using namespace glow;
namespace glowutils
{
const char * AdaptiveGrid::s_vsSource = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require
uniform mat4 transform;
uniform vec2 viewPlaneDistance;
layout (location = 0) in vec4 a_vertex;
flat out float v_type;
out vec3 v_vertex;
void main()
{
float m = 1.0 - viewPlaneDistance[1];
float t = a_vertex.w;
vec4 vertex = transform * vec4(a_vertex.xyz, 1.0);
v_vertex = vertex.xyz;
// interpolate minor grid lines alpha based on viewPlaneDistance
v_type = mix(1.0 - t, 1.0 - 2.0 * m * t, step(a_vertex.w, 0.7998));
gl_Position = vertex;
}
)";
const char * AdaptiveGrid::s_fsSource = R"(
#version 140
#extension GL_ARB_explicit_attrib_location : require
uniform vec2 viewPlaneDistance;
uniform float znear;
uniform float zfar;
uniform vec3 color;
flat in float v_type;
in vec3 v_vertex;
layout (location = 0) out vec4 fragColor;
void main()
{
float t = v_type;
float z = gl_FragCoord.z;
// complete function
// z = (2.0 * zfar * znear / (zfar + znear - (zfar - znear) * (2.0 * z - 1.0)));
// normalized to [0,1]
// z = (z - znear) / (zfar - znear);
// simplyfied with wolfram alpha
z = - znear * z / (zfar * z - zfar - znear * z);
float g = mix(t, 1.0, z * z);
float l = clamp(8.0 - length(v_vertex) / viewPlaneDistance[0], 0.0, 1.0);
fragColor = vec4(color, l * (1.0 - g * g));
}
)";
AdaptiveGrid::AdaptiveGrid(
unsigned short segments
, const vec3 & location
, const vec3 & normal)
: m_program(new Program())
, m_vao(nullptr)
, m_buffer(nullptr)
, m_camera(nullptr)
, m_location(location)
, m_normal(normal)
, m_size(0)
{
m_transform = transform(m_location, m_normal);
StringTemplate* vertexShaderString = new StringTemplate(new glow::StaticStringSource(s_vsSource));
StringTemplate* fragmentShaderString = new StringTemplate(new glow::StaticStringSource(s_fsSource));
#ifdef MAC_OS
vertexShaderString->replace("#version 140", "#version 150");
fragmentShaderString->replace("#version 140", "#version 150");
#endif
m_program->attach(new Shader(GL_VERTEX_SHADER, vertexShaderString),
new Shader(GL_FRAGMENT_SHADER, fragmentShaderString));
setColor(vec3(.8f));
setupGridLineBuffer(segments);
m_vao = new VertexArrayObject;
auto binding = m_vao->binding(0);
binding->setAttribute(0);
binding->setBuffer(m_buffer, 0, sizeof(vec4));
binding->setFormat(4, GL_FLOAT, GL_FALSE, 0);
m_vao->enable(0);
}
AdaptiveGrid::~AdaptiveGrid()
{
}
void AdaptiveGrid::setupGridLineBuffer(unsigned short segments)
{
std::vector<vec4> points;
float type;
int n = 1;
const float g(static_cast<float>(segments));
type = .2f; // sub gridlines, every 0.125, except every 0.5
for (float f = -g + .125f; f < g; f += .125f)
{
if (n++ % 4)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
}
type = .4f; // grid lines every 1.0 units, offseted by 0.5
for (float f = -g + .5f; f < g; f += 1.f)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
type = .8f; // grid lines every 1.0 units
for (float f = -g + 1.f; f < g; f += 1.f)
{
points.emplace_back(g, 0.f, f, type);
points.emplace_back(-g, 0.f, f, type);
points.emplace_back(f, 0.f, g, type);
points.emplace_back(f, 0.f,-g, type);
}
// use hesse normal form and transform each grid line onto the specified plane.
mat4 T; // ToDo;
for (vec4 & point : points)
point = vec4(vec3(T * vec4(point.x, point.y, point.z, 1.f)), point.w);
m_buffer = new Buffer(GL_ARRAY_BUFFER);
m_buffer->setData(points, GL_STATIC_DRAW);
m_size = static_cast<unsigned short>(segments * 64 - 4);
}
void AdaptiveGrid::setCamera(const Camera * camera)
{
m_camera = camera;
update();
}
void AdaptiveGrid::setNearFar(
float zNear
, float zFar)
{
m_program->setUniform("znear", zNear);
m_program->setUniform("zfar", zFar);
}
void AdaptiveGrid::setColor(const vec3 & color)
{
m_program->setUniform("color", color);
}
void AdaptiveGrid::update()
{
if (!m_camera)
return;
setNearFar(m_camera->zNear(), m_camera->zFar());
update(m_camera->eye(), m_camera->viewProjection());
}
void AdaptiveGrid::update(
const vec3 & viewpoint
, const mat4 & modelViewProjection)
{
// Project the camera's eye position onto the grid plane.
bool intersects; // should always intersect.
const vec3 i = intersection(intersects, m_location, m_normal
, viewpoint, viewpoint - m_normal);
// This transforms the horizontal plane vectors u and v onto the actual
// grid plane. Than express the intersection i as a linear combination of
// u and v by solving the linear equation system.
// Finally round the s and t values to get the nearest major grid point.
const float l = length(viewpoint - i);
const float distancelog = log(l * .5f) / log(8.f);
const float viewPlaneDistance = pow(8.f, ceil(distancelog));
mat4 T; // ToDo;
const vec3 u(vec3(T * vec4(viewPlaneDistance, 0.f, 0.f, 1.f)) - m_location);
const vec3 v(vec3(T * vec4(0.f, 0.f, viewPlaneDistance, 1.f)) - m_location);
const int j = (u[0] < 0.0f || u[0] > 0.0f) ? 0 : (u[1] < 0.0 || u[1] > 0.0) ? 1 : 2;
const int k = (v[0] < 0.0 || v[0] > 0.0) && j != 0 ? 0 : (v[1] < 0.0 || v[1] > 0.0) && j != 1 ? 1 : 2;
const vec3 a(i - m_location);
const float t = v[k] > 0.0 || v[k] < 0.0 ? a[k] / v[k] : 0.f;
const float s = u[j] > 0.0 || u[j] < 0.0 ? (a[j] - t * v[j]) / u[j] : 0.f;
const vec3 irounded = round(s) * u + round(t) * v;
const mat4 offset = translate(irounded) * scale(vec3(viewPlaneDistance));
m_program->setUniform("viewPlaneDistance", vec2(l, mod(distancelog, 1.f)));
m_program->setUniform("transform", modelViewProjection * offset);
}
void AdaptiveGrid::draw()
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
CheckGLError();
glEnable(GL_BLEND);
CheckGLError();
glEnable(GL_DEPTH_TEST);
CheckGLError();
m_program->use();
m_vao->bind();
m_vao->drawArrays(GL_LINES, 0, m_size);
m_vao->unbind();
m_program->release();
glDisable(GL_BLEND);
CheckGLError();
}
} // namespace glowutils
<|endoftext|>
|
<commit_before>#include <bits/stdc++.h>
using namespace std;
int main(){
int hrs,min,sec;
int time1,time2;
char c;
cout<<"Enter railway time in Format:\n h:m:s (eg:15:23:59)\n";
cout<<"Enter Time 1: ";
cin>>hrs>>c>>min>>c>>sec;
assert(hrs<25 && hrs>=0);
assert(min<61 && min>=0);
assert(sec<61 && sec>=0);
time1 = hrs*60*60 + min*60 + sec;
cout<<"Enter Time 2: ";
cin>>hrs>>c>>min>>c>>sec;
assert(hrs<25 && hrs>=0);
assert(min<61 && min>=0);
assert(sec<61 && sec>=0);
time2 = hrs*60*60 + min*60 + sec;
if(time1 == time2)
cout<<"Both the Times are Equal\n";
else if(time1 < time2)
cout<<"Time1 is minimum\n";
else
cout<<"Time2 is minimum\n";
return 0;
}<commit_msg>update compareTime.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
int main(){
int hrs,min,sec;
int time1,time2;
char c;
cout<<"Enter railway time in Format:\n h:m:s (eg:15:23:59)\n";
cout<<"Enter Time 1: ";
cin>>hrs>>c>>min>>c>>sec;
assert(hrs<24 && hrs>=0);
assert(min<61 && min>=0);
assert(sec<61 && sec>=0);
time1 = hrs*60*60 + min*60 + sec;
cout<<"Enter Time 2: ";
cin>>hrs>>c>>min>>c>>sec;
assert(hrs<24 && hrs>=0);
assert(min<61 && min>=0);
assert(sec<61 && sec>=0);
time2 = hrs*60*60 + min*60 + sec;
if(time1 == time2)
cout<<"Both the Times are Equal\n";
else if(time1 < time2)
cout<<"Time1 is minimum\n";
else
cout<<"Time2 is minimum\n";
return 0;
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Inria and University Pierre and Marie Curie
*/
/**
* \file mylibm.hpp
* \brief Provides a set of auxiliary functions to superaccumulation.
* For internal use
*
* \authors
* Developers : \n
* Roman Iakymchuk -- roman.iakymchuk@lip6.fr \n
* Sylvain Collange -- sylvain.collange@inria.fr \n
* Matthias Wiesenberger -- mattwi@fysik.dtu.dk
*/
#ifndef MYLIBM_HPP_INCLUDED
#define MYLIBM_HPP_INCLUDED
#include "config.h"
namespace exblas{
namespace cpu{
static inline int64_t myllrint(double x) {
#ifndef _WITHOUT_VCL
return _mm_cvtsd_si64(_mm_set_sd(x));
#else
return std::llrint(x);
#endif
}
static inline double myrint(double x)
{
#ifndef _WITHOUT_VCL
#if defined __GNUG__ || _MSC_VER
// Workaround gcc bug 51033
union {
__m128d v;
double d[2];
} r;
//_mm_round_sd(_mm_undefined_pd(), _mm_set_sd(x));
//__m128d undefined;
//r.v = _mm_round_sd(_mm_setzero_pd(), _mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
//r.v = _mm_round_sd(undefined, _mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
r.v = _mm_round_pd(_mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
return r.d[0];
#else
double r;
//asm("roundsd $0, %1, %0" : "=x" (r) : "x" (x));
asm(ASM_BEGIN "roundsd %0, %1, 0" ASM_END : "=x" (r) : "x" (x));
return r;
#endif
#else
return std::rint(x);
#endif//_WITHOUT_VCL
}
//inline double uint64_as_double(uint64_t i)
//{
// double d;
// asm("movsd %0, %1" : "=x" (d) : "g" (i) :);
// return d;
//}
static inline int exponent(double x)
{
// simpler frexp
union {
double d;
uint64_t i;
} caster;
caster.d = x;
uint64_t e = ((caster.i >> 52) & 0x7ff) - 0x3ff;
return e;
}
static inline int biased_exponent(double x)
{
union {
double d;
uint64_t i;
} caster;
caster.d = x;
uint64_t e = (caster.i >> 52) & 0x7ff;
return e;
}
static inline double myldexp(double x, int e)
{
// Scale x by e
union {
double d;
uint64_t i;
} caster;
caster.d = x;
caster.i += (uint64_t)e << 52;
return caster.d;
}
static inline double exp2i(int e)
{
// simpler ldexp
union {
double d;
uint64_t i;
} caster;
caster.i = (uint64_t)(e + 0x3ff) << 52;
return caster.d;
}
// Assumptions: th>tl>=0, no overlap between th and tl
static inline double OddRoundSumNonnegative(double th, double tl)
{
// Adapted from:
// Sylvie Boldo, and Guillaume Melquiond. "Emulation of a FMA and correctly rounded sums: proved algorithms using rounding to odd." IEEE Transactions on Computers, 57, no. 4 (2008): 462-471.
union {
double d;
int64_t l;
} thdb;
thdb.d = th + tl;
// - if the mantissa of th is odd, there is nothing to do
// - otherwise, round up as both tl and th are positive
// in both cases, this means setting the msb to 1 when tl>0
thdb.l |= (tl != 0.0);
return thdb.d;
}
#ifdef THREADSAFE
#define TSAFE 1
#define LOCK_PREFIX "lock "
#else
#define TSAFE 0
#define LOCK_PREFIX
#endif
// signedcarry in {-1, 0, 1}
inline static int64_t xadd(int64_t & memref, int64_t x, unsigned char & of)
{
#if defined _MSC_VER && !TSAFE //non-atomic load-ADDC-store
int64_t y = memref;
memref = y + x;
int64_t x63 = (x >> 63) & 1;
int64_t y63 = (y >> 63) & 1;
int64_t r63 = (memref >> 63) & 1;
int64_t c62 = r63 ^ x63 ^ y63;
int64_t c63 = (x63 & y63) | (c62 & (x63 | y63));
of = c63 ^ c62;
return y;
#else
// OF and SF -> carry=1
// OF and !SF -> carry=-1
// !OF -> carry=0
int64_t oldword = x;
#ifdef ATT_SYNTAX
asm volatile (LOCK_PREFIX"xaddq %1, %0\n"
"setob %2"
: "+m" (memref), "+r" (oldword), "=q" (of) : : "cc", "memory");
#else
asm volatile (LOCK_PREFIX"xadd %1, %0\n"
"seto %2"
: "+m" (memref), "+r" (oldword), "=q" (of) : : "cc", "memory");
#endif //ATT_SYNTAX
return oldword;
#endif //_MSC_VER
}
//static inline vcl::Vec8d clear_significand(vcl::Vec8d x) {
// return x & vcl::Vec8d(_mm512_castsi256_pd(_mm512_set1_epi64x(0xfff0000000000000ull)));
//}
//static inline double horizontal_max(vcl::Vec8d x) {
// vcl::Vec4d h = x.get_high();
// vcl::Vec4d l = x.get_low();
// vcl::Vec4d m1 = max(h, l);
// vcl::Vec4d m2 = vcl::permute4d<1, 0, 1, 0>(m1);
// vcl::Vec4d m = vcl::max(m1, m2);
// return m[0]; // Why is it so hard to convert from vector xmm register to scalar xmm register?
//}
//
//inline static void horizontal_twosum(vcl::Vec8d & r, vcl::Vec8d & s)
//{
// //r = KnuthTwoSum(r, s, s);
// transpose1(r, s);
// r = KnuthTwoSum(r, s, s);
// transpose2(r, s);
// r = KnuthTwoSum(r, s, s);
//}
//
//static inline bool sign_horizontal_or (vcl::Vec8db const & a) {
// //effectively tests if any element in a is non zero
// return vcl::horizontal_or( a);
// //return !_mm512_testz_pd(a,a);
//}
#ifndef _WITHOUT_VCL
inline static bool horizontal_or(vcl::Vec8d const & a) {
//return _mm512_movemask_pd(a) != 0;
vcl::Vec8db p = a != 0;
return vcl::horizontal_or( p);
//return !_mm512_testz_pd(p, p);
}
#else
inline static bool horizontal_or( const double & a){
return a!= 0;
}
#endif//_WITHOUT_VCL
}//namespace cpu
}//namespace exblas
#endif
<commit_msg>Add _WITHOUT_VCL to xadd manual code<commit_after>/*
* Copyright (c) 2016 Inria and University Pierre and Marie Curie
*/
/**
* \file mylibm.hpp
* \brief Provides a set of auxiliary functions to superaccumulation.
* For internal use
*
* \authors
* Developers : \n
* Roman Iakymchuk -- roman.iakymchuk@lip6.fr \n
* Sylvain Collange -- sylvain.collange@inria.fr \n
* Matthias Wiesenberger -- mattwi@fysik.dtu.dk
*/
#ifndef MYLIBM_HPP_INCLUDED
#define MYLIBM_HPP_INCLUDED
#include "config.h"
namespace exblas{
namespace cpu{
static inline int64_t myllrint(double x) {
#ifndef _WITHOUT_VCL
return _mm_cvtsd_si64(_mm_set_sd(x));
#else
return std::llrint(x);
#endif
}
static inline double myrint(double x)
{
#ifndef _WITHOUT_VCL
#if defined __GNUG__ || _MSC_VER
// Workaround gcc bug 51033
union {
__m128d v;
double d[2];
} r;
//_mm_round_sd(_mm_undefined_pd(), _mm_set_sd(x));
//__m128d undefined;
//r.v = _mm_round_sd(_mm_setzero_pd(), _mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
//r.v = _mm_round_sd(undefined, _mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
r.v = _mm_round_pd(_mm_set_sd(x), _MM_FROUND_TO_NEAREST_INT);
return r.d[0];
#else
double r;
//asm("roundsd $0, %1, %0" : "=x" (r) : "x" (x));
asm(ASM_BEGIN "roundsd %0, %1, 0" ASM_END : "=x" (r) : "x" (x));
return r;
#endif
#else
return std::rint(x);
#endif//_WITHOUT_VCL
}
//inline double uint64_as_double(uint64_t i)
//{
// double d;
// asm("movsd %0, %1" : "=x" (d) : "g" (i) :);
// return d;
//}
static inline int exponent(double x)
{
// simpler frexp
union {
double d;
uint64_t i;
} caster;
caster.d = x;
uint64_t e = ((caster.i >> 52) & 0x7ff) - 0x3ff;
return e;
}
static inline int biased_exponent(double x)
{
union {
double d;
uint64_t i;
} caster;
caster.d = x;
uint64_t e = (caster.i >> 52) & 0x7ff;
return e;
}
static inline double myldexp(double x, int e)
{
// Scale x by e
union {
double d;
uint64_t i;
} caster;
caster.d = x;
caster.i += (uint64_t)e << 52;
return caster.d;
}
static inline double exp2i(int e)
{
// simpler ldexp
union {
double d;
uint64_t i;
} caster;
caster.i = (uint64_t)(e + 0x3ff) << 52;
return caster.d;
}
// Assumptions: th>tl>=0, no overlap between th and tl
static inline double OddRoundSumNonnegative(double th, double tl)
{
// Adapted from:
// Sylvie Boldo, and Guillaume Melquiond. "Emulation of a FMA and correctly rounded sums: proved algorithms using rounding to odd." IEEE Transactions on Computers, 57, no. 4 (2008): 462-471.
union {
double d;
int64_t l;
} thdb;
thdb.d = th + tl;
// - if the mantissa of th is odd, there is nothing to do
// - otherwise, round up as both tl and th are positive
// in both cases, this means setting the msb to 1 when tl>0
thdb.l |= (tl != 0.0);
return thdb.d;
}
#ifdef THREADSAFE //MW: we don't define this anywhere?
#define TSAFE 1
#define LOCK_PREFIX "lock "
#else
#define TSAFE 0 //MW: so I guess it's always 0 i.e. false
#define LOCK_PREFIX
#endif
// signedcarry in {-1, 0, 1}
inline static int64_t xadd(int64_t & memref, int64_t x, unsigned char & of)
{
//msvc doesn't allow inline assembler code
//If we don't have VCL, then sometimes the assembler code also makes problems
#if defined (_WITHOUT_VCL || _MSC_VER) && !TSAFE
//manually compute non-atomic load-ADDC-store
int64_t y = memref;
memref = y + x;
int64_t x63 = (x >> 63) & 1;
int64_t y63 = (y >> 63) & 1;
int64_t r63 = (memref >> 63) & 1;
int64_t c62 = r63 ^ x63 ^ y63;
int64_t c63 = (x63 & y63) | (c62 & (x63 | y63));
of = c63 ^ c62;
return y;
#else
// OF and SF -> carry=1
// OF and !SF -> carry=-1
// !OF -> carry=0
int64_t oldword = x;
#ifdef ATT_SYNTAX
asm volatile (LOCK_PREFIX"xaddq %1, %0\n"
"setob %2"
: "+m" (memref), "+r" (oldword), "=q" (of) : : "cc", "memory");
#else
asm volatile (LOCK_PREFIX"xadd %1, %0\n"
"seto %2"
: "+m" (memref), "+r" (oldword), "=q" (of) : : "cc", "memory");
#endif //ATT_SYNTAX
return oldword;
#endif //_MSC_VER
}
//static inline vcl::Vec8d clear_significand(vcl::Vec8d x) {
// return x & vcl::Vec8d(_mm512_castsi256_pd(_mm512_set1_epi64x(0xfff0000000000000ull)));
//}
//static inline double horizontal_max(vcl::Vec8d x) {
// vcl::Vec4d h = x.get_high();
// vcl::Vec4d l = x.get_low();
// vcl::Vec4d m1 = max(h, l);
// vcl::Vec4d m2 = vcl::permute4d<1, 0, 1, 0>(m1);
// vcl::Vec4d m = vcl::max(m1, m2);
// return m[0]; // Why is it so hard to convert from vector xmm register to scalar xmm register?
//}
//
//inline static void horizontal_twosum(vcl::Vec8d & r, vcl::Vec8d & s)
//{
// //r = KnuthTwoSum(r, s, s);
// transpose1(r, s);
// r = KnuthTwoSum(r, s, s);
// transpose2(r, s);
// r = KnuthTwoSum(r, s, s);
//}
//
//static inline bool sign_horizontal_or (vcl::Vec8db const & a) {
// //effectively tests if any element in a is non zero
// return vcl::horizontal_or( a);
// //return !_mm512_testz_pd(a,a);
//}
#ifndef _WITHOUT_VCL
inline static bool horizontal_or(vcl::Vec8d const & a) {
//return _mm512_movemask_pd(a) != 0;
vcl::Vec8db p = a != 0;
return vcl::horizontal_or( p);
//return !_mm512_testz_pd(p, p);
}
#else
inline static bool horizontal_or( const double & a){
return a!= 0;
}
#endif//_WITHOUT_VCL
}//namespace cpu
}//namespace exblas
#endif
<|endoftext|>
|
<commit_before>//////////////////////////////////
//
// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5 -lboost_timer
//
//////////////////////////////////
#include <iostream> // std::cout
#include <fstream> // std::ifsteam
#include <utility> // std::pair
#include <vector> // std::vector
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/timer/timer.hpp>
int main(int argc, char*argv[]){
if (argc != 2)
{
std::cerr << "No file!!!" << std::endl;
return -1;
}
std::ifstream file(argv[1]); // std::ifstream::in ??
std::string str;
boost::timer::cpu_timer timer;
/* start get number of edges */
getline(file, str);
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::parse;
int n;
auto it = str.begin();
bool r = parse(it, str.end(),
int_[([&n](int i){n = i;})] >> int_);
/* end get number of edges */
/* start get list of edges and weights */
typedef std::pair<int, int> Edge;
std::vector<Edge> Edges; // vector to store std::pair of edges.
std::vector<int> Weights; // vector to weights as integers.
while (getline(file,str)){ // get graph line-by-line.
int Vert1;
int Vert2;
double Weight; // are all weights integer-valued ??
auto it = str.begin(); // initialize iterator for qi::parse.
bool r = parse(it, str.end(), // parse graph.
int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);
Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.
Edges.push_back(edge);
Weights.push_back(Weight);
}
/* end get list of edges and weights */
typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty; // initialize type to store weights on edges.
// adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph; // create graph.
Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.
// here, the graph should be built... Find shortest path.
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.
std::vector<vertex_descriptor> parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.
std::vector<int> distances(boost::num_vertices(g));
// find shortest distances.
boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));
/* start find longest-shortest path */
int maxDistance = 0;
int maxVertex = 0;
// create iterator over vertices.
// vertexPair.first is the iterated element, and .second is the end-index of all vertices.
typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vertexPair;
for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.
{
// replace maxDistance if a greater distance is found, and maxDistance must be less than "infinity" (of 32-bit signed integer).
if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
// if distance == maxDistance, check if vertex index is smaller.
if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){
maxDistance = distances[*vertexPair.first];
}
}
boost::timer::cpu_times times = timer.elapsed();
// output vertex and distance of the longest-shortest path.
std::cout << "RESULT VERTEX " << maxVertex << std::endl;
std::cout << "RESULT DIST " << maxDistance << std::endl;
/* end find longest-shortest path */
// print CPU- and Wall-Time.
// boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.
std::cout << std::endl;
std::cout << "WALL-CLOCK " << times.wall / 1e9 << "s" << std::endl;
std::cout << "USER TIME " << times.user / 1e9 << "s" << std::endl;
file.close();
return 0;
}
<commit_msg>fixed typo in ex5.cxx<commit_after>//////////////////////////////////
//
// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5 -lboost_timer
//
//////////////////////////////////
#include <iostream> // std::cout
#include <fstream> // std::ifsteam
#include <utility> // std::pair
#include <vector> // std::vector
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/timer/timer.hpp>
int main(int argc, char*argv[]){
if (argc != 2)
{
std::cerr << "No file!!!" << std::endl;
return -1;
}
std::ifstream file(argv[1]); // std::ifstream::in ??
std::string str;
boost::timer::cpu_timer timer;
/* start get number of edges */
getline(file, str);
using namespace boost::spirit;
using qi::int_;
using qi::double_;
using qi::parse;
int n;
auto it = str.begin();
bool r = parse(it, str.end(),
int_[([&n](int i){n = i;})] >> int_);
/* end get number of edges */
/* start get list of edges and weights */
typedef std::pair<int, int> Edge;
std::vector<Edge> Edges; // vector to store std::pair of edges.
std::vector<int> Weights; // vector to weights as integers.
while (getline(file,str)){ // get graph line-by-line.
int Vert1;
int Vert2;
double Weight; // are all weights integer-valued ??
auto it = str.begin(); // initialize iterator for qi::parse.
bool r = parse(it, str.end(), // parse graph.
int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]);
Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.
Edges.push_back(edge);
Weights.push_back(Weight);
}
/* end get list of edges and weights */
typedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty; // initialize type to store weights on edges.
// adjacency_list<out-edges, vertex_set, directedness, vertex properties, edge properties>
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty> Graph; // create graph.
Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.
// here, the graph should be built... Find shortest path.
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.
std::vector<vertex_descriptor> parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.
std::vector<int> distances(boost::num_vertices(g));
// find shortest distances.
boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));
/* start find longest-shortest path */
int maxDistance = 0;
int maxVertex = 0;
// create iterator over vertices.
// vertexPair.first is the iterated element, and .second is the end-index of all vertices.
typedef boost::graph_traits <Graph>::vertex_iterator vertex_iter;
std::pair<vertex_iter, vertex_iter> vertexPair;
for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.
{
// replace maxDistance if a greater distance is found, and maxDistance must be less than "infinity" (of 32-bit signed integer).
if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){
maxDistance = distances[*vertexPair.first];
maxVertex = *vertexPair.first;
}
// if distance == maxDistance, check if vertex index is smaller.
if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){
maxVertex = *vertexPair.first;
}
}
boost::timer::cpu_times times = timer.elapsed();
// output vertex and distance of the longest-shortest path.
std::cout << "RESULT VERTEX " << maxVertex << std::endl;
std::cout << "RESULT DIST " << maxDistance << std::endl;
/* end find longest-shortest path */
// print CPU- and Wall-Time.
// boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.
std::cout << std::endl;
std::cout << "WALL-CLOCK " << times.wall / 1e9 << "s" << std::endl;
std::cout << "USER TIME " << times.user / 1e9 << "s" << std::endl;
file.close();
return 0;
}
<|endoftext|>
|
<commit_before>#include "testdriver_comparator.h"
// used for Canonical XML
#define LIBXML_C14N_ENABLED
#define LIBXML_OUTPUT_ENABLED
#include <libxml/c14n.h>
#include <libxml/tree.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
namespace zorba {
/*******************************************************************************
********************************************************************************/
int
canonicalizeAndCompare(const std::string& aComparisonMethod,
const char* aRefFile,
const char* aResultFile,
const std::string& aRBKTBinDir)
{
xmlDocPtr lRefResult_ptr;
xmlDocPtr lResult_ptr;
LIBXML_TEST_VERSION
if (aComparisonMethod.compare("XML") == 0)
{
lRefResult_ptr = xmlReadFile(aRefFile, 0, 0);
lResult_ptr = xmlReadFile(aResultFile, 0, 0);
}
else if (aComparisonMethod.compare("Text") == 0 ||
aComparisonMethod.compare("Fragment") == 0)
{
// prepend and append an artifical root tag as requested by the guidelines
std::ostringstream lTmpRefResult;
lTmpRefResult << "<root>" << std::endl;
std::ifstream lRefInStream(aRefFile);
if (!lRefInStream.good())
{
std::cout << "Failed to open ref file " << aRefFile << std::endl;
return 8;
}
std::cout << "reading from file " << aRefFile << std::endl;
char buf[1024];
while (!lRefInStream.eof())
{
lRefInStream.read(buf, 1024);
lTmpRefResult.write(buf, lRefInStream.gcount());
}
if (buf[lRefInStream.gcount()-1] != '\n')
lTmpRefResult << std::endl;
lTmpRefResult << "</root>";
lRefResult_ptr = xmlReadMemory(lTmpRefResult.str().c_str(), lTmpRefResult.str().size(), "ref_result.xml", 0, 0);
// prepend and append an artifical root tag as requested by the guidelines
std::ostringstream lTmpResult;
lTmpResult << "<root>" << std::endl;
std::ifstream lInStream(aResultFile);
if (!lInStream.good())
{
std::cout << "Failed to open result file " << aResultFile << std::endl;
return 8;
}
std::cout << "reading from file " << aResultFile << std::endl;
while (!lInStream.eof())
{
lInStream.read(buf, 1024);
lTmpResult.write(buf, lInStream.gcount());
}
lTmpResult << std::endl << "</root>";
lResult_ptr = xmlReadMemory(lTmpResult.str().c_str(), lTmpResult.str().size(), "result.xml", 0, 0);
}
else if (aComparisonMethod.compare("Error") == 0 )
{
std::cout << "an error was expected but we got a result" << std::endl;
return 8;
}
else if (aComparisonMethod.compare("Inspect") == 0 )
{
std::cout << "result must be inspected by humans." << std::endl;
return 0;
}
else if (aComparisonMethod.compare("Ignore") == 0 )
{
// safely return no error here
return 0;
}
else
{
std::cout << "comparison method not supported: " << aComparisonMethod << std::endl;
return 9;
}
if (lRefResult_ptr == NULL || lResult_ptr == NULL)
{
std::cerr << "couldn't read reference result or result file" << std::endl;
return 8;
}
std::string lCanonicalRefFile = aRBKTBinDir + "/canonical_ref.xml";
std::string lCanonicalResFile = aRBKTBinDir + "/canonical_res.xml";
int lRefResultRes = xmlC14NDocSave(lRefResult_ptr, 0, 0, NULL, 0, lCanonicalRefFile.c_str(), 0);
int lResultRes = xmlC14NDocSave(lResult_ptr, 0, 0, NULL, 0, lCanonicalResFile.c_str(), 0);
xmlFreeDoc(lRefResult_ptr);
xmlFreeDoc(lResult_ptr);
if (lRefResultRes < 0)
{
std::cerr << "error canonicalizing reference result" << std::endl;
return 10;
}
if (lResultRes < 0)
{
std::cerr << "error canonicalizing result" << std::endl;
return 10;
}
// last, we have to diff the result
int lLine, lCol, lPos; // where do the files differ
std::string lRefLine, lResultLine;
bool lRes = fileEquals(lCanonicalRefFile.c_str(),
lCanonicalResFile.c_str(),
lLine, lCol, lPos, lRefLine, lResultLine);
if (!lRes)
{
std::cout << std::endl
<< "Canonical result does not match canonical expected result:"
<< std::endl;
printFile(std::cout, aRefFile);
std::cout << "=== end of expected result ===" << std::endl;
std::cout << "See line " << lLine << ", col " << lCol
<< " of expected result. " << std::endl;
std::cout << "Actual: <";
if( -1 != lPos )
printPart(std::cout, aResultFile, lPos, 15);
else
std::cout << lResultLine;
std::cout << ">" << std::endl;
std::cout << "Expected: <";
if( -1 != lPos )
printPart(std::cout, aRefFile, lPos, 15);
else
std::cout << lRefLine;
std::cout << ">" << std::endl;
return 8;
}
return 0;
}
/*******************************************************************************
Return false if the files are not equal.
aLine contains the line number in which the first difference occurs
aCol contains the column number in which the first difference occurs
aPos is the character number off the first difference in the file
-1 is returned for aLine, aCol, and aPos if the files are equal
********************************************************************************/
bool
fileEquals(
const char* aRefFile,
const char* aResFile,
int& aLine,
int& aCol,
int& aPos,
std::string& aRefLine,
std::string& aResLine)
{
std::ifstream li(aRefFile);
std::ifstream ri(aResFile);
std::string lLine, rLine;
if (!li.good())
{
std::cout << "Failed to open ref file " << aRefFile << std::endl;
return false;
}
if (!ri.good())
{
std::cout << "Failed to open results file " << aResFile << std::endl;
return false;
}
aLine = 1; aCol = 0; aPos = -1;
while (! li.eof() )
{
if ( ri.eof() )
{
std::getline(li, lLine);
if (li.peek() == -1) // ignore end-of-line in the ref result
return true;
else
return false;
}
std::getline(li, lLine);
std::getline(ri, rLine);
// TODO: should be removed, right?
trim ( lLine );
trim ( rLine );
if ( (aCol = lLine.compare(rLine)) != 0)
{
aRefLine = lLine;
aResLine = rLine;
return false;
}
++aLine;
}
return true;
}
/*******************************************************************************
Print parts of a file starting at aStartPos with the length of aLen
********************************************************************************/
void
printPart(std::ostream& os, const std::string &aInFile, int aStartPos, int aLen)
{
char* buffer = new char [aLen];
try {
std::ifstream lIn(aInFile.c_str());
lIn.seekg(aStartPos);
#ifdef WIN32
int lCharsRead = lIn._Readsome_s (buffer, aLen, aLen);
#else
int lCharsRead = lIn.readsome (buffer, aLen);
#endif
os.write (buffer, lCharsRead);
os.flush();
delete[] buffer;
} catch (...)
{
delete[] buffer;
}
return;
}
/*******************************************************************************
********************************************************************************/
void
printFile(std::ostream& os, const std::string &aInFile)
{
std::ifstream lInFileStream(aInFile.c_str());
assert(lInFileStream.good());
char buf[1024];
while (!lInFileStream.eof()) {
lInFileStream.read(buf, 1024);
os.write(buf, lInFileStream.gcount());
}
os << std::endl;
}
void
trim(std::string& str)
{
std::string::size_type notwhite = str.find_first_not_of(" \r\t\n");
str.erase(0,notwhite);
notwhite = str.find_last_not_of(" \t\n\r");
str.erase(notwhite+1);
}
} /* namespace zorba */
<commit_msg>ignore xml declaration in ref files<commit_after>#include "testdriver_comparator.h"
// used for Canonical XML
#define LIBXML_C14N_ENABLED
#define LIBXML_OUTPUT_ENABLED
#include <libxml/c14n.h>
#include <libxml/tree.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
namespace zorba {
/*******************************************************************************
********************************************************************************/
int
canonicalizeAndCompare(const std::string& aComparisonMethod,
const char* aRefFile,
const char* aResultFile,
const std::string& aRBKTBinDir)
{
xmlDocPtr lRefResult_ptr;
xmlDocPtr lResult_ptr;
LIBXML_TEST_VERSION
if (aComparisonMethod.compare("XML") == 0)
{
lRefResult_ptr = xmlReadFile(aRefFile, 0, 0);
lResult_ptr = xmlReadFile(aResultFile, 0, 0);
}
else if (aComparisonMethod.compare("Text") == 0 ||
aComparisonMethod.compare("Fragment") == 0)
{
// prepend and append an artifical root tag as requested by the guidelines
std::ostringstream lTmpRefResult;
lTmpRefResult << "<root>" << std::endl;
std::ifstream lRefInStream(aRefFile);
if (!lRefInStream.good())
{
std::cout << "Failed to open ref file " << aRefFile << std::endl;
return 8;
}
std::cout << "reading from file " << aRefFile << std::endl;
char buf[1024];
while (!lRefInStream.eof())
{
lRefInStream.read(buf, 1024);
lTmpRefResult.write(buf, lRefInStream.gcount());
}
if (buf[lRefInStream.gcount()-1] != '\n')
lTmpRefResult << std::endl;
lTmpRefResult << "</root>";
lRefResult_ptr = xmlReadMemory(lTmpRefResult.str().c_str(), lTmpRefResult.str().size(), "ref_result.xml", 0, 0);
// prepend and append an artifical root tag as requested by the guidelines
std::ostringstream lTmpResult;
lTmpResult << "<root>" << std::endl;
std::ifstream lInStream(aResultFile);
if (!lInStream.good())
{
std::cout << "Failed to open result file " << aResultFile << std::endl;
return 8;
}
std::cout << "reading from file " << aResultFile << std::endl;
while (!lInStream.eof())
{
lInStream.read(buf, 1024);
lTmpResult.write(buf, lInStream.gcount());
}
lTmpResult << std::endl << "</root>";
lResult_ptr = xmlReadMemory(lTmpResult.str().c_str(), lTmpResult.str().size(), "result.xml", 0, 0);
}
else if (aComparisonMethod.compare("Error") == 0 )
{
std::cout << "an error was expected but we got a result" << std::endl;
return 8;
}
else if (aComparisonMethod.compare("Inspect") == 0 )
{
std::cout << "result must be inspected by humans." << std::endl;
return 0;
}
else if (aComparisonMethod.compare("Ignore") == 0 )
{
// safely return no error here
return 0;
}
else
{
std::cout << "comparison method not supported: " << aComparisonMethod << std::endl;
return 9;
}
if (lRefResult_ptr == NULL || lResult_ptr == NULL)
{
std::cerr << "couldn't read reference result or result file" << std::endl;
return 8;
}
std::string lCanonicalRefFile = aRBKTBinDir + "/canonical_ref.xml";
std::string lCanonicalResFile = aRBKTBinDir + "/canonical_res.xml";
int lRefResultRes = xmlC14NDocSave(lRefResult_ptr, 0, 0, NULL, 0, lCanonicalRefFile.c_str(), 0);
int lResultRes = xmlC14NDocSave(lResult_ptr, 0, 0, NULL, 0, lCanonicalResFile.c_str(), 0);
xmlFreeDoc(lRefResult_ptr);
xmlFreeDoc(lResult_ptr);
if (lRefResultRes < 0)
{
std::cerr << "error canonicalizing reference result" << std::endl;
return 10;
}
if (lResultRes < 0)
{
std::cerr << "error canonicalizing result" << std::endl;
return 10;
}
// last, we have to diff the result
int lLine, lCol, lPos; // where do the files differ
std::string lRefLine, lResultLine;
bool lRes = fileEquals(lCanonicalRefFile.c_str(),
lCanonicalResFile.c_str(),
lLine, lCol, lPos, lRefLine, lResultLine);
if (!lRes)
{
std::cout << std::endl
<< "Canonical result does not match canonical expected result:"
<< std::endl;
printFile(std::cout, aRefFile);
std::cout << "=== end of expected result ===" << std::endl;
std::cout << "See line " << lLine << ", col " << lCol
<< " of expected result. " << std::endl;
std::cout << "Actual: <";
if( -1 != lPos )
printPart(std::cout, aResultFile, lPos, 15);
else
std::cout << lResultLine;
std::cout << ">" << std::endl;
std::cout << "Expected: <";
if( -1 != lPos )
printPart(std::cout, aRefFile, lPos, 15);
else
std::cout << lRefLine;
std::cout << ">" << std::endl;
return 8;
}
return 0;
}
/*******************************************************************************
Return false if the files are not equal.
aLine contains the line number in which the first difference occurs
aCol contains the column number in which the first difference occurs
aPos is the character number off the first difference in the file
-1 is returned for aLine, aCol, and aPos if the files are equal
********************************************************************************/
bool
fileEquals(
const char* aRefFile,
const char* aResFile,
int& aLine,
int& aCol,
int& aPos,
std::string& aRefLine,
std::string& aResLine)
{
std::ifstream li(aRefFile);
std::ifstream ri(aResFile);
std::string lLine, rLine;
if (!li.good())
{
std::cout << "Failed to open ref file " << aRefFile << std::endl;
return false;
}
if (!ri.good())
{
std::cout << "Failed to open results file " << aResFile << std::endl;
return false;
}
aLine = 1; aCol = 0; aPos = -1;
while (! li.eof() )
{
if ( ri.eof() )
{
std::getline(li, lLine);
if (li.peek() == -1) // ignore end-of-line in the ref result
return true;
else
return false;
}
std::getline(li, lLine);
std::getline(ri, rLine);
// TODO: should be removed, right?
trim ( lLine );
trim ( rLine );
while ( (aCol = lLine.compare(rLine)) != 0)
{
if (aLine == 1 &&
lLine == "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
{
++aLine;
std::getline(li, lLine);
continue;
}
else
{
aRefLine = lLine;
aResLine = rLine;
return false;
}
}
++aLine;
}
return true;
}
/*******************************************************************************
Print parts of a file starting at aStartPos with the length of aLen
********************************************************************************/
void
printPart(std::ostream& os, const std::string &aInFile, int aStartPos, int aLen)
{
char* buffer = new char [aLen];
try {
std::ifstream lIn(aInFile.c_str());
lIn.seekg(aStartPos);
#ifdef WIN32
int lCharsRead = lIn._Readsome_s (buffer, aLen, aLen);
#else
int lCharsRead = lIn.readsome (buffer, aLen);
#endif
os.write (buffer, lCharsRead);
os.flush();
delete[] buffer;
} catch (...)
{
delete[] buffer;
}
return;
}
/*******************************************************************************
********************************************************************************/
void
printFile(std::ostream& os, const std::string &aInFile)
{
std::ifstream lInFileStream(aInFile.c_str());
assert(lInFileStream.good());
char buf[1024];
while (!lInFileStream.eof()) {
lInFileStream.read(buf, 1024);
os.write(buf, lInFileStream.gcount());
}
os << std::endl;
}
void
trim(std::string& str)
{
std::string::size_type notwhite = str.find_first_not_of(" \r\t\n");
str.erase(0,notwhite);
notwhite = str.find_last_not_of(" \t\n\r");
str.erase(notwhite+1);
}
} /* namespace zorba */
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2014, Google 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 Google 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.
*
*/
#include <chrono>
#include <thread>
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.pb.h"
#include "test/cpp/util/echo.pb.h"
#include "src/cpp/util/time.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/core/util/port.h"
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;
namespace grpc {
namespace testing {
namespace {
void* tag(int i) {
return (void*)(gpr_intptr)i;
}
void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
bool ok;
void* got_tag;
EXPECT_TRUE(cq->Next(&got_tag, &ok));
EXPECT_EQ(expect_ok, ok);
EXPECT_EQ(tag(i), got_tag);
}
class End2endTest : public ::testing::Test {
protected:
End2endTest() : service_(&srv_cq_) {}
void SetUp() override {
int port = grpc_pick_unused_port_or_die();
server_address_ << "localhost:" << port;
// Setup server
ServerBuilder builder;
builder.AddPort(server_address_.str());
builder.RegisterAsyncService(&service_);
server_ = builder.BuildAndStart();
}
void TearDown() override { server_->Shutdown(); }
void ResetStub() {
std::shared_ptr<ChannelInterface> channel =
CreateChannel(server_address_.str(), ChannelArguments());
stub_.reset(grpc::cpp::test::util::TestService::NewStub(channel));
}
void server_ok(int i) {
verify_ok(&srv_cq_, i, true);
}
void client_ok(int i) {
verify_ok(&cli_cq_, i , true);
}
void server_fail(int i) {
verify_ok(&srv_cq_, i, false);
}
void client_fail(int i) {
verify_ok(&cli_cq_, i, false);
}
CompletionQueue cli_cq_;
CompletionQueue srv_cq_;
std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
std::unique_ptr<Server> server_;
grpc::cpp::test::util::TestService::AsyncService service_;
std::ostringstream server_address_;
};
TEST_F(End2endTest, SimpleRpc) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
send_request.set_message("Hello");
stub_->Echo(
&cli_ctx, send_request, &recv_response, &recv_status, &cli_cq_, tag(1));
service_.RequestEcho(
&srv_ctx, &recv_request, &response_writer, &srv_cq_, tag(2));
server_ok(2);
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
response_writer.Finish(send_response, Status::OK, tag(3));
server_ok(3);
client_ok(1);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.IsOk());
}
TEST_F(End2endTest, SimpleClientStreaming) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
send_request.set_message("Hello");
ClientAsyncWriter<EchoRequest>* cli_stream =
stub_->RequestStream(&cli_ctx, &recv_response, &cli_cq_, tag(1));
service_.RequestRequestStream(
&srv_ctx, &srv_stream, &srv_cq_, tag(2));
server_ok(2);
client_ok(1);
cli_stream->Write(send_request, tag(3));
client_ok(3);
srv_stream.Read(&recv_request, tag(4));
server_ok(4);
EXPECT_EQ(send_request.message(), recv_request.message());
cli_stream->Write(send_request, tag(5));
client_ok(5);
srv_stream.Read(&recv_request, tag(6));
server_ok(6);
EXPECT_EQ(send_request.message(), recv_request.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_request, tag(8));
server_fail(8);
send_response.set_message(recv_request.message());
srv_stream.Finish(send_response, Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.IsOk());
}
TEST_F(End2endTest, SimpleBidiStreaming) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
send_request.set_message("Hello");
ClientAsyncReaderWriter<EchoRequest, EchoResponse>* cli_stream =
stub_->BidiStream(&cli_ctx, &cli_cq_, tag(1));
service_.RequestBidiStream(
&srv_ctx, &srv_stream, &srv_cq_, tag(2));
server_ok(2);
client_ok(1);
cli_stream->Write(send_request, tag(3));
client_ok(3);
srv_stream.Read(&recv_request, tag(4));
server_ok(4);
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
srv_stream.Write(send_response, tag(5));
server_ok(5);
cli_stream->Read(&recv_response, tag(6));
client_ok(6);
EXPECT_EQ(send_response.message(), recv_response.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_request, tag(8));
server_fail(8);
srv_stream.Finish(Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_TRUE(recv_status.IsOk());
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
grpc_init();
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
grpc_shutdown();
google::protobuf::ShutdownProtobufLibrary();
return result;
}
<commit_msg>add a simple server streaming e2e test, which passes<commit_after>/*
*
* Copyright 2014, Google 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 Google 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.
*
*/
#include <chrono>
#include <thread>
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.pb.h"
#include "test/cpp/util/echo.pb.h"
#include "src/cpp/util/time.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include "test/core/util/port.h"
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;
namespace grpc {
namespace testing {
namespace {
void* tag(int i) {
return (void*)(gpr_intptr)i;
}
void verify_ok(CompletionQueue* cq, int i, bool expect_ok) {
bool ok;
void* got_tag;
EXPECT_TRUE(cq->Next(&got_tag, &ok));
EXPECT_EQ(expect_ok, ok);
EXPECT_EQ(tag(i), got_tag);
}
class End2endTest : public ::testing::Test {
protected:
End2endTest() : service_(&srv_cq_) {}
void SetUp() override {
int port = grpc_pick_unused_port_or_die();
server_address_ << "localhost:" << port;
// Setup server
ServerBuilder builder;
builder.AddPort(server_address_.str());
builder.RegisterAsyncService(&service_);
server_ = builder.BuildAndStart();
}
void TearDown() override { server_->Shutdown(); }
void ResetStub() {
std::shared_ptr<ChannelInterface> channel =
CreateChannel(server_address_.str(), ChannelArguments());
stub_.reset(grpc::cpp::test::util::TestService::NewStub(channel));
}
void server_ok(int i) {
verify_ok(&srv_cq_, i, true);
}
void client_ok(int i) {
verify_ok(&cli_cq_, i , true);
}
void server_fail(int i) {
verify_ok(&srv_cq_, i, false);
}
void client_fail(int i) {
verify_ok(&cli_cq_, i, false);
}
CompletionQueue cli_cq_;
CompletionQueue srv_cq_;
std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
std::unique_ptr<Server> server_;
grpc::cpp::test::util::TestService::AsyncService service_;
std::ostringstream server_address_;
};
TEST_F(End2endTest, SimpleRpc) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
grpc::ServerAsyncResponseWriter<EchoResponse> response_writer(&srv_ctx);
send_request.set_message("Hello");
stub_->Echo(
&cli_ctx, send_request, &recv_response, &recv_status, &cli_cq_, tag(1));
service_.RequestEcho(
&srv_ctx, &recv_request, &response_writer, &srv_cq_, tag(2));
server_ok(2);
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
response_writer.Finish(send_response, Status::OK, tag(3));
server_ok(3);
client_ok(1);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.IsOk());
}
// Two pings and a final pong.
TEST_F(End2endTest, SimpleClientStreaming) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
ServerAsyncReader<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
send_request.set_message("Hello");
ClientAsyncWriter<EchoRequest>* cli_stream =
stub_->RequestStream(&cli_ctx, &recv_response, &cli_cq_, tag(1));
service_.RequestRequestStream(
&srv_ctx, &srv_stream, &srv_cq_, tag(2));
server_ok(2);
client_ok(1);
cli_stream->Write(send_request, tag(3));
client_ok(3);
srv_stream.Read(&recv_request, tag(4));
server_ok(4);
EXPECT_EQ(send_request.message(), recv_request.message());
cli_stream->Write(send_request, tag(5));
client_ok(5);
srv_stream.Read(&recv_request, tag(6));
server_ok(6);
EXPECT_EQ(send_request.message(), recv_request.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_request, tag(8));
server_fail(8);
send_response.set_message(recv_request.message());
srv_stream.Finish(send_response, Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_EQ(send_response.message(), recv_response.message());
EXPECT_TRUE(recv_status.IsOk());
}
// One ping, two pongs.
TEST_F(End2endTest, SimpleServerStreaming) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
ServerAsyncWriter<EchoResponse> srv_stream(&srv_ctx);
send_request.set_message("Hello");
ClientAsyncReader<EchoResponse>* cli_stream =
stub_->ResponseStream(&cli_ctx, send_request, &cli_cq_, tag(1));
service_.RequestResponseStream(
&srv_ctx, &recv_request, &srv_stream, &srv_cq_, tag(2));
server_ok(2);
client_ok(1);
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
srv_stream.Write(send_response, tag(3));
server_ok(3);
cli_stream->Read(&recv_response, tag(4));
client_ok(4);
EXPECT_EQ(send_response.message(), recv_response.message());
srv_stream.Write(send_response, tag(5));
server_ok(5);
cli_stream->Read(&recv_response, tag(6));
client_ok(6);
EXPECT_EQ(send_response.message(), recv_response.message());
srv_stream.Finish(Status::OK, tag(7));
server_ok(7);
cli_stream->Read(&recv_response, tag(8));
client_fail(8);
cli_stream->Finish(&recv_status, tag(9));
client_ok(9);
EXPECT_TRUE(recv_status.IsOk());
}
// One ping, one pong.
TEST_F(End2endTest, SimpleBidiStreaming) {
ResetStub();
EchoRequest send_request;
EchoRequest recv_request;
EchoResponse send_response;
EchoResponse recv_response;
Status recv_status;
ClientContext cli_ctx;
ServerContext srv_ctx;
ServerAsyncReaderWriter<EchoResponse, EchoRequest> srv_stream(&srv_ctx);
send_request.set_message("Hello");
ClientAsyncReaderWriter<EchoRequest, EchoResponse>* cli_stream =
stub_->BidiStream(&cli_ctx, &cli_cq_, tag(1));
service_.RequestBidiStream(
&srv_ctx, &srv_stream, &srv_cq_, tag(2));
server_ok(2);
client_ok(1);
cli_stream->Write(send_request, tag(3));
client_ok(3);
srv_stream.Read(&recv_request, tag(4));
server_ok(4);
EXPECT_EQ(send_request.message(), recv_request.message());
send_response.set_message(recv_request.message());
srv_stream.Write(send_response, tag(5));
server_ok(5);
cli_stream->Read(&recv_response, tag(6));
client_ok(6);
EXPECT_EQ(send_response.message(), recv_response.message());
cli_stream->WritesDone(tag(7));
client_ok(7);
srv_stream.Read(&recv_request, tag(8));
server_fail(8);
srv_stream.Finish(Status::OK, tag(9));
server_ok(9);
cli_stream->Finish(&recv_status, tag(10));
client_ok(10);
EXPECT_TRUE(recv_status.IsOk());
}
} // namespace
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
grpc_init();
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
grpc_shutdown();
google::protobuf::ShutdownProtobufLibrary();
return result;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTextMasterPageContext.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:24:04 $
*
* 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 _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;
Reference < XStyle > XMLTextMasterPageContext::Create()
{
Reference < XStyle > xNewStyle;
Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
UNO_QUERY );
if( xFactory.is() )
{
Reference < XInterface > xIfc =
xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.style.PageStyle")) );
if( xIfc.is() )
xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
}
return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );
XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
sal_uInt16 nPrfx, const OUString& rLName,
const Reference< XAttributeList > & xAttrList,
sal_Bool bOverwrite ) :
SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE ),
sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) ),
sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) ),
sPageMasterName(),
bInsertHeader( sal_False ),
bInsertFooter( sal_False ),
bInsertHeaderLeft( sal_False ),
bInsertFooterLeft( sal_False ),
bHeaderInserted( sal_False ),
bFooterInserted( sal_False ),
bHeaderLeftInserted( sal_False ),
bFooterLeftInserted( sal_False )
{
OUString sName, sDisplayName;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( XML_NAMESPACE_STYLE == nPrefix )
{
if( IsXMLToken( aLocalName, XML_NAME ) )
{
sName = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
{
sDisplayName = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
{
sFollow = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
{
sPageMasterName = xAttrList->getValueByIndex( i );
}
}
}
if( sDisplayName.getLength() )
{
rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
sDisplayName );
}
else
{
sDisplayName = sName;
}
if( 0 == sDisplayName.getLength() )
return;
Reference < XNameContainer > xPageStyles =
GetImport().GetTextImport()->GetPageStyles();
if( !xPageStyles.is() )
return;
Any aAny;
sal_Bool bNew = sal_False;
if( xPageStyles->hasByName( sDisplayName ) )
{
aAny = xPageStyles->getByName( sDisplayName );
aAny >>= xStyle;
}
else
{
xStyle = Create();
if( !xStyle.is() )
return;
aAny <<= xStyle;
xPageStyles->insertByName( sDisplayName, aAny );
bNew = sal_True;
}
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
{
aAny = xPropSet->getPropertyValue( sIsPhysical );
bNew = !*(sal_Bool *)aAny.getValue();
}
SetNew( bNew );
if( bOverwrite || bNew )
{
Reference < XMultiPropertyStates > xMultiStates( xPropSet,
UNO_QUERY );
OSL_ENSURE( xMultiStates.is(),
"text page style does not support multi property set" );
if( xMultiStates.is() )
xMultiStates->setAllPropertiesToDefault();
bInsertHeader = bInsertFooter = sal_True;
bInsertHeaderLeft = bInsertFooterLeft = sal_True;
}
}
XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}
SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap =
GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();
sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_TEXT_MP_HEADER:
if( bInsertHeader && !bHeaderInserted )
{
bInsert = sal_True;
bHeaderInserted = sal_True;
}
break;
case XML_TOK_TEXT_MP_FOOTER:
if( bInsertFooter && !bFooterInserted )
{
bInsert = bFooter = sal_True;
bFooterInserted = sal_True;
}
break;
case XML_TOK_TEXT_MP_HEADER_LEFT:
if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
bInsert = bLeft = sal_True;
break;
case XML_TOK_TEXT_MP_FOOTER_LEFT:
if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
bInsert = bFooter = bLeft = sal_True;
break;
}
if( bInsert && xStyle.is() )
{
pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
xAttrList,
bFooter, bLeft );
}
else
{
pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
xAttrList );
}
return pContext;
}
SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const sal_Bool bFooter,
const sal_Bool bLeft )
{
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
return new XMLTextHeaderFooterContext( GetImport(),
nPrefix, rLocalName,
xAttrList,
xPropSet,
bFooter, bLeft );
}
void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
if( xStyle.is() && (IsNew() || bOverwrite) )
{
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
if( sPageMasterName.getLength() )
{
XMLPropStyleContext* pStyle =
GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
if (pStyle)
{
pStyle->FillPropertySet(xPropSet);
}
}
Reference < XNameContainer > xPageStyles =
GetImport().GetTextImport()->GetPageStyles();
if( !xPageStyles.is() )
return;
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
{
OUString sDisplayFollow(
GetImport().GetStyleDisplayName(
XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
if( !sDisplayFollow.getLength() ||
!xPageStyles->hasByName( sDisplayFollow ) )
sDisplayFollow = xStyle->getName();
Any aAny = xPropSet->getPropertyValue( sFollowStyle );
OUString sCurrFollow;
aAny >>= sCurrFollow;
if( sCurrFollow != sDisplayFollow )
{
aAny <<= sDisplayFollow;
xPropSet->setPropertyValue( sFollowStyle, aAny );
}
}
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.10.32); FILE MERGED 2005/11/03 17:47:11 cl 1.10.32.1: warning free code changes for unxlngi6<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTextMasterPageContext.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:46:49 $
*
* 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 _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;
Reference < XStyle > XMLTextMasterPageContext::Create()
{
Reference < XStyle > xNewStyle;
Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
UNO_QUERY );
if( xFactory.is() )
{
Reference < XInterface > xIfc =
xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.style.PageStyle")) );
if( xIfc.is() )
xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
}
return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );
XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
sal_uInt16 nPrfx, const OUString& rLName,
const Reference< XAttributeList > & xAttrList,
sal_Bool bOverwrite )
: SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE )
, sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) )
, sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) )
, sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
, bInsertHeader( sal_False )
, bInsertFooter( sal_False )
, bInsertHeaderLeft( sal_False )
, bInsertFooterLeft( sal_False )
, bHeaderInserted( sal_False )
, bFooterInserted( sal_False )
, bHeaderLeftInserted( sal_False )
, bFooterLeftInserted( sal_False )
{
OUString sName, sDisplayName;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( XML_NAMESPACE_STYLE == nPrefix )
{
if( IsXMLToken( aLocalName, XML_NAME ) )
{
sName = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
{
sDisplayName = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
{
sFollow = xAttrList->getValueByIndex( i );
}
else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
{
sPageMasterName = xAttrList->getValueByIndex( i );
}
}
}
if( sDisplayName.getLength() )
{
rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
sDisplayName );
}
else
{
sDisplayName = sName;
}
if( 0 == sDisplayName.getLength() )
return;
Reference < XNameContainer > xPageStyles =
GetImport().GetTextImport()->GetPageStyles();
if( !xPageStyles.is() )
return;
Any aAny;
sal_Bool bNew = sal_False;
if( xPageStyles->hasByName( sDisplayName ) )
{
aAny = xPageStyles->getByName( sDisplayName );
aAny >>= xStyle;
}
else
{
xStyle = Create();
if( !xStyle.is() )
return;
aAny <<= xStyle;
xPageStyles->insertByName( sDisplayName, aAny );
bNew = sal_True;
}
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
{
aAny = xPropSet->getPropertyValue( sIsPhysical );
bNew = !*(sal_Bool *)aAny.getValue();
}
SetNew( bNew );
if( bOverwrite || bNew )
{
Reference < XMultiPropertyStates > xMultiStates( xPropSet,
UNO_QUERY );
OSL_ENSURE( xMultiStates.is(),
"text page style does not support multi property set" );
if( xMultiStates.is() )
xMultiStates->setAllPropertiesToDefault();
bInsertHeader = bInsertFooter = sal_True;
bInsertHeaderLeft = bInsertFooterLeft = sal_True;
}
}
XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}
SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap =
GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();
sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_TEXT_MP_HEADER:
if( bInsertHeader && !bHeaderInserted )
{
bInsert = sal_True;
bHeaderInserted = sal_True;
}
break;
case XML_TOK_TEXT_MP_FOOTER:
if( bInsertFooter && !bFooterInserted )
{
bInsert = bFooter = sal_True;
bFooterInserted = sal_True;
}
break;
case XML_TOK_TEXT_MP_HEADER_LEFT:
if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
bInsert = bLeft = sal_True;
break;
case XML_TOK_TEXT_MP_FOOTER_LEFT:
if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
bInsert = bFooter = bLeft = sal_True;
break;
}
if( bInsert && xStyle.is() )
{
pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
xAttrList,
bFooter, bLeft );
}
else
{
pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
xAttrList );
}
return pContext;
}
SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
const sal_Bool bFooter,
const sal_Bool bLeft )
{
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
return new XMLTextHeaderFooterContext( GetImport(),
nPrefix, rLocalName,
xAttrList,
xPropSet,
bFooter, bLeft );
}
void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
if( xStyle.is() && (IsNew() || bOverwrite) )
{
Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
if( sPageMasterName.getLength() )
{
XMLPropStyleContext* pStyle =
GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
if (pStyle)
{
pStyle->FillPropertySet(xPropSet);
}
}
Reference < XNameContainer > xPageStyles =
GetImport().GetTextImport()->GetPageStyles();
if( !xPageStyles.is() )
return;
Reference< XPropertySetInfo > xPropSetInfo =
xPropSet->getPropertySetInfo();
if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
{
OUString sDisplayFollow(
GetImport().GetStyleDisplayName(
XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
if( !sDisplayFollow.getLength() ||
!xPageStyles->hasByName( sDisplayFollow ) )
sDisplayFollow = xStyle->getName();
Any aAny = xPropSet->getPropertyValue( sFollowStyle );
OUString sCurrFollow;
aAny >>= sCurrFollow;
if( sCurrFollow != sDisplayFollow )
{
aAny <<= sDisplayFollow;
xPropSet->setPropertyValue( sFollowStyle, aAny );
}
}
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cassert>
#include "IECore/VectorTraits.h"
namespace IECore
{
template<class BoundIterator>
class BoundedKDTree<BoundIterator>::AxisSort
{
public :
AxisSort( unsigned int axis ) : m_axis( axis )
{
}
bool operator() ( BoundIterator i, BoundIterator j )
{
return i->center()[m_axis] < j->center()[m_axis];
}
private :
const unsigned int m_axis;
};
template<class BoundIterator>
class BoundedKDTree<BoundIterator>::Node
{
public :
Node()
{
m_bound = Bound();
}
inline void makeLeaf( PermutationIterator permFirst, PermutationIterator permLast )
{
m_cutAxisAndLeaf = 255;
m_perm.first = &(*permFirst);
m_perm.last = &(*permLast);
}
inline void makeBranch( unsigned char cutAxis )
{
m_cutAxisAndLeaf = cutAxis;
}
inline bool isLeaf() const
{
return m_cutAxisAndLeaf==255;
}
inline BoundIterator *permFirst() const
{
assert( isLeaf() );
return m_perm.first;
}
inline BoundIterator *permLast() const
{
assert( isLeaf() );
return m_perm.last;
}
inline bool isBranch() const
{
return m_cutAxisAndLeaf!=255;
}
inline unsigned char cutAxis() const
{
assert( isBranch() );
return m_cutAxisAndLeaf;
}
inline Bound &bound()
{
return m_bound;
}
inline Bound bound() const
{
return m_bound;
}
static NodeIndex rootIndex()
{
return 1;
}
static NodeIndex lowChildIndex( NodeIndex index )
{
return index * 2;
}
static NodeIndex highChildIndex( NodeIndex index )
{
return index * 2 + 1;
}
private :
unsigned char m_cutAxisAndLeaf;
Bound m_bound;
struct {
BoundIterator *first;
BoundIterator *last;
} m_perm;
};
template<class BoundIterator>
unsigned char BoundedKDTree<BoundIterator>::majorAxis( PermutationConstIterator permFirst, PermutationConstIterator permLast )
{
BaseType min, max;
for( unsigned char i=0; i<VectorTraits<BaseType>::dimensions(); i++ ) {
min[i] = Imath::limits<typename BaseType::BaseType>::max();
max[i] = Imath::limits<typename BaseType::BaseType>::min();
}
/// \todo Find a better cutting axis
for( PermutationConstIterator it=permFirst; it!=permLast; it++ )
{
BaseType center = (*it)->center();
for( unsigned char i=0; i<VectorTraits<BaseType>::dimensions(); i++ )
{
if( center[i] < min[i] )
{
min[i] = center[i];
}
if( center[i] > max[i] )
{
max[i] = center[i];
}
}
}
unsigned char major = 0;
BaseType size = max - min;
for( unsigned char i=1; i<VectorTraits<BaseType>::dimensions(); i++ )
{
if( size[i] > size[major] )
{
major = i;
}
}
return major;
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::bound( NodeIndex nodeIndex )
{
const Node &node = m_nodes[nodeIndex];
if( node.isLeaf() )
{
BoundIterator *permLast = node.permLast();
for( BoundIterator *perm = node.permFirst(); perm!=permLast; perm++ )
{
node.bound().extendBy( **perm );
}
}
else
{
assert( node.isBranch() );
bound( Node::lowChildIndex( nodeIndex ) );
bound( Node::highChildIndex( nodeIndex ) );
node.bound().extendBy( m_nodes[Node::lowChildIndex( nodeIndex )].bound() );
node.bound().extendBy( m_nodes[Node::highChildIndex( nodeIndex )].bound() );
}
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::build( NodeIndex nodeIndex, PermutationIterator permFirst, PermutationIterator permLast )
{
// make room for the new node
if( nodeIndex>=m_nodes.size() )
{
m_nodes.resize( nodeIndex+1 );
}
Node &node = m_nodes[nodeIndex];
if( permLast - permFirst > m_maxLeafSize )
{
unsigned int cutAxis = majorAxis( permFirst, permLast );
PermutationIterator permMid = permFirst + (permLast - permFirst)/2;
std::nth_element( permFirst, permMid, permLast, AxisSort( cutAxis ) );
// insert node
node.makeBranch( cutAxis );
build( Node::lowChildIndex( nodeIndex ), permFirst, permMid );
build( Node::highChildIndex( nodeIndex ), permMid, permLast );
}
else
{
// leaf node
node.makeLeaf( permFirst, permLast );
}
}
template<class BoundIterator>
BoundedKDTree<BoundIterator>::BoundedKDTree( BoundIterator first, BoundIterator last, int maxLeafSize )
: m_maxLeafSize( maxLeafSize ), m_lastBound( last )
{
m_perm.resize( last - first );
unsigned int i=0;
for( BoundIterator it=first; it!=last; it++ )
{
m_perm[i++] = it;
}
build( Node::rootIndex(), m_perm.begin(), m_perm.end() );
bound( Node::rootIndex() );
}
template<class BoundIterator>
unsigned int BoundedKDTree<BoundIterator>::intersectingBounds( const Bound &b, std::vector<BoundIterator> &bounds ) const
{
bounds.clear();
intersectingBoundsWalk(Node::rootIndex(), b, bounds );
return bounds.size();
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::intersectingBoundsWalk( NodeIndex nodeIndex, const Bound &b, std::vector<BoundIterator> &bounds ) const
{
const Node &node = m_nodes[nodeIndex];
if( node.isLeaf() )
{
BoundIterator *permLast = node.permLast();
for( BoundIterator *perm = node.permFirst(); perm!=permLast; perm++ )
{
const Bound &bb = **perm;
if ( bb.intersects(b) )
{
bounds.push_back( *perm );
}
}
}
else
{
NodeIndex firstChild = Node::highChildIndex( nodeIndex );
if ( m_nodes[firstChild].bound().intersects(b) )
{
intersectingBoundsWalk( firstChild, b, bounds );
}
NodeIndex secondChild = Node::lowChildIndex( nodeIndex );
if ( m_nodes[secondChild].bound().intersects(b) )
{
intersectingBoundsWalk( secondChild, b, bounds );
}
}
}
} // namespace IECore
<commit_msg>Fixed license. Added asserts.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <cassert>
#include "IECore/VectorTraits.h"
namespace IECore
{
template<class BoundIterator>
class BoundedKDTree<BoundIterator>::AxisSort
{
public :
AxisSort( unsigned int axis ) : m_axis( axis )
{
}
bool operator() ( BoundIterator i, BoundIterator j )
{
return i->center()[m_axis] < j->center()[m_axis];
}
private :
const unsigned int m_axis;
};
template<class BoundIterator>
class BoundedKDTree<BoundIterator>::Node
{
public :
Node()
{
m_bound = Bound();
}
inline void makeLeaf( PermutationIterator permFirst, PermutationIterator permLast )
{
m_cutAxisAndLeaf = 255;
m_perm.first = &(*permFirst);
m_perm.last = &(*permLast);
}
inline void makeBranch( unsigned char cutAxis )
{
m_cutAxisAndLeaf = cutAxis;
}
inline bool isLeaf() const
{
return m_cutAxisAndLeaf==255;
}
inline BoundIterator *permFirst() const
{
assert( isLeaf() );
return m_perm.first;
}
inline BoundIterator *permLast() const
{
assert( isLeaf() );
return m_perm.last;
}
inline bool isBranch() const
{
return m_cutAxisAndLeaf!=255;
}
inline unsigned char cutAxis() const
{
assert( isBranch() );
return m_cutAxisAndLeaf;
}
inline Bound &bound()
{
return m_bound;
}
inline Bound bound() const
{
return m_bound;
}
static NodeIndex rootIndex()
{
return 1;
}
static NodeIndex lowChildIndex( NodeIndex index )
{
return index * 2;
}
static NodeIndex highChildIndex( NodeIndex index )
{
return index * 2 + 1;
}
private :
unsigned char m_cutAxisAndLeaf;
Bound m_bound;
struct {
BoundIterator *first;
BoundIterator *last;
} m_perm;
};
template<class BoundIterator>
unsigned char BoundedKDTree<BoundIterator>::majorAxis( PermutationConstIterator permFirst, PermutationConstIterator permLast )
{
BaseType min, max;
for( unsigned char i=0; i<VectorTraits<BaseType>::dimensions(); i++ ) {
min[i] = Imath::limits<typename BaseType::BaseType>::max();
max[i] = Imath::limits<typename BaseType::BaseType>::min();
}
/// \todo Find a better cutting axis
for( PermutationConstIterator it=permFirst; it!=permLast; it++ )
{
BaseType center = (*it)->center();
for( unsigned char i=0; i<VectorTraits<BaseType>::dimensions(); i++ )
{
if( center[i] < min[i] )
{
min[i] = center[i];
}
if( center[i] > max[i] )
{
max[i] = center[i];
}
}
}
unsigned char major = 0;
BaseType size = max - min;
for( unsigned char i=1; i<VectorTraits<BaseType>::dimensions(); i++ )
{
if( size[i] > size[major] )
{
major = i;
}
}
return major;
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::bound( NodeIndex nodeIndex )
{
const Node &node = m_nodes[nodeIndex];
if( node.isLeaf() )
{
BoundIterator *permLast = node.permLast();
for( BoundIterator *perm = node.permFirst(); perm!=permLast; perm++ )
{
node.bound().extendBy( **perm );
}
}
else
{
assert( node.isBranch() );
assert( Node::lowChildIndex( nodeIndex ) < m_nodes.size() );
assert( Node::highChildIndex( nodeIndex ) < m_nodes.size() );
bound( Node::lowChildIndex( nodeIndex ) );
bound( Node::highChildIndex( nodeIndex ) );
node.bound().extendBy( m_nodes[Node::lowChildIndex( nodeIndex )].bound() );
node.bound().extendBy( m_nodes[Node::highChildIndex( nodeIndex )].bound() );
}
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::build( NodeIndex nodeIndex, PermutationIterator permFirst, PermutationIterator permLast )
{
// make room for the new node
if( nodeIndex>=m_nodes.size() )
{
m_nodes.resize( nodeIndex+1 );
}
assert( nodeIndex < m_nodes.size() );
Node &node = m_nodes[nodeIndex];
if( permLast - permFirst > m_maxLeafSize )
{
unsigned int cutAxis = majorAxis( permFirst, permLast );
PermutationIterator permMid = permFirst + (permLast - permFirst)/2;
std::nth_element( permFirst, permMid, permLast, AxisSort( cutAxis ) );
// insert node
node.makeBranch( cutAxis );
build( Node::lowChildIndex( nodeIndex ), permFirst, permMid );
build( Node::highChildIndex( nodeIndex ), permMid, permLast );
}
else
{
// leaf node
node.makeLeaf( permFirst, permLast );
}
}
template<class BoundIterator>
BoundedKDTree<BoundIterator>::BoundedKDTree( BoundIterator first, BoundIterator last, int maxLeafSize )
: m_maxLeafSize( maxLeafSize ), m_lastBound( last )
{
m_perm.resize( last - first );
unsigned int i=0;
for( BoundIterator it=first; it!=last; it++ )
{
m_perm[i++] = it;
}
build( Node::rootIndex(), m_perm.begin(), m_perm.end() );
bound( Node::rootIndex() );
}
template<class BoundIterator>
unsigned int BoundedKDTree<BoundIterator>::intersectingBounds( const Bound &b, std::vector<BoundIterator> &bounds ) const
{
bounds.clear();
intersectingBoundsWalk(Node::rootIndex(), b, bounds );
return bounds.size();
}
template<class BoundIterator>
void BoundedKDTree<BoundIterator>::intersectingBoundsWalk( NodeIndex nodeIndex, const Bound &b, std::vector<BoundIterator> &bounds ) const
{
const Node &node = m_nodes[nodeIndex];
if( node.isLeaf() )
{
BoundIterator *permLast = node.permLast();
for( BoundIterator *perm = node.permFirst(); perm!=permLast; perm++ )
{
const Bound &bb = **perm;
if ( bb.intersects(b) )
{
bounds.push_back( *perm );
}
}
}
else
{
NodeIndex firstChild = Node::highChildIndex( nodeIndex );
if ( m_nodes[firstChild].bound().intersects(b) )
{
intersectingBoundsWalk( firstChild, b, bounds );
}
NodeIndex secondChild = Node::lowChildIndex( nodeIndex );
if ( m_nodes[secondChild].bound().intersects(b) )
{
intersectingBoundsWalk( secondChild, b, bounds );
}
}
}
} // namespace IECore
<|endoftext|>
|
<commit_before>#ifndef __AMUSE_AUDIOGROUPPOOL_HPP__
#define __AMUSE_AUDIOGROUPPOOL_HPP__
#include <stdint.h>
#include <vector>
#include <cmath>
#include <unordered_map>
#include "Entity.hpp"
#include "Common.hpp"
namespace amuse
{
/** Converts time-cents representation to seconds */
static inline double TimeCentsToSeconds(int32_t tc)
{
if (uint32_t(tc) == 0x80000000)
return 0.0;
return std::exp2(tc / (1200.0 * 65536.0));
}
/** Defines phase-based volume curve for macro volume control */
struct ADSR
{
uint8_t attackFine; /* 0-255ms */
uint8_t attackCoarse; /* 0-65280ms */
uint8_t decayFine; /* 0-255ms */
uint8_t decayCoarse; /* 0-65280ms */
uint8_t sustainFine; /* multiply by 0.0244 for percentage */
uint8_t sustainCoarse; /* multiply by 6.25 for percentage */
uint8_t releaseFine; /* 0-255ms */
uint8_t releaseCoarse; /* 0-65280ms */
double getAttack() const { return (attackCoarse * 255 + attackFine) / 1000.0; }
double getDecay() const { return decayCoarse == 128 ? 0.0 : ((decayCoarse * 255 + decayFine) / 1000.0); }
double getSustain() const
{
return decayCoarse == 128 ? 1.0 : ((sustainCoarse * 6.25 + sustainFine * 0.0244) / 100.0);
}
double getRelease() const { return (releaseCoarse * 255 + releaseFine) / 1000.0; }
};
/** Defines phase-based volume curve for macro volume control (modified DLS standard) */
struct ADSRDLS
{
uint32_t attack; /* 16.16 Time-cents */
uint32_t decay; /* 16.16 Time-cents */
uint16_t sustain; /* 0x1000 == 100% */
uint16_t release; /* milliseconds */
uint32_t velToAttack; /* 16.16, 1000.0 == 100%; attack = <attack> + (vel/128) * <velToAttack> */
uint32_t keyToDecay; /* 16.16, 1000.0 == 100%; decay = <decay> + (note/128) * <keyToDecay> */
double getAttack() const { return TimeCentsToSeconds(attack); }
double getDecay() const { return TimeCentsToSeconds(decay); }
double getSustain() const { return sustain / double(0x1000); }
double getRelease() const { return release / double(1000); }
double getVelToAttack(int8_t vel) const
{
if (velToAttack == 0x80000000)
return getAttack();
return getAttack() + vel * (velToAttack / 65536.0 / 1000.0) / 128.0;
}
double getKeyToDecay(int8_t note) const
{
if (keyToDecay == 0x80000000)
return getDecay();
return getDecay() + note * (keyToDecay / 65536.0 / 1000.0) / 128.0;
}
};
/** Maps individual MIDI keys to sound-entity as indexed in table
* (macro-voice, keymap, layer) */
struct Keymap
{
int16_t objectId;
int8_t transpose;
int8_t pan; /* -128 for surround-channel only */
int8_t prioOffset;
int8_t pad[3];
};
/** Maps ranges of MIDI keys to sound-entity (macro-voice, keymap, layer) */
struct LayerMapping
{
int16_t objectId;
int8_t keyLo;
int8_t keyHi;
int8_t transpose;
int8_t volume;
int8_t prioOffset;
int8_t span;
int8_t pan;
};
/** Database of functional objects within Audio Group */
class AudioGroupPool
{
std::unordered_map<ObjectId, const unsigned char*> m_soundMacros;
std::unordered_map<ObjectId, const unsigned char*> m_tables;
std::unordered_map<ObjectId, const Keymap*> m_keymaps;
std::unordered_map<ObjectId, std::vector<const LayerMapping*>> m_layers;
public:
AudioGroupPool(const unsigned char* data);
AudioGroupPool(const unsigned char* data, PCDataTag);
const unsigned char* soundMacro(ObjectId id) const;
const Keymap* keymap(ObjectId id) const;
const std::vector<const LayerMapping*>* layer(ObjectId id) const;
const ADSR* tableAsAdsr(ObjectId id) const;
const ADSRDLS* tableAsAdsrDLS(ObjectId id) const { return reinterpret_cast<const ADSRDLS*>(tableAsAdsr(id)); }
const Curve* tableAsCurves(ObjectId id) const { return reinterpret_cast<const Curve*>(tableAsAdsr(id)); }
};
}
#endif // __AMUSE_AUDIOGROUPPOOL_HPP__
<commit_msg>less redundant way of handling little-endian shorts<commit_after>#ifndef __AMUSE_AUDIOGROUPPOOL_HPP__
#define __AMUSE_AUDIOGROUPPOOL_HPP__
#include <stdint.h>
#include <vector>
#include <cmath>
#include <unordered_map>
#include "Entity.hpp"
#include "Common.hpp"
namespace amuse
{
/** Converts time-cents representation to seconds */
static inline double TimeCentsToSeconds(int32_t tc)
{
if (uint32_t(tc) == 0x80000000)
return 0.0;
return std::exp2(tc / (1200.0 * 65536.0));
}
/** Defines phase-based volume curve for macro volume control */
struct ADSR
{
uint16_t attack;
uint16_t decay;
uint16_t sustain; /* 0x1000 == 100% */
uint16_t release; /* milliseconds */
double getAttack() const { return attack / 1000.0; }
double getDecay() const { return (decay == 0x8000) ? 0.0 : (decay / 1000.0); }
double getSustain() const { return sustain / double(0x1000); }
double getRelease() const { return release / double(1000); }
};
/** Defines phase-based volume curve for macro volume control (modified DLS standard) */
struct ADSRDLS
{
uint32_t attack; /* 16.16 Time-cents */
uint32_t decay; /* 16.16 Time-cents */
uint16_t sustain; /* 0x1000 == 100% */
uint16_t release; /* milliseconds */
uint32_t velToAttack; /* 16.16, 1000.0 == 100%; attack = <attack> + (vel/128) * <velToAttack> */
uint32_t keyToDecay; /* 16.16, 1000.0 == 100%; decay = <decay> + (note/128) * <keyToDecay> */
double getAttack() const { return TimeCentsToSeconds(attack); }
double getDecay() const { return TimeCentsToSeconds(decay); }
double getSustain() const { return sustain / double(0x1000); }
double getRelease() const { return release / double(1000); }
double getVelToAttack(int8_t vel) const
{
if (velToAttack == 0x80000000)
return getAttack();
return getAttack() + vel * (velToAttack / 65536.0 / 1000.0) / 128.0;
}
double getKeyToDecay(int8_t note) const
{
if (keyToDecay == 0x80000000)
return getDecay();
return getDecay() + note * (keyToDecay / 65536.0 / 1000.0) / 128.0;
}
};
/** Maps individual MIDI keys to sound-entity as indexed in table
* (macro-voice, keymap, layer) */
struct Keymap
{
int16_t objectId;
int8_t transpose;
int8_t pan; /* -128 for surround-channel only */
int8_t prioOffset;
int8_t pad[3];
};
/** Maps ranges of MIDI keys to sound-entity (macro-voice, keymap, layer) */
struct LayerMapping
{
int16_t objectId;
int8_t keyLo;
int8_t keyHi;
int8_t transpose;
int8_t volume;
int8_t prioOffset;
int8_t span;
int8_t pan;
};
/** Database of functional objects within Audio Group */
class AudioGroupPool
{
std::unordered_map<ObjectId, const unsigned char*> m_soundMacros;
std::unordered_map<ObjectId, const unsigned char*> m_tables;
std::unordered_map<ObjectId, const Keymap*> m_keymaps;
std::unordered_map<ObjectId, std::vector<const LayerMapping*>> m_layers;
public:
AudioGroupPool(const unsigned char* data);
AudioGroupPool(const unsigned char* data, PCDataTag);
const unsigned char* soundMacro(ObjectId id) const;
const Keymap* keymap(ObjectId id) const;
const std::vector<const LayerMapping*>* layer(ObjectId id) const;
const ADSR* tableAsAdsr(ObjectId id) const;
const ADSRDLS* tableAsAdsrDLS(ObjectId id) const { return reinterpret_cast<const ADSRDLS*>(tableAsAdsr(id)); }
const Curve* tableAsCurves(ObjectId id) const { return reinterpret_cast<const Curve*>(tableAsAdsr(id)); }
};
}
#endif // __AMUSE_AUDIOGROUPPOOL_HPP__
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <type_traits>
#include <archie/meta/static_constexpr_storage.hpp>
namespace archie {
namespace detail {
template <typename...>
struct to_function_pointer_;
template <typename R, typename... Args>
struct to_function_pointer_<R(Args...)> {
using type = R (*)(Args...);
template <typename T>
std::enable_if_t<std::is_convertible<T, type>::value, type> operator()(T t) const {
return t;
}
template <typename T>
std::enable_if_t<!std::is_convertible<T, type>::value && std::is_empty<T>::value &&
std::is_trivially_constructible<T>::value,
type>
operator()(T) const {
return this->operator()(
[](Args... args) { return std::add_const_t<T>{}(std::forward<Args>(args)...); });
}
};
}
template <typename...>
struct pure_function;
template <typename R, typename... Args>
struct pure_function<R(Args...)> {
using type = R (*)(Args...);
pure_function() = default;
template <typename T>
explicit pure_function(T t)
: fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}
template <typename T>
pure_function& operator=(T t) {
fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);
return *this;
}
template <typename... U>
auto operator()(U&&... u) const {
return (*fptr)(std::forward<U>(u)...);
}
explicit operator bool() const { return fptr != nullptr; }
operator type() const { return fptr; }
private:
type fptr = nullptr;
};
}
<commit_msg>hide logic<commit_after>#pragma once
#include <utility>
#include <type_traits>
#include <archie/meta/static_constexpr_storage.hpp>
namespace archie {
namespace detail {
template <typename...>
struct to_function_pointer_;
template <typename R, typename... Args>
struct to_function_pointer_<R(Args...)> {
using type = R (*)(Args...);
private:
struct convertible_tag {};
struct stateless_tag {};
template <typename T>
type convert(T&& t, convertible_tag) const {
return std::forward<T>(t);
}
template <typename T>
type convert(T&&, stateless_tag) const {
using Func = std::decay_t<T>;
auto const wrap =
[](Args... args) { return std::add_const_t<Func>{}(std::forward<Args>(args)...); };
return operator()(wrap);
}
public:
template <typename T>
type operator()(T&& t) const {
using Func = std::decay_t<T>;
return convert(
std::forward<T>(t),
std::conditional_t<std::is_convertible<Func, type>::value, convertible_tag,
std::conditional_t<std::is_empty<Func>::value &&
std::is_trivially_constructible<Func>::value,
stateless_tag, void>>{});
}
};
}
template <typename...>
struct pure_function;
template <typename R, typename... Args>
struct pure_function<R(Args...)> {
using type = R (*)(Args...);
pure_function() = default;
template <typename T>
explicit pure_function(T t)
: fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}
template <typename T>
pure_function& operator=(T t) {
fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);
return *this;
}
template <typename... U>
auto operator()(U&&... u) const {
return (*fptr)(std::forward<U>(u)...);
}
explicit operator bool() const { return fptr != nullptr; }
operator type() const { return fptr; }
private:
type fptr = nullptr;
};
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "File.h"
#include "Folder.h"
#include "Device.h"
#include "Media.h"
#include "database/SqliteTools.h"
#include "filesystem/IDirectory.h"
#include "filesystem/IDevice.h"
#include "utils/Filename.h"
#include <unordered_map>
namespace policy
{
const std::string FolderTable::Name = "Folder";
const std::string FolderTable::PrimaryKeyColumn = "id_folder";
unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id;
}
std::shared_ptr<factory::IFileSystem> Folder::FsFactory;
Folder::Folder( DBConnection dbConnection, sqlite::Row& row )
: m_dbConection( dbConnection )
{
row >> m_id
>> m_path
>> m_parent
>> m_isBlacklisted
>> m_deviceId
>> m_isPresent
>> m_isRemovable;
}
Folder::Folder( const std::string& path, unsigned int parent, unsigned int deviceId, bool isRemovable )
: m_id( 0 )
, m_path( path )
, m_parent( parent )
, m_isBlacklisted( false )
, m_deviceId( deviceId )
, m_isPresent( true )
, m_isRemovable( isRemovable )
{
}
bool Folder::createTable(DBConnection connection)
{
std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name +
"("
"id_folder INTEGER PRIMARY KEY AUTOINCREMENT,"
"path TEXT,"
"parent_id UNSIGNED INTEGER,"
"is_blacklisted INTEGER NOT NULL DEFAULT 0,"
"device_id UNSIGNED INTEGER,"
"is_present BOOLEAN NOT NULL DEFAULT 1,"
"is_removable BOOLEAN NOT NULL,"
"FOREIGN KEY (parent_id) REFERENCES " + policy::FolderTable::Name +
"(id_folder) ON DELETE CASCADE,"
"FOREIGN KEY (device_id) REFERENCES " + policy::DeviceTable::Name +
"(id_device) ON DELETE CASCADE,"
"UNIQUE(path, device_id) ON CONFLICT FAIL"
")";
std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_device_present AFTER UPDATE OF is_present ON "
+ policy::DeviceTable::Name +
" BEGIN"
" UPDATE " + policy::FolderTable::Name + " SET is_present = new.is_present WHERE device_id = new.id_device;"
" END";
return sqlite::Tools::executeRequest( connection, req ) &&
sqlite::Tools::executeRequest( connection, triggerReq );
}
std::shared_ptr<Folder> Folder::create( DBConnection connection, const std::string& fullPath, unsigned int parentId, Device& device, fs::IDevice& deviceFs )
{
std::string path;
if ( device.isRemovable() == true )
path = utils::file::removePath( fullPath, deviceFs.mountpoint() );
else
path = fullPath;
auto self = std::make_shared<Folder>( path, parentId, device.id(), device.isRemovable() );
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, parent_id, device_id, is_removable) VALUES(?, ?, ?, ?)";
if ( insert( connection, self, req, path, sqlite::ForeignKey( parentId ), device.id(), device.isRemovable() ) == false )
return nullptr;
self->m_dbConection = connection;
if ( device.isRemovable() == true )
{
self->m_deviceMountpoint = deviceFs.mountpoint();
self->m_fullPath = self->m_deviceMountpoint.get() + path;
}
return self;
}
bool Folder::blacklist( DBConnection connection, const std::string& fullPath )
{
auto f = fromPath( connection, fullPath );
if ( f != nullptr )
{
// Let the foreign key destroy everything beneath this folder
destroy( connection, f->id() );
}
auto folderFs = FsFactory->createDirectory( fullPath );
if ( folderFs == nullptr )
return false;
auto deviceFs = folderFs->device();
auto device = Device::fromUuid( connection, deviceFs->uuid() );
if ( device == nullptr )
device = Device::create( connection, deviceFs->uuid(), deviceFs->isRemovable() );
std::string path;
if ( deviceFs->isRemovable() == true )
path = utils::file::removePath( fullPath, deviceFs->mountpoint() );
else
path = fullPath;
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, parent_id, is_blacklisted, device_id, is_removable) VALUES(?, ?, ?, ?, ?)";
return sqlite::Tools::insert( connection, req, path, nullptr, true, device->id(), deviceFs->isRemovable() ) != 0;
}
void Folder::setFileSystemFactory( std::shared_ptr<factory::IFileSystem> fsFactory )
{
FsFactory = fsFactory;
}
std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath )
{
return fromPath( conn, fullPath, false );
}
std::shared_ptr<Folder> Folder::blacklistedFolder( DBConnection conn, const std::string& fullPath )
{
return fromPath( conn, fullPath, true );
}
std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath, bool blacklisted )
{
auto folderFs = FsFactory->createDirectory( fullPath );
if ( folderFs == nullptr )
return nullptr;
auto deviceFs = folderFs->device();
if ( deviceFs == nullptr )
{
LOG_ERROR( "Failed to get device containing an existing folder: ", fullPath );
return nullptr;
}
if ( deviceFs->isRemovable() == false )
{
std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND is_removable = 0 AND is_blacklisted = ?";
return fetch( conn, req, fullPath, blacklisted );
}
std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND device_id = ? AND is_blacklisted = ?";
auto device = Device::fromUuid( conn, deviceFs->uuid() );
// We are trying to find a folder. If we don't know the device it's on, we don't know the folder.
if ( device == nullptr )
return nullptr;
auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() );
auto folder = fetch( conn, req, path, device->id(), blacklisted );
if ( folder == nullptr )
return nullptr;
folder->m_deviceMountpoint = deviceFs->mountpoint();
folder->m_fullPath = folder->m_deviceMountpoint.get() + path;
return folder;
}
unsigned int Folder::id() const
{
return m_id;
}
const std::string& Folder::path() const
{
if ( m_isRemovable == false )
return m_path;
auto lock = m_deviceMountpoint.lock();
if ( m_deviceMountpoint.isCached() == true )
return m_fullPath;
auto device = Device::fetch( m_dbConection, m_deviceId );
auto deviceFs = FsFactory->createDevice( device->uuid() );
m_deviceMountpoint = deviceFs->mountpoint();
m_fullPath = m_deviceMountpoint.get() + m_path;
return m_fullPath;
}
std::vector<std::shared_ptr<File>> Folder::files()
{
static const std::string req = "SELECT * FROM " + policy::FileTable::Name +
" WHERE folder_id = ?";
return File::fetchAll<File>( m_dbConection, req, m_id );
}
std::vector<std::shared_ptr<Folder>> Folder::folders()
{
return fetchAll( m_dbConection, m_id );
}
std::shared_ptr<Folder> Folder::parent()
{
return fetch( m_dbConection, m_parent );
}
unsigned int Folder::deviceId() const
{
return m_deviceId;
}
bool Folder::isPresent() const
{
return m_isPresent;
}
std::vector<std::shared_ptr<Folder>> Folder::fetchAll( DBConnection dbConn, unsigned int parentFolderId )
{
if ( parentFolderId == 0 )
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
+ " WHERE parent_id IS NULL AND is_blacklisted = 0 AND is_present = 1";
return DatabaseHelpers::fetchAll<Folder>( dbConn, req );
}
else
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
+ " WHERE parent_id = ? AND is_blacklisted = 0 AND is_present = 1";
return DatabaseHelpers::fetchAll<Folder>( dbConn, req, parentFolderId );
}
}
<commit_msg>Folder: blacklist: Explicitely use a boolean<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "File.h"
#include "Folder.h"
#include "Device.h"
#include "Media.h"
#include "database/SqliteTools.h"
#include "filesystem/IDirectory.h"
#include "filesystem/IDevice.h"
#include "utils/Filename.h"
#include <unordered_map>
namespace policy
{
const std::string FolderTable::Name = "Folder";
const std::string FolderTable::PrimaryKeyColumn = "id_folder";
unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id;
}
std::shared_ptr<factory::IFileSystem> Folder::FsFactory;
Folder::Folder( DBConnection dbConnection, sqlite::Row& row )
: m_dbConection( dbConnection )
{
row >> m_id
>> m_path
>> m_parent
>> m_isBlacklisted
>> m_deviceId
>> m_isPresent
>> m_isRemovable;
}
Folder::Folder( const std::string& path, unsigned int parent, unsigned int deviceId, bool isRemovable )
: m_id( 0 )
, m_path( path )
, m_parent( parent )
, m_isBlacklisted( false )
, m_deviceId( deviceId )
, m_isPresent( true )
, m_isRemovable( isRemovable )
{
}
bool Folder::createTable(DBConnection connection)
{
std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name +
"("
"id_folder INTEGER PRIMARY KEY AUTOINCREMENT,"
"path TEXT,"
"parent_id UNSIGNED INTEGER,"
"is_blacklisted BOOLEAN NOT NULL DEFAULT 0,"
"device_id UNSIGNED INTEGER,"
"is_present BOOLEAN NOT NULL DEFAULT 1,"
"is_removable BOOLEAN NOT NULL,"
"FOREIGN KEY (parent_id) REFERENCES " + policy::FolderTable::Name +
"(id_folder) ON DELETE CASCADE,"
"FOREIGN KEY (device_id) REFERENCES " + policy::DeviceTable::Name +
"(id_device) ON DELETE CASCADE,"
"UNIQUE(path, device_id) ON CONFLICT FAIL"
")";
std::string triggerReq = "CREATE TRIGGER IF NOT EXISTS is_device_present AFTER UPDATE OF is_present ON "
+ policy::DeviceTable::Name +
" BEGIN"
" UPDATE " + policy::FolderTable::Name + " SET is_present = new.is_present WHERE device_id = new.id_device;"
" END";
return sqlite::Tools::executeRequest( connection, req ) &&
sqlite::Tools::executeRequest( connection, triggerReq );
}
std::shared_ptr<Folder> Folder::create( DBConnection connection, const std::string& fullPath, unsigned int parentId, Device& device, fs::IDevice& deviceFs )
{
std::string path;
if ( device.isRemovable() == true )
path = utils::file::removePath( fullPath, deviceFs.mountpoint() );
else
path = fullPath;
auto self = std::make_shared<Folder>( path, parentId, device.id(), device.isRemovable() );
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, parent_id, device_id, is_removable) VALUES(?, ?, ?, ?)";
if ( insert( connection, self, req, path, sqlite::ForeignKey( parentId ), device.id(), device.isRemovable() ) == false )
return nullptr;
self->m_dbConection = connection;
if ( device.isRemovable() == true )
{
self->m_deviceMountpoint = deviceFs.mountpoint();
self->m_fullPath = self->m_deviceMountpoint.get() + path;
}
return self;
}
bool Folder::blacklist( DBConnection connection, const std::string& fullPath )
{
auto f = fromPath( connection, fullPath );
if ( f != nullptr )
{
// Let the foreign key destroy everything beneath this folder
destroy( connection, f->id() );
}
auto folderFs = FsFactory->createDirectory( fullPath );
if ( folderFs == nullptr )
return false;
auto deviceFs = folderFs->device();
auto device = Device::fromUuid( connection, deviceFs->uuid() );
if ( device == nullptr )
device = Device::create( connection, deviceFs->uuid(), deviceFs->isRemovable() );
std::string path;
if ( deviceFs->isRemovable() == true )
path = utils::file::removePath( fullPath, deviceFs->mountpoint() );
else
path = fullPath;
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, parent_id, is_blacklisted, device_id, is_removable) VALUES(?, ?, ?, ?, ?)";
return sqlite::Tools::insert( connection, req, path, nullptr, true, device->id(), deviceFs->isRemovable() ) != 0;
}
void Folder::setFileSystemFactory( std::shared_ptr<factory::IFileSystem> fsFactory )
{
FsFactory = fsFactory;
}
std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath )
{
return fromPath( conn, fullPath, false );
}
std::shared_ptr<Folder> Folder::blacklistedFolder( DBConnection conn, const std::string& fullPath )
{
return fromPath( conn, fullPath, true );
}
std::shared_ptr<Folder> Folder::fromPath( DBConnection conn, const std::string& fullPath, bool blacklisted )
{
auto folderFs = FsFactory->createDirectory( fullPath );
if ( folderFs == nullptr )
return nullptr;
auto deviceFs = folderFs->device();
if ( deviceFs == nullptr )
{
LOG_ERROR( "Failed to get device containing an existing folder: ", fullPath );
return nullptr;
}
if ( deviceFs->isRemovable() == false )
{
std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND is_removable = 0 AND is_blacklisted = ?";
return fetch( conn, req, fullPath, blacklisted );
}
std::string req = "SELECT * FROM " + policy::FolderTable::Name + " WHERE path = ? AND device_id = ? AND is_blacklisted = ?";
auto device = Device::fromUuid( conn, deviceFs->uuid() );
// We are trying to find a folder. If we don't know the device it's on, we don't know the folder.
if ( device == nullptr )
return nullptr;
auto path = utils::file::removePath( fullPath, deviceFs->mountpoint() );
auto folder = fetch( conn, req, path, device->id(), blacklisted );
if ( folder == nullptr )
return nullptr;
folder->m_deviceMountpoint = deviceFs->mountpoint();
folder->m_fullPath = folder->m_deviceMountpoint.get() + path;
return folder;
}
unsigned int Folder::id() const
{
return m_id;
}
const std::string& Folder::path() const
{
if ( m_isRemovable == false )
return m_path;
auto lock = m_deviceMountpoint.lock();
if ( m_deviceMountpoint.isCached() == true )
return m_fullPath;
auto device = Device::fetch( m_dbConection, m_deviceId );
auto deviceFs = FsFactory->createDevice( device->uuid() );
m_deviceMountpoint = deviceFs->mountpoint();
m_fullPath = m_deviceMountpoint.get() + m_path;
return m_fullPath;
}
std::vector<std::shared_ptr<File>> Folder::files()
{
static const std::string req = "SELECT * FROM " + policy::FileTable::Name +
" WHERE folder_id = ?";
return File::fetchAll<File>( m_dbConection, req, m_id );
}
std::vector<std::shared_ptr<Folder>> Folder::folders()
{
return fetchAll( m_dbConection, m_id );
}
std::shared_ptr<Folder> Folder::parent()
{
return fetch( m_dbConection, m_parent );
}
unsigned int Folder::deviceId() const
{
return m_deviceId;
}
bool Folder::isPresent() const
{
return m_isPresent;
}
std::vector<std::shared_ptr<Folder>> Folder::fetchAll( DBConnection dbConn, unsigned int parentFolderId )
{
if ( parentFolderId == 0 )
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
+ " WHERE parent_id IS NULL AND is_blacklisted = 0 AND is_present = 1";
return DatabaseHelpers::fetchAll<Folder>( dbConn, req );
}
else
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name
+ " WHERE parent_id = ? AND is_blacklisted = 0 AND is_present = 1";
return DatabaseHelpers::fetchAll<Folder>( dbConn, req, parentFolderId );
}
}
<|endoftext|>
|
<commit_before>#pragma once
/*
* Factories for variable names.
*/
#include <crab/common/types.hpp>
#include <boost/optional.hpp>
#include <boost/range/iterator_range.hpp>
#include <limits>
#include <unordered_map>
#include <vector>
#include <functional>
namespace crab {
namespace cfg {
namespace var_factory_impl {
namespace indexed_string_impl {
template<typename T>
inline std::string get_str(T e);
template<> inline std::string get_str(std::string e) { return e; }
}
// This variable factory creates a new variable associated to an
// element of type T. It can also create variables that are not
// associated to an element of type T. We call them shadow variables.
//
// The factory uses a counter of type index_t to generate variable
// id's that always increases.
template<class T>
class variable_factory {
typedef variable_factory<T> variable_factory_t;
public:
class indexed_string {
template<typename Any>
friend class variable_factory;
public:
// FIXME: we should use some unlimited precision type to avoid
// overflow. However, this change is a bit involving since we
// need to change the algorithm api's in patricia_trees.hpp because
// they assume ikos::index_t.
typedef ikos::index_t index_t;
private:
boost::optional<T> _s;
index_t _id;
std::string _name; // optional string name associated with _id
variable_factory* _vfac;
// NOT IMPLEMENTED
indexed_string();
indexed_string(index_t id, variable_factory *vfac, std::string name = "")
: _id(id), _name(name), _vfac(vfac) { }
indexed_string(T s, index_t id, variable_factory *vfac)
: _s(s), _id(id), _name(""), _vfac(vfac) { }
public:
~indexed_string() {}
indexed_string(const indexed_string& is)
: _s(is._s), _id(is._id), _name(is._name), _vfac(is._vfac) { }
indexed_string& operator=(const indexed_string& is) {
if (this != &is) {
_s = is._s;
_id = is._id;
_name = is._name;
_vfac = is._vfac;
}
return *this;
}
index_t index() const { return this->_id; }
std::string str() const {
if (_s) {
return indexed_string_impl::get_str<T>(*_s);
} else {
if (_name != "") {
return _name;
} else {
// unlikely prefix
return "@V_" + std::to_string(_id);
}
}
}
boost::optional<T> get() const{
return _s ? *_s : boost::optional<T>();
}
variable_factory& get_var_factory() { return *_vfac; }
bool operator<(indexed_string s) const
{ return (_id < s._id); }
bool operator==(indexed_string s) const
{ return (_id == s._id);}
void write(crab_os& o) const
{ o << str(); }
friend crab_os& operator<<(crab_os& o, indexed_string s) {
o << s.str();
return o;
}
friend size_t hash_value(indexed_string s) {
std::hash<index_t> hasher;
return hasher(s.index());
}
};
public:
typedef typename indexed_string::index_t index_t;
private:
typedef std::unordered_map<T, indexed_string> t_map_t;
typedef std::unordered_map<index_t, indexed_string> shadow_map_t;
index_t _next_id;
t_map_t _map;
shadow_map_t _shadow_map;
std::vector<indexed_string> _shadow_vars;
index_t get_and_increment_id(void) {
if (_next_id == std::numeric_limits<index_t>::max()) {
CRAB_ERROR("Reached limit of ", std::numeric_limits<index_t>::max(),
" variables");
}
index_t res = _next_id;
++_next_id;
return res;
}
public:
typedef indexed_string varname_t;
typedef boost::iterator_range
<typename std::vector<indexed_string>::iterator> var_range;
typedef boost::iterator_range
<typename std::vector<indexed_string>::const_iterator> const_var_range;
public:
variable_factory(): _next_id(1) {}
variable_factory(index_t start_id): _next_id(start_id) { }
variable_factory(const variable_factory_t& o) = delete;
variable_factory_t& operator=(const variable_factory_t& o) = delete;
virtual ~variable_factory() {}
// hook for generating indexed_string's without being
// associated with a particular T (w/o caching).
// XXX: do not use it unless strictly necessary.
virtual indexed_string get() {
indexed_string is(get_and_increment_id(), this);
_shadow_vars.push_back(is);
return is;
}
// generate a shadow indexed_string's associated to some key
virtual indexed_string get(index_t key, std::string name = "") {
auto it = _shadow_map.find(key);
if (it == _shadow_map.end()) {
indexed_string is(get_and_increment_id(), this, name);
_shadow_map.insert(typename shadow_map_t::value_type(key, is));
_shadow_vars.push_back(is);
return is;
} else {
return it->second;
}
}
virtual indexed_string operator[](T s) {
auto it = _map.find(s);
if (it == _map.end()) {
indexed_string is(s, get_and_increment_id(), this);
_map.insert(typename t_map_t::value_type(s, is));
return is;
} else {
return it->second;
}
}
// return all the shadow variables created by the factory.
virtual const_var_range get_shadow_vars() const {
return boost::make_iterator_range(_shadow_vars.begin(),
_shadow_vars.end());
}
};
//! Specialized factory for strings
class str_variable_factory : public variable_factory<std::string> {
typedef variable_factory<std::string> variable_factory_t;
public:
typedef variable_factory_t::varname_t varname_t;
typedef variable_factory_t::const_var_range const_var_range;
typedef variable_factory_t::index_t index_t;
str_variable_factory(): variable_factory_t() { }
};
//! Specialized factory for integers
class int_variable_factory {
public:
typedef int varname_t;
int_variable_factory() {}
int_variable_factory(const int_variable_factory& o) = delete;
int_variable_factory& operator=(const int_variable_factory& o) = delete;
varname_t operator[](int v) { return v; }
};
inline int fresh_colour(int col_x, int col_y) {
switch(col_x) {
case 0: return col_y == 1 ? 2 : 1;
case 1: return col_y == 0 ? 2 : 0;
case 2: return col_y == 0 ? 1 : 0;
default: CRAB_ERROR("Unreachable");
}
}
//! Three-coloured variable allocation. So the number of variables
// is bounded by 3|Tbl|, rather than always increasing.
class str_var_alloc_col {
static const char** col_prefix;
public:
typedef str_variable_factory::varname_t varname_t;
static str_variable_factory vfac;
str_var_alloc_col()
: colour(0), next_id(0)
{ }
str_var_alloc_col(const str_var_alloc_col& o)
: colour(o.colour), next_id(o.next_id)
{ }
str_var_alloc_col(const str_var_alloc_col& x, const str_var_alloc_col& y)
: colour(fresh_colour(x.colour, y.colour)),
next_id(0) {
assert(colour != x.colour);
assert(colour != y.colour);
}
str_var_alloc_col& operator=(const str_var_alloc_col& x) {
colour = x.colour;
next_id = x.next_id;
return *this;
}
str_variable_factory::varname_t next() {
std::string v = col_prefix[colour] + std::to_string(next_id++);
return vfac[v];
}
protected:
int colour;
int next_id;
};
class int_var_alloc_col {
public:
typedef int varname_t;
static int_variable_factory vfac;
int_var_alloc_col()
: colour(0), next_id(0)
{ }
int_var_alloc_col(const int_var_alloc_col& o)
: colour(o.colour), next_id(o.next_id)
{ }
int_var_alloc_col(const int_var_alloc_col& x, const int_var_alloc_col& y)
: colour(fresh_colour(x.colour, y.colour)),
next_id(0) {
assert(colour != x.colour);
assert(colour != y.colour);
}
int_var_alloc_col& operator=(const int_var_alloc_col& x) {
colour = x.colour;
next_id = x.next_id;
return *this;
}
int_variable_factory::varname_t next() {
int id = next_id++;
return 3*id + colour;
}
protected:
int colour;
int next_id;
};
} // end namespace var_factory_impl
} // end namespace cfg
} // end namespace crab
<commit_msg>Argument to create a fresh indexed_string with a name<commit_after>#pragma once
/*
* Factories for variable names.
*/
#include <crab/common/types.hpp>
#include <boost/optional.hpp>
#include <boost/range/iterator_range.hpp>
#include <limits>
#include <unordered_map>
#include <vector>
#include <functional>
namespace crab {
namespace cfg {
namespace var_factory_impl {
namespace indexed_string_impl {
template<typename T>
inline std::string get_str(T e);
template<> inline std::string get_str(std::string e) { return e; }
}
// This variable factory creates a new variable associated to an
// element of type T. It can also create variables that are not
// associated to an element of type T. We call them shadow variables.
//
// The factory uses a counter of type index_t to generate variable
// id's that always increases.
template<class T>
class variable_factory {
typedef variable_factory<T> variable_factory_t;
public:
class indexed_string {
template<typename Any>
friend class variable_factory;
public:
// FIXME: we should use some unlimited precision type to avoid
// overflow. However, this change is a bit involving since we
// need to change the algorithm api's in patricia_trees.hpp because
// they assume ikos::index_t.
typedef ikos::index_t index_t;
private:
boost::optional<T> _s;
index_t _id;
std::string _name; // optional string name associated with _id
variable_factory* _vfac;
// NOT IMPLEMENTED
indexed_string();
indexed_string(index_t id, variable_factory *vfac, std::string name = "")
: _id(id), _name(name), _vfac(vfac) { }
indexed_string(T s, index_t id, variable_factory *vfac)
: _s(s), _id(id), _name(""), _vfac(vfac) { }
public:
~indexed_string() {}
indexed_string(const indexed_string& is)
: _s(is._s), _id(is._id), _name(is._name), _vfac(is._vfac) { }
indexed_string& operator=(const indexed_string& is) {
if (this != &is) {
_s = is._s;
_id = is._id;
_name = is._name;
_vfac = is._vfac;
}
return *this;
}
index_t index() const { return this->_id; }
std::string str() const {
if (_s) {
return indexed_string_impl::get_str<T>(*_s);
} else {
if (_name != "") {
return _name;
} else {
// unlikely prefix
return "@V_" + std::to_string(_id);
}
}
}
boost::optional<T> get() const{
return _s ? *_s : boost::optional<T>();
}
variable_factory& get_var_factory() { return *_vfac; }
bool operator<(indexed_string s) const
{ return (_id < s._id); }
bool operator==(indexed_string s) const
{ return (_id == s._id);}
void write(crab_os& o) const
{ o << str(); }
friend crab_os& operator<<(crab_os& o, indexed_string s) {
o << s.str();
return o;
}
friend size_t hash_value(indexed_string s) {
std::hash<index_t> hasher;
return hasher(s.index());
}
};
public:
typedef typename indexed_string::index_t index_t;
private:
typedef std::unordered_map<T, indexed_string> t_map_t;
typedef std::unordered_map<index_t, indexed_string> shadow_map_t;
index_t _next_id;
t_map_t _map;
shadow_map_t _shadow_map;
std::vector<indexed_string> _shadow_vars;
index_t get_and_increment_id(void) {
if (_next_id == std::numeric_limits<index_t>::max()) {
CRAB_ERROR("Reached limit of ", std::numeric_limits<index_t>::max(),
" variables");
}
index_t res = _next_id;
++_next_id;
return res;
}
public:
typedef indexed_string varname_t;
typedef boost::iterator_range
<typename std::vector<indexed_string>::iterator> var_range;
typedef boost::iterator_range
<typename std::vector<indexed_string>::const_iterator> const_var_range;
public:
variable_factory(): _next_id(1) {}
variable_factory(index_t start_id): _next_id(start_id) { }
variable_factory(const variable_factory_t& o) = delete;
variable_factory_t& operator=(const variable_factory_t& o) = delete;
virtual ~variable_factory() {}
// hook for generating indexed_string's without being
// associated with a particular T (w/o caching).
// XXX: do not use it unless strictly necessary.
virtual indexed_string get(std::string name = "") {
indexed_string is(get_and_increment_id(), this, name);
_shadow_vars.push_back(is);
return is;
}
// generate a shadow indexed_string's associated to some key
virtual indexed_string get(index_t key, std::string name = "") {
auto it = _shadow_map.find(key);
if (it == _shadow_map.end()) {
indexed_string is(get_and_increment_id(), this, name);
_shadow_map.insert(typename shadow_map_t::value_type(key, is));
_shadow_vars.push_back(is);
return is;
} else {
return it->second;
}
}
virtual indexed_string operator[](T s) {
auto it = _map.find(s);
if (it == _map.end()) {
indexed_string is(s, get_and_increment_id(), this);
_map.insert(typename t_map_t::value_type(s, is));
return is;
} else {
return it->second;
}
}
// return all the shadow variables created by the factory.
virtual const_var_range get_shadow_vars() const {
return boost::make_iterator_range(_shadow_vars.begin(),
_shadow_vars.end());
}
};
//! Specialized factory for strings
class str_variable_factory : public variable_factory<std::string> {
typedef variable_factory<std::string> variable_factory_t;
public:
typedef variable_factory_t::varname_t varname_t;
typedef variable_factory_t::const_var_range const_var_range;
typedef variable_factory_t::index_t index_t;
str_variable_factory(): variable_factory_t() { }
};
//! Specialized factory for integers
class int_variable_factory {
public:
typedef int varname_t;
int_variable_factory() {}
int_variable_factory(const int_variable_factory& o) = delete;
int_variable_factory& operator=(const int_variable_factory& o) = delete;
varname_t operator[](int v) { return v; }
};
inline int fresh_colour(int col_x, int col_y) {
switch(col_x) {
case 0: return col_y == 1 ? 2 : 1;
case 1: return col_y == 0 ? 2 : 0;
case 2: return col_y == 0 ? 1 : 0;
default: CRAB_ERROR("Unreachable");
}
}
//! Three-coloured variable allocation. So the number of variables
// is bounded by 3|Tbl|, rather than always increasing.
class str_var_alloc_col {
static const char** col_prefix;
public:
typedef str_variable_factory::varname_t varname_t;
static str_variable_factory vfac;
str_var_alloc_col()
: colour(0), next_id(0)
{ }
str_var_alloc_col(const str_var_alloc_col& o)
: colour(o.colour), next_id(o.next_id)
{ }
str_var_alloc_col(const str_var_alloc_col& x, const str_var_alloc_col& y)
: colour(fresh_colour(x.colour, y.colour)),
next_id(0) {
assert(colour != x.colour);
assert(colour != y.colour);
}
str_var_alloc_col& operator=(const str_var_alloc_col& x) {
colour = x.colour;
next_id = x.next_id;
return *this;
}
str_variable_factory::varname_t next() {
std::string v = col_prefix[colour] + std::to_string(next_id++);
return vfac[v];
}
protected:
int colour;
int next_id;
};
class int_var_alloc_col {
public:
typedef int varname_t;
static int_variable_factory vfac;
int_var_alloc_col()
: colour(0), next_id(0)
{ }
int_var_alloc_col(const int_var_alloc_col& o)
: colour(o.colour), next_id(o.next_id)
{ }
int_var_alloc_col(const int_var_alloc_col& x, const int_var_alloc_col& y)
: colour(fresh_colour(x.colour, y.colour)),
next_id(0) {
assert(colour != x.colour);
assert(colour != y.colour);
}
int_var_alloc_col& operator=(const int_var_alloc_col& x) {
colour = x.colour;
next_id = x.next_id;
return *this;
}
int_variable_factory::varname_t next() {
int id = next_id++;
return 3*id + colour;
}
protected:
int colour;
int next_id;
};
} // end namespace var_factory_impl
} // end namespace cfg
} // end namespace crab
<|endoftext|>
|
<commit_before>/**
* \file
* \brief ThreadBase class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-03-14
*/
#ifndef INCLUDE_DISTORTOS_THREADBASE_HPP_
#define INCLUDE_DISTORTOS_THREADBASE_HPP_
#include "distortos/scheduler/ThreadControlBlock.hpp"
#include "distortos/Semaphore.hpp"
namespace distortos
{
/// ThreadBase class is a base for threads
class ThreadBase
{
public:
/**
* \brief ThreadBase's constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will
* be added, nullptr to inherit thread group from currently running thread
* \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception
* of signals for this thread
*/
ThreadBase(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy,
scheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);
/**
* \brief ThreadBase's constructor.
*
* \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will
* be added, nullptr to inherit thread group from currently running thread
* \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception
* of signals for this thread
*/
ThreadBase(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy,
scheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);
/**
* \brief Generates signal for thread.
*
* Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
*
* Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be
* unblocked.
*
* \param [in] signalNumber is the signal that will be generated, [0; 31]
*
* \return 0 on success, error code otherwise:
* - EINVAL - \a signalNumber value is invalid;
* - ENOTSUP - reception of signals is disabled for this thread;
*/
int generateSignal(const uint8_t signalNumber)
{
return threadControlBlock_.generateSignal(signalNumber);
}
/**
* \return effective priority of thread
*/
uint8_t getEffectivePriority() const
{
return threadControlBlock_.getEffectivePriority();
}
/**
* \brief Gets set of currently pending signals.
*
* Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html
*
* This function shall return the set of signals that are blocked from delivery and are pending on the thread.
*
* \return set of currently pending signals
*/
SignalSet getPendingSignalSet() const
{
return threadControlBlock_.getPendingSignalSet();
}
/**
* \return priority of thread
*/
uint8_t getPriority() const
{
return threadControlBlock_.getPriority();
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return threadControlBlock_.getSchedulingPolicy();
}
/**
* \return current state of thread
*/
scheduler::ThreadControlBlock::State getState() const
{
return threadControlBlock_.getState();
}
/**
* \brief Waits for thread termination.
*
* Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join
* Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html
*
* Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to
* join() on the same target thread are undefined.
*
* \return 0 on success, error code otherwise:
* - EDEADLK - deadlock condition was detected,
* - EINVAL - this thread is not joinable,
* - ...
*/
int join();
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(const uint8_t priority, const bool alwaysBehind = {})
{
threadControlBlock_.setPriority(priority, alwaysBehind);
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(const SchedulingPolicy schedulingPolicy)
{
threadControlBlock_.setSchedulingPolicy(schedulingPolicy);
}
/**
* \brief Starts the thread.
*
* This operation can be performed on threads in "New" state only.
*
* \return 0 on success, error code otherwise:
* - EINVAL - thread is already started;
* - error codes returned by scheduler::Scheduler::add();
*/
int start();
ThreadBase(const ThreadBase&) = delete;
ThreadBase(ThreadBase&&) = default;
const ThreadBase& operator=(const ThreadBase&) = delete;
ThreadBase& operator=(ThreadBase&&) = delete;
protected:
/**
* \brief ThreadBase's destructor
*
* \note Polymorphic objects of ThreadBase type must not be deleted via pointer/reference
*/
~ThreadBase()
{
}
/**
* \return reference to internal ThreadControlBlock object
*/
scheduler::ThreadControlBlock& getThreadControlBlock()
{
return threadControlBlock_;
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadBase is a reference to ThreadBase object that is being run
*/
static void threadRunner(ThreadBase& threadBase) __attribute__ ((noreturn));
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes, from Scheduler::remove().
*/
void terminationHook();
/// internal ThreadControlBlock object
scheduler::ThreadControlBlock threadControlBlock_;
/// semaphore used by join()
Semaphore joinSemaphore_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_THREADBASE_HPP_
<commit_msg>ThreadBase::getPendingSignalSet(): use SignalsReceiverControlBlock::getPendingSignalSet() instead of ThreadControlBlock::getPendingSignalSet()<commit_after>/**
* \file
* \brief ThreadBase class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-03-14
*/
#ifndef INCLUDE_DISTORTOS_THREADBASE_HPP_
#define INCLUDE_DISTORTOS_THREADBASE_HPP_
#include "distortos/scheduler/ThreadControlBlock.hpp"
#include "distortos/signals/SignalsReceiverControlBlock.hpp"
#include "distortos/Semaphore.hpp"
namespace distortos
{
/// ThreadBase class is a base for threads
class ThreadBase
{
public:
/**
* \brief ThreadBase's constructor.
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will
* be added, nullptr to inherit thread group from currently running thread
* \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception
* of signals for this thread
*/
ThreadBase(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy,
scheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);
/**
* \brief ThreadBase's constructor.
*
* \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will
* be added, nullptr to inherit thread group from currently running thread
* \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception
* of signals for this thread
*/
ThreadBase(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy,
scheduler::ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver);
/**
* \brief Generates signal for thread.
*
* Similar to pthread_kill() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_kill.html
*
* Adds the signalNumber to set of pending signals. If this thread is currently waiting for this signal, it will be
* unblocked.
*
* \param [in] signalNumber is the signal that will be generated, [0; 31]
*
* \return 0 on success, error code otherwise:
* - EINVAL - \a signalNumber value is invalid;
* - ENOTSUP - reception of signals is disabled for this thread;
*/
int generateSignal(const uint8_t signalNumber)
{
return threadControlBlock_.generateSignal(signalNumber);
}
/**
* \return effective priority of thread
*/
uint8_t getEffectivePriority() const
{
return threadControlBlock_.getEffectivePriority();
}
/**
* \brief Gets set of currently pending signals.
*
* Similar to sigpending() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigpending.html
*
* This function shall return the set of signals that are blocked from delivery and are pending on the thread.
*
* \return set of currently pending signals
*/
SignalSet getPendingSignalSet() const
{
const auto signalsReceiverControlBlock = threadControlBlock_.getSignalsReceiverControlBlock();
if (signalsReceiverControlBlock == nullptr)
return SignalSet{SignalSet::empty};
return signalsReceiverControlBlock->getPendingSignalSet();
}
/**
* \return priority of thread
*/
uint8_t getPriority() const
{
return threadControlBlock_.getPriority();
}
/**
* \return scheduling policy of the thread
*/
SchedulingPolicy getSchedulingPolicy() const
{
return threadControlBlock_.getSchedulingPolicy();
}
/**
* \return current state of thread
*/
scheduler::ThreadControlBlock::State getState() const
{
return threadControlBlock_.getState();
}
/**
* \brief Waits for thread termination.
*
* Similar to std::thread::join() - http://en.cppreference.com/w/cpp/thread/thread/join
* Similar to POSIX pthread_join() - http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html
*
* Blocks current thread until this thread finishes its execution. The results of multiple simultaneous calls to
* join() on the same target thread are undefined.
*
* \return 0 on success, error code otherwise:
* - EDEADLK - deadlock condition was detected,
* - EINVAL - this thread is not joinable,
* - ...
*/
int join();
/**
* \brief Changes priority of thread.
*
* If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
*
* \param [in] priority is the new priority of thread
* \param [in] alwaysBehind selects the method of ordering when lowering the priority
* - false - the thread is moved to the head of the group of threads with the new priority (default),
* - true - the thread is moved to the tail of the group of threads with the new priority.
*/
void setPriority(const uint8_t priority, const bool alwaysBehind = {})
{
threadControlBlock_.setPriority(priority, alwaysBehind);
}
/**
* param [in] schedulingPolicy is the new scheduling policy of the thread
*/
void setSchedulingPolicy(const SchedulingPolicy schedulingPolicy)
{
threadControlBlock_.setSchedulingPolicy(schedulingPolicy);
}
/**
* \brief Starts the thread.
*
* This operation can be performed on threads in "New" state only.
*
* \return 0 on success, error code otherwise:
* - EINVAL - thread is already started;
* - error codes returned by scheduler::Scheduler::add();
*/
int start();
ThreadBase(const ThreadBase&) = delete;
ThreadBase(ThreadBase&&) = default;
const ThreadBase& operator=(const ThreadBase&) = delete;
ThreadBase& operator=(ThreadBase&&) = delete;
protected:
/**
* \brief ThreadBase's destructor
*
* \note Polymorphic objects of ThreadBase type must not be deleted via pointer/reference
*/
~ThreadBase()
{
}
/**
* \return reference to internal ThreadControlBlock object
*/
scheduler::ThreadControlBlock& getThreadControlBlock()
{
return threadControlBlock_;
}
private:
/**
* \brief Thread runner function - entry point of threads.
*
* After return from actual thread function, thread is terminated, so this function never returns.
*
* \param [in] threadBase is a reference to ThreadBase object that is being run
*/
static void threadRunner(ThreadBase& threadBase) __attribute__ ((noreturn));
/**
* \brief "Run" function of thread
*
* This should be overridden by derived classes.
*/
virtual void run() = 0;
/**
* \brief Termination hook function of thread
*
* This function is called after run() completes, from Scheduler::remove().
*/
void terminationHook();
/// internal ThreadControlBlock object
scheduler::ThreadControlBlock threadControlBlock_;
/// semaphore used by join()
Semaphore joinSemaphore_;
};
} // namespace distortos
#endif // INCLUDE_DISTORTOS_THREADBASE_HPP_
<|endoftext|>
|
<commit_before>/*
* @file stream_encoder.hpp
*
* @brief Ellis TBD C++ header.
*/
#pragma once
#ifndef ELLIS_STREAM_ENCODER_HPP_
#define ELLIS_STREAM_ENCODER_HPP_
#include <ellis/defs.hpp>
#include <ellis/err.hpp>
#include <ellis/node.hpp>
#include <memory>
namespace ellis {
enum class encoding_status {
CONTINUE,
END,
ERROR
};
// aka serialize, aka output
class stream_encoder {
public:
/** This function is called by the data stream to tell the encoder it may
* encode up to bytecount bytes of data into the provided buffer.
*
* The callee should use up to the given size, as needed, for encoding, and
* update bytecount to reflect the amount of unused buffer space left over.
*
* If there has been a non-recoverable error in the encoding process, the
* ERROR status will be returned; otherwise, if an ellis node has been
* completely encoded, a status of END is returned; otherwise a status of
* CONTINUE will be returned (to indicate that additional space is needed
* for the encoding--to be provided via additional calls to fill_buffer).
*
* If a status of ERROR is returned, the get_error() function may be used to
* access the details of the error.
*
* If a status of END or ERROR is returned, then the decoder must be reset
* before any further calls to fill_buffer().
*/
virtual encoding_status fill_buffer(
byte *buf,
int *bytecount) = 0;
/** Return the error details. Caller owns it now.
*/
virtual std::unique_ptr<err> get_error() = 0;
/** Reset the encoder to start encoding new_node into output buffers. */
virtual void reset(const node *new_node) = 0;
virtual ~stream_encoder() {}
};
} /* namespace ellis */
#endif /* ELLIS_STREAM_ENCODER_HPP_ */
<commit_msg>stream_encoder: remove unnecessary #include<commit_after>/*
* @file stream_encoder.hpp
*
* @brief Ellis TBD C++ header.
*/
#pragma once
#ifndef ELLIS_STREAM_ENCODER_HPP_
#define ELLIS_STREAM_ENCODER_HPP_
#include <ellis/defs.hpp>
#include <ellis/err.hpp>
#include <ellis/node.hpp>
namespace ellis {
enum class encoding_status {
CONTINUE,
END,
ERROR
};
// aka serialize, aka output
class stream_encoder {
public:
/** This function is called by the data stream to tell the encoder it may
* encode up to bytecount bytes of data into the provided buffer.
*
* The callee should use up to the given size, as needed, for encoding, and
* update bytecount to reflect the amount of unused buffer space left over.
*
* If there has been a non-recoverable error in the encoding process, the
* ERROR status will be returned; otherwise, if an ellis node has been
* completely encoded, a status of END is returned; otherwise a status of
* CONTINUE will be returned (to indicate that additional space is needed
* for the encoding--to be provided via additional calls to fill_buffer).
*
* If a status of ERROR is returned, the get_error() function may be used to
* access the details of the error.
*
* If a status of END or ERROR is returned, then the decoder must be reset
* before any further calls to fill_buffer().
*/
virtual encoding_status fill_buffer(
byte *buf,
int *bytecount) = 0;
/** Return the error details. Caller owns it now.
*/
virtual std::unique_ptr<err> get_error() = 0;
/** Reset the encoder to start encoding new_node into output buffers. */
virtual void reset(const node *new_node) = 0;
virtual ~stream_encoder() {}
};
} /* namespace ellis */
#endif /* ELLIS_STREAM_ENCODER_HPP_ */
<|endoftext|>
|
<commit_before>#ifndef MATCH_HPP
#define MATCH_HPP
#include "engine/plugins/plugin_base.hpp"
#include "engine/map_matching/bayes_classifier.hpp"
#include "engine/object_encoder.hpp"
#include "engine/search_engine.hpp"
#include "engine/guidance/textual_route_annotation.hpp"
#include "engine/guidance/segment_list.hpp"
#include "engine/api_response_generator.hpp"
#include "engine/routing_algorithms/map_matching.hpp"
#include "util/compute_angle.hpp"
#include "util/integer_range.hpp"
#include "util/json_logger.hpp"
#include "util/json_util.hpp"
#include "util/string_util.hpp"
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
namespace osrm
{
namespace engine
{
namespace plugins
{
template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
using SubMatching = routing_algorithms::SubMatching;
using SubMatchingList = routing_algorithms::SubMatchingList;
using CandidateLists = routing_algorithms::CandidateLists;
using ClassifierT = map_matching::BayesClassifier<map_matching::LaplaceDistribution,
map_matching::LaplaceDistribution,
double>;
using TraceClassification = ClassifierT::ClassificationT;
public:
MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching)
: descriptor_string("match"), facade(facade),
max_locations_map_matching(max_locations_map_matching),
// the values where derived from fitting a laplace distribution
// to the values of manually classified traces
classifier(map_matching::LaplaceDistribution(0.005986, 0.016646),
map_matching::LaplaceDistribution(0.054385, 0.458432),
0.696774) // valid apriori probability
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
}
virtual ~MapMatchingPlugin() {}
const std::string GetDescriptor() const final override { return descriptor_string; }
TraceClassification
classify(const float trace_length, const float matched_length, const int removed_points) const
{
(void)removed_points; // unused
const double distance_feature = -std::log(trace_length) + std::log(matched_length);
// matched to the same point
if (!std::isfinite(distance_feature))
{
return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
}
const auto label_with_confidence = classifier.classify(distance_feature);
return label_with_confidence;
}
CandidateLists getCandidates(
const std::vector<util::FixedPointCoordinate> &input_coords,
const std::vector<std::pair<const int, const boost::optional<int>>> &input_bearings,
const double gps_precision,
std::vector<double> &sub_trace_lengths)
{
CandidateLists candidates_lists;
// assuming the gps_precision is the standart-diviation of normal distribution that models
// GPS noise (in this model) this should give us the correct candidate with >0.95
double query_radius = 3 * gps_precision;
double last_distance =
util::coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]);
sub_trace_lengths.resize(input_coords.size());
sub_trace_lengths[0] = 0;
for (const auto current_coordinate : util::irange<std::size_t>(0, input_coords.size()))
{
bool allow_uturn = false;
if (0 < current_coordinate)
{
last_distance = util::coordinate_calculation::haversineDistance(
input_coords[current_coordinate - 1], input_coords[current_coordinate]);
sub_trace_lengths[current_coordinate] +=
sub_trace_lengths[current_coordinate - 1] + last_distance;
}
if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate)
{
double turn_angle = util::ComputeAngle(input_coords[current_coordinate - 1],
input_coords[current_coordinate],
input_coords[current_coordinate + 1]);
// sharp turns indicate a possible uturn
if (turn_angle <= 90.0 || turn_angle >= 270.0)
{
allow_uturn = true;
}
}
// Use bearing values if supplied, otherwise fallback to 0,180 defaults
auto bearing = input_bearings.size() > 0 ? input_bearings[current_coordinate].first : 0;
auto range = input_bearings.size() > 0
? (input_bearings[current_coordinate].second
? *input_bearings[current_coordinate].second
: 10)
: 180;
auto candidates = facade->NearestPhantomNodesInRange(input_coords[current_coordinate],
query_radius, bearing, range);
if (candidates.size() == 0)
{
break;
}
// sort by forward id, then by reverse id and then by distance
std::sort(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.phantom_node.forward_node_id < rhs.phantom_node.forward_node_id ||
(lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
(lhs.phantom_node.reverse_node_id < rhs.phantom_node.reverse_node_id ||
(lhs.phantom_node.reverse_node_id ==
rhs.phantom_node.reverse_node_id &&
lhs.distance < rhs.distance)));
});
auto new_end = std::unique(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
lhs.phantom_node.reverse_node_id == rhs.phantom_node.reverse_node_id;
});
candidates.resize(new_end - candidates.begin());
if (!allow_uturn)
{
const auto compact_size = candidates.size();
for (const auto i : util::irange<std::size_t>(0, compact_size))
{
// Split edge if it is bidirectional and append reverse direction to end of list
if (candidates[i].phantom_node.forward_node_id != SPECIAL_NODEID &&
candidates[i].phantom_node.reverse_node_id != SPECIAL_NODEID)
{
PhantomNode reverse_node(candidates[i].phantom_node);
reverse_node.forward_node_id = SPECIAL_NODEID;
candidates.push_back(
PhantomNodeWithDistance{reverse_node, candidates[i].distance});
candidates[i].phantom_node.reverse_node_id = SPECIAL_NODEID;
}
}
}
// sort by distance to make pruning effective
std::sort(candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.distance < rhs.distance;
});
candidates_lists.push_back(std::move(candidates));
}
return candidates_lists;
}
util::json::Object submatchingToJSON(const SubMatching &sub,
const RouteParameters &route_parameters,
const InternalRouteResult &raw_route)
{
util::json::Object subtrace;
if (route_parameters.classify)
{
subtrace.values["confidence"] = sub.confidence;
}
auto response_generator = MakeApiResponseGenerator(facade);
subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route);
if (route_parameters.geometry || route_parameters.print_instructions)
{
using SegmentList = guidance::SegmentList<DataFacadeT>;
// Passing false to extract_alternative extracts the route.
const constexpr bool EXTRACT_ROUTE = false;
// by passing false to segment_list, we skip the douglas peucker simplification
// and mark all segments as necessary within the generation process
const constexpr bool NO_ROUTE_SIMPLIFICATION = false;
SegmentList segment_list(raw_route, EXTRACT_ROUTE, route_parameters.zoom_level,
NO_ROUTE_SIMPLIFICATION, facade);
if (route_parameters.geometry)
{
subtrace.values["geometry"] =
response_generator.GetGeometry(route_parameters.compression, segment_list);
}
if (route_parameters.print_instructions)
{
subtrace.values["instructions"] =
guidance::AnnotateRoute<DataFacadeT>(segment_list.Get(), facade);
}
util::json::Object json_route_summary;
json_route_summary.values["total_distance"] = segment_list.GetDistance();
json_route_summary.values["total_time"] = segment_list.GetDuration();
subtrace.values["route_summary"] = json_route_summary;
}
subtrace.values["indices"] = util::json::make_array(sub.indices);
util::json::Array points;
for (const auto &node : sub.nodes)
{
points.values.emplace_back(
util::json::make_array(node.location.lat / COORDINATE_PRECISION,
node.location.lon / COORDINATE_PRECISION));
}
subtrace.values["matched_points"] = points;
util::json::Array names;
for (const auto &node : sub.nodes)
{
names.values.emplace_back(facade->get_name_for_id(node.name_id));
}
subtrace.values["matched_names"] = names;
return subtrace;
}
Status HandleRequest(const RouteParameters &route_parameters,
util::json::Object &json_result) final override
{
// enforce maximum number of locations for performance reasons
if (max_locations_map_matching > 0 &&
static_cast<int>(route_parameters.coordinates.size()) > max_locations_map_matching)
{
json_result.values["status_message"] = "Too many coodindates";
return Status::Error;
}
// check number of parameters
if (!check_all_coordinates(route_parameters.coordinates))
{
json_result.values["status_message"] = "Invalid coordinates";
return Status::Error;
}
std::vector<double> sub_trace_lengths;
const auto &input_coords = route_parameters.coordinates;
const auto &input_timestamps = route_parameters.timestamps;
const auto &input_bearings = route_parameters.bearings;
if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size())
{
json_result.values["status_message"] =
"Number of timestamps does not match number of coordinates";
return Status::Error;
}
if (input_bearings.size() > 0 && input_coords.size() != input_bearings.size())
{
json_result.values["status_message"] =
"Number of bearings does not match number of coordinates";
return Status::Error;
}
// at least two coordinates are needed for map matching
if (static_cast<int>(input_coords.size()) < 2)
{
json_result.values["status_message"] = "At least two coordinates needed";
return Status::Error;
}
const auto candidates_lists = getCandidates(
input_coords, input_bearings, route_parameters.gps_precision, sub_trace_lengths);
if (candidates_lists.size() != input_coords.size())
{
BOOST_ASSERT(candidates_lists.size() < input_coords.size());
json_result.values["status_message"] =
std::string("Could not find a matching segment for coordinate ") +
std::to_string(candidates_lists.size());
return Status::NoSegment;
}
// setup logging if enabled
if (util::json::Logger::get())
util::json::Logger::get()->initialize("matching");
// call the actual map matching
SubMatchingList sub_matchings;
search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps,
route_parameters.matching_beta,
route_parameters.gps_precision, sub_matchings);
util::json::Array matchings;
for (auto &sub : sub_matchings)
{
// classify result
if (route_parameters.classify)
{
double trace_length =
sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()];
TraceClassification classification =
classify(trace_length, sub.length,
(sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size());
if (classification.first == ClassifierT::ClassLabel::POSITIVE)
{
sub.confidence = classification.second;
}
else
{
sub.confidence = 1 - classification.second;
}
}
BOOST_ASSERT(sub.nodes.size() > 1);
// FIXME we only run this to obtain the geometry
// The clean way would be to get this directly from the map matching plugin
InternalRouteResult raw_route;
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = sub.nodes[i];
current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
BOOST_ASSERT(current_phantom_node_pair.source_phantom.IsValid());
BOOST_ASSERT(current_phantom_node_pair.target_phantom.IsValid());
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates,
std::vector<bool>(raw_route.segment_end_coordinates.size() + 1, true), raw_route);
BOOST_ASSERT(raw_route.shortest_path_length != INVALID_EDGE_WEIGHT);
matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route));
}
if (util::json::Logger::get())
util::json::Logger::get()->render("matching", json_result);
json_result.values["matchings"] = matchings;
if (sub_matchings.empty())
{
json_result.values["status_message"] = "Cannot find matchings";
return Status::EmptyResult;
}
json_result.values["status_message"] = "Found matchings";
return Status::Ok;
}
private:
std::string descriptor_string;
DataFacadeT *facade;
int max_locations_map_matching;
ClassifierT classifier;
};
}
}
}
#endif // MATCH_HPP
<commit_msg>improve comments for gps_precision<commit_after>#ifndef MATCH_HPP
#define MATCH_HPP
#include "engine/plugins/plugin_base.hpp"
#include "engine/map_matching/bayes_classifier.hpp"
#include "engine/object_encoder.hpp"
#include "engine/search_engine.hpp"
#include "engine/guidance/textual_route_annotation.hpp"
#include "engine/guidance/segment_list.hpp"
#include "engine/api_response_generator.hpp"
#include "engine/routing_algorithms/map_matching.hpp"
#include "util/compute_angle.hpp"
#include "util/integer_range.hpp"
#include "util/json_logger.hpp"
#include "util/json_util.hpp"
#include "util/string_util.hpp"
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
namespace osrm
{
namespace engine
{
namespace plugins
{
template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
using SubMatching = routing_algorithms::SubMatching;
using SubMatchingList = routing_algorithms::SubMatchingList;
using CandidateLists = routing_algorithms::CandidateLists;
using ClassifierT = map_matching::BayesClassifier<map_matching::LaplaceDistribution,
map_matching::LaplaceDistribution,
double>;
using TraceClassification = ClassifierT::ClassificationT;
public:
MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching)
: descriptor_string("match"), facade(facade),
max_locations_map_matching(max_locations_map_matching),
// the values where derived from fitting a laplace distribution
// to the values of manually classified traces
classifier(map_matching::LaplaceDistribution(0.005986, 0.016646),
map_matching::LaplaceDistribution(0.054385, 0.458432),
0.696774) // valid apriori probability
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
}
virtual ~MapMatchingPlugin() {}
const std::string GetDescriptor() const final override { return descriptor_string; }
TraceClassification
classify(const float trace_length, const float matched_length, const int removed_points) const
{
(void)removed_points; // unused
const double distance_feature = -std::log(trace_length) + std::log(matched_length);
// matched to the same point
if (!std::isfinite(distance_feature))
{
return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
}
const auto label_with_confidence = classifier.classify(distance_feature);
return label_with_confidence;
}
CandidateLists getCandidates(
const std::vector<util::FixedPointCoordinate> &input_coords,
const std::vector<std::pair<const int, const boost::optional<int>>> &input_bearings,
const double gps_precision,
std::vector<double> &sub_trace_lengths)
{
CandidateLists candidates_lists;
// assuming gps_precision is the standard deviation of a normal distribution that
// models GPS noise (in this model), this should give us the correct search radius
// with > 99% confidence
double query_radius = 3 * gps_precision;
double last_distance =
util::coordinate_calculation::haversineDistance(input_coords[0], input_coords[1]);
sub_trace_lengths.resize(input_coords.size());
sub_trace_lengths[0] = 0;
for (const auto current_coordinate : util::irange<std::size_t>(0, input_coords.size()))
{
bool allow_uturn = false;
if (0 < current_coordinate)
{
last_distance = util::coordinate_calculation::haversineDistance(
input_coords[current_coordinate - 1], input_coords[current_coordinate]);
sub_trace_lengths[current_coordinate] +=
sub_trace_lengths[current_coordinate - 1] + last_distance;
}
if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate)
{
double turn_angle = util::ComputeAngle(input_coords[current_coordinate - 1],
input_coords[current_coordinate],
input_coords[current_coordinate + 1]);
// sharp turns indicate a possible uturn
if (turn_angle <= 90.0 || turn_angle >= 270.0)
{
allow_uturn = true;
}
}
// Use bearing values if supplied, otherwise fallback to 0,180 defaults
auto bearing = input_bearings.size() > 0 ? input_bearings[current_coordinate].first : 0;
auto range = input_bearings.size() > 0
? (input_bearings[current_coordinate].second
? *input_bearings[current_coordinate].second
: 10)
: 180;
auto candidates = facade->NearestPhantomNodesInRange(input_coords[current_coordinate],
query_radius, bearing, range);
if (candidates.size() == 0)
{
break;
}
// sort by forward id, then by reverse id and then by distance
std::sort(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.phantom_node.forward_node_id < rhs.phantom_node.forward_node_id ||
(lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
(lhs.phantom_node.reverse_node_id < rhs.phantom_node.reverse_node_id ||
(lhs.phantom_node.reverse_node_id ==
rhs.phantom_node.reverse_node_id &&
lhs.distance < rhs.distance)));
});
auto new_end = std::unique(
candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.phantom_node.forward_node_id == rhs.phantom_node.forward_node_id &&
lhs.phantom_node.reverse_node_id == rhs.phantom_node.reverse_node_id;
});
candidates.resize(new_end - candidates.begin());
if (!allow_uturn)
{
const auto compact_size = candidates.size();
for (const auto i : util::irange<std::size_t>(0, compact_size))
{
// Split edge if it is bidirectional and append reverse direction to end of list
if (candidates[i].phantom_node.forward_node_id != SPECIAL_NODEID &&
candidates[i].phantom_node.reverse_node_id != SPECIAL_NODEID)
{
PhantomNode reverse_node(candidates[i].phantom_node);
reverse_node.forward_node_id = SPECIAL_NODEID;
candidates.push_back(
PhantomNodeWithDistance{reverse_node, candidates[i].distance});
candidates[i].phantom_node.reverse_node_id = SPECIAL_NODEID;
}
}
}
// sort by distance to make pruning effective
std::sort(candidates.begin(), candidates.end(),
[](const PhantomNodeWithDistance &lhs, const PhantomNodeWithDistance &rhs)
{
return lhs.distance < rhs.distance;
});
candidates_lists.push_back(std::move(candidates));
}
return candidates_lists;
}
util::json::Object submatchingToJSON(const SubMatching &sub,
const RouteParameters &route_parameters,
const InternalRouteResult &raw_route)
{
util::json::Object subtrace;
if (route_parameters.classify)
{
subtrace.values["confidence"] = sub.confidence;
}
auto response_generator = MakeApiResponseGenerator(facade);
subtrace.values["hint_data"] = response_generator.BuildHintData(raw_route);
if (route_parameters.geometry || route_parameters.print_instructions)
{
using SegmentList = guidance::SegmentList<DataFacadeT>;
// Passing false to extract_alternative extracts the route.
const constexpr bool EXTRACT_ROUTE = false;
// by passing false to segment_list, we skip the douglas peucker simplification
// and mark all segments as necessary within the generation process
const constexpr bool NO_ROUTE_SIMPLIFICATION = false;
SegmentList segment_list(raw_route, EXTRACT_ROUTE, route_parameters.zoom_level,
NO_ROUTE_SIMPLIFICATION, facade);
if (route_parameters.geometry)
{
subtrace.values["geometry"] =
response_generator.GetGeometry(route_parameters.compression, segment_list);
}
if (route_parameters.print_instructions)
{
subtrace.values["instructions"] =
guidance::AnnotateRoute<DataFacadeT>(segment_list.Get(), facade);
}
util::json::Object json_route_summary;
json_route_summary.values["total_distance"] = segment_list.GetDistance();
json_route_summary.values["total_time"] = segment_list.GetDuration();
subtrace.values["route_summary"] = json_route_summary;
}
subtrace.values["indices"] = util::json::make_array(sub.indices);
util::json::Array points;
for (const auto &node : sub.nodes)
{
points.values.emplace_back(
util::json::make_array(node.location.lat / COORDINATE_PRECISION,
node.location.lon / COORDINATE_PRECISION));
}
subtrace.values["matched_points"] = points;
util::json::Array names;
for (const auto &node : sub.nodes)
{
names.values.emplace_back(facade->get_name_for_id(node.name_id));
}
subtrace.values["matched_names"] = names;
return subtrace;
}
Status HandleRequest(const RouteParameters &route_parameters,
util::json::Object &json_result) final override
{
// enforce maximum number of locations for performance reasons
if (max_locations_map_matching > 0 &&
static_cast<int>(route_parameters.coordinates.size()) > max_locations_map_matching)
{
json_result.values["status_message"] = "Too many coodindates";
return Status::Error;
}
// check number of parameters
if (!check_all_coordinates(route_parameters.coordinates))
{
json_result.values["status_message"] = "Invalid coordinates";
return Status::Error;
}
std::vector<double> sub_trace_lengths;
const auto &input_coords = route_parameters.coordinates;
const auto &input_timestamps = route_parameters.timestamps;
const auto &input_bearings = route_parameters.bearings;
if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size())
{
json_result.values["status_message"] =
"Number of timestamps does not match number of coordinates";
return Status::Error;
}
if (input_bearings.size() > 0 && input_coords.size() != input_bearings.size())
{
json_result.values["status_message"] =
"Number of bearings does not match number of coordinates";
return Status::Error;
}
// at least two coordinates are needed for map matching
if (static_cast<int>(input_coords.size()) < 2)
{
json_result.values["status_message"] = "At least two coordinates needed";
return Status::Error;
}
const auto candidates_lists = getCandidates(
input_coords, input_bearings, route_parameters.gps_precision, sub_trace_lengths);
if (candidates_lists.size() != input_coords.size())
{
BOOST_ASSERT(candidates_lists.size() < input_coords.size());
json_result.values["status_message"] =
std::string("Could not find a matching segment for coordinate ") +
std::to_string(candidates_lists.size());
return Status::NoSegment;
}
// setup logging if enabled
if (util::json::Logger::get())
util::json::Logger::get()->initialize("matching");
// call the actual map matching
SubMatchingList sub_matchings;
search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps,
route_parameters.matching_beta,
route_parameters.gps_precision, sub_matchings);
util::json::Array matchings;
for (auto &sub : sub_matchings)
{
// classify result
if (route_parameters.classify)
{
double trace_length =
sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()];
TraceClassification classification =
classify(trace_length, sub.length,
(sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size());
if (classification.first == ClassifierT::ClassLabel::POSITIVE)
{
sub.confidence = classification.second;
}
else
{
sub.confidence = 1 - classification.second;
}
}
BOOST_ASSERT(sub.nodes.size() > 1);
// FIXME we only run this to obtain the geometry
// The clean way would be to get this directly from the map matching plugin
InternalRouteResult raw_route;
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = sub.nodes[i];
current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
BOOST_ASSERT(current_phantom_node_pair.source_phantom.IsValid());
BOOST_ASSERT(current_phantom_node_pair.target_phantom.IsValid());
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates,
std::vector<bool>(raw_route.segment_end_coordinates.size() + 1, true), raw_route);
BOOST_ASSERT(raw_route.shortest_path_length != INVALID_EDGE_WEIGHT);
matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route));
}
if (util::json::Logger::get())
util::json::Logger::get()->render("matching", json_result);
json_result.values["matchings"] = matchings;
if (sub_matchings.empty())
{
json_result.values["status_message"] = "Cannot find matchings";
return Status::EmptyResult;
}
json_result.values["status_message"] = "Found matchings";
return Status::Ok;
}
private:
std::string descriptor_string;
DataFacadeT *facade;
int max_locations_map_matching;
ClassifierT classifier;
};
}
}
}
#endif // MATCH_HPP
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains base class for adapters
*/
#pragma once
namespace etl {
/*!
* \brief A base class for adapters.
*/
template <typename Matrix>
struct adapter {
using matrix_t = Matrix; ///< The adapted matrix type
using expr_t = matrix_t; ///< The wrapped expression type
using value_type = value_t<matrix_t>; ///< The value type
using memory_type = value_type*; ///< The memory type
using const_memory_type = const value_type*; ///< The const memory type
/*!
* \brief The vectorization type for V
*/
template <typename V = default_vec>
using vec_type = typename V::template vec_type<value_type>;
protected:
matrix_t value; ///< The adapted matrix
public:
/*!
* \brief Construct a new matrix and fill it with zeros
*
* This constructor can only be used when the matrix is fast
*/
adapter() noexcept : value(value_type()) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it witht the given value
*
* \param value The value to fill the matrix with
*
* This constructor can only be used when the matrix is fast
*/
explicit adapter(value_type value) noexcept : value(value) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it with zeros
* \param dim The dimension of the matrix
*/
explicit adapter(size_t dim) noexcept : value(dim, dim, value_type()) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it witht the given value
*
* \param value The value to fill the matrix with
* \param dim The dimension of the matrix
*/
adapter(size_t dim, value_type value) noexcept : value(dim, dim, value) {
//Nothing else to init
}
/*!
* \brief Construct a adapter by copy
* \param rhs The right-hand-side matrix
*/
adapter(const adapter& rhs) = default;
/*!
* \brief Assign to the matrix by copy
* \param rhs The right-hand-side matrix
* \return a reference to the assigned matrix
*/
adapter& operator=(const adapter& rhs) = default;
/*!
* \brief Construct a adapter by move
* \param rhs The right-hand-side matrix
*/
adapter(adapter&& rhs) noexcept = default;
/*!
* \brief Assign to the matrix by move
* \param rhs The right-hand-side matrix
* \return a reference to the assigned matrix
*/
adapter& operator=(adapter&& rhs) noexcept = default;
/*!
* \brief Access the (i, j) element of the 2D matrix
* \param i The index of the first dimension
* \param j The index of the second dimension
* \return a reference to the (i,j) element
*
* Accessing an element outside the matrix results in Undefined Behaviour.
*/
const value_type& operator()(size_t i, size_t j) const noexcept {
return value(i, j);
}
/*!
* \brief Returns the element at the given index
* \param i The index
* \return a reference to the element at the given index.
*/
const value_type& operator[](size_t i) const noexcept {
return value[i];
}
/*!
* \brief Returns the element at the given index
* \param i The index
* \return a reference to the element at the given index.
*/
value_type& operator[](size_t i) noexcept {
return value[i];
}
/*!
* \returns the value at the given index
* This function never alters the state of the container.
* \param i The index
* \return the value at the given index.
*/
value_type read_flat(size_t i) const noexcept {
return value.read_flat(i);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
memory_type memory_start() noexcept {
return value.memory_start();
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
const_memory_type memory_start() const noexcept {
return value.memory_start();
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
memory_type memory_end() noexcept {
return value.memory_end();
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
const_memory_type memory_end() const noexcept {
return value.memory_end();
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
vec_type<V> load(size_t i) const noexcept {
return value.template load<V>(i);
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
vec_type<V> loadu(size_t i) const noexcept {
return value.template loadu<V>(i);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal stores
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void stream(vec_type<V> in, size_t i) noexcept {
value.template stream<V>(in, i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void store(vec_type<V> in, size_t i) noexcept {
value.template store<V>(in, i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void storeu(vec_type<V> in, size_t i) noexcept {
value.template storeu<V>(in, i);
}
/*!
* \brief Test if this expression aliases with the given expression
* \param rhs The other expression to test
* \return true if the two expressions aliases, false otherwise
*/
template<typename E>
bool alias(const E& rhs) const noexcept {
return value.alias(rhs);
}
// Assignment functions
/*!
* \brief Assign to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
std_assign_evaluate(value, lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(value, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(value, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(value, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(value, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(value, lhs);
}
// Internals
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::evaluator_visitor& visitor) const {
cpp_unused(visitor);
}
/*!
* \brief Return GPU memory of this expression, if any.
* \return a pointer to the GPU memory or nullptr if not allocated in GPU.
*/
value_type* gpu_memory() const noexcept {
return value.gpu_memory();
}
/*!
* \brief Evict the expression from GPU.
*/
void gpu_evict() const noexcept {
value.gpu_evict();
}
/*!
* \brief Invalidates the CPU memory
*/
void invalidate_cpu() const noexcept {
value.invalidate_cpu();
}
/*!
* \brief Invalidates the GPU memory
*/
void invalidate_gpu() const noexcept {
value.invalidate_gpu();
}
/*!
* \brief Validates the CPU memory
*/
void validate_cpu() const noexcept {
value.validate_cpu();
}
/*!
* \brief Validates the GPU memory
*/
void validate_gpu() const noexcept {
value.validate_gpu();
}
/*!
* \brief Ensures that the GPU memory is allocated and that the GPU memory
* is up to date (to undefined value).
*/
void ensure_gpu_allocated() const {
value.ensure_gpu_allocated();
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
*/
void ensure_gpu_up_to_date() const {
value.ensure_gpu_up_to_date();
}
/*!
* \brief Copy back from the GPU to the expression memory if
* necessary.
*/
void ensure_cpu_up_to_date() const {
value.ensure_cpu_up_to_date();
}
/*!
* \brief Copy from GPU to GPU
* \param gpu_memory Pointer to CPU memory
*/
void gpu_copy_from(const value_type* gpu_memory) const {
value.gpu_copy_from(gpu_memory);
}
/*!
* \brief Indicates if the CPU memory is up to date.
* \return true if the CPU memory is up to date, false otherwise.
*/
bool is_cpu_up_to_date() const noexcept {
return value.is_cpu_up_to_date();
}
/*!
* \brief Indicates if the GPU memory is up to date.
* \return true if the GPU memory is up to date, false otherwise.
*/
bool is_gpu_up_to_date() const noexcept {
return value.is_gpu_up_to_date();
}
/*!
* \brief Returns the number of dimensions of the matrix
* \return the number of dimensions of the matrix
*/
static constexpr size_t dimensions() noexcept {
return 2;
}
};
} //end of namespace etl
<commit_msg>Correctly adapt gpu_compute<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains base class for adapters
*/
#pragma once
namespace etl {
/*!
* \brief A base class for adapters.
*/
template <typename Matrix>
struct adapter {
using matrix_t = Matrix; ///< The adapted matrix type
using expr_t = matrix_t; ///< The wrapped expression type
using value_type = value_t<matrix_t>; ///< The value type
using memory_type = value_type*; ///< The memory type
using const_memory_type = const value_type*; ///< The const memory type
/*!
* \brief The vectorization type for V
*/
template <typename V = default_vec>
using vec_type = typename V::template vec_type<value_type>;
protected:
matrix_t value; ///< The adapted matrix
public:
/*!
* \brief Construct a new matrix and fill it with zeros
*
* This constructor can only be used when the matrix is fast
*/
adapter() noexcept : value(value_type()) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it witht the given value
*
* \param value The value to fill the matrix with
*
* This constructor can only be used when the matrix is fast
*/
explicit adapter(value_type value) noexcept : value(value) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it with zeros
* \param dim The dimension of the matrix
*/
explicit adapter(size_t dim) noexcept : value(dim, dim, value_type()) {
//Nothing else to init
}
/*!
* \brief Construct a new adapter matrix and fill it witht the given value
*
* \param value The value to fill the matrix with
* \param dim The dimension of the matrix
*/
adapter(size_t dim, value_type value) noexcept : value(dim, dim, value) {
//Nothing else to init
}
/*!
* \brief Construct a adapter by copy
* \param rhs The right-hand-side matrix
*/
adapter(const adapter& rhs) = default;
/*!
* \brief Assign to the matrix by copy
* \param rhs The right-hand-side matrix
* \return a reference to the assigned matrix
*/
adapter& operator=(const adapter& rhs) = default;
/*!
* \brief Construct a adapter by move
* \param rhs The right-hand-side matrix
*/
adapter(adapter&& rhs) noexcept = default;
/*!
* \brief Assign to the matrix by move
* \param rhs The right-hand-side matrix
* \return a reference to the assigned matrix
*/
adapter& operator=(adapter&& rhs) noexcept = default;
/*!
* \brief Access the (i, j) element of the 2D matrix
* \param i The index of the first dimension
* \param j The index of the second dimension
* \return a reference to the (i,j) element
*
* Accessing an element outside the matrix results in Undefined Behaviour.
*/
const value_type& operator()(size_t i, size_t j) const noexcept {
return value(i, j);
}
/*!
* \brief Returns the element at the given index
* \param i The index
* \return a reference to the element at the given index.
*/
const value_type& operator[](size_t i) const noexcept {
return value[i];
}
/*!
* \brief Returns the element at the given index
* \param i The index
* \return a reference to the element at the given index.
*/
value_type& operator[](size_t i) noexcept {
return value[i];
}
/*!
* \returns the value at the given index
* This function never alters the state of the container.
* \param i The index
* \return the value at the given index.
*/
value_type read_flat(size_t i) const noexcept {
return value.read_flat(i);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
memory_type memory_start() noexcept {
return value.memory_start();
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
const_memory_type memory_start() const noexcept {
return value.memory_start();
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
memory_type memory_end() noexcept {
return value.memory_end();
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*
* This should only be used by ETL itself in order not to void
* the adapter guarantee.
*/
const_memory_type memory_end() const noexcept {
return value.memory_end();
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
vec_type<V> load(size_t i) const noexcept {
return value.template load<V>(i);
}
/*!
* \brief Load several elements of the matrix at once
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the matrix
*/
template<typename V = default_vec>
vec_type<V> loadu(size_t i) const noexcept {
return value.template loadu<V>(i);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal stores
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void stream(vec_type<V> in, size_t i) noexcept {
value.template stream<V>(in, i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void store(vec_type<V> in, size_t i) noexcept {
value.template store<V>(in, i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void storeu(vec_type<V> in, size_t i) noexcept {
value.template storeu<V>(in, i);
}
/*!
* \brief Test if this expression aliases with the given expression
* \param rhs The other expression to test
* \return true if the two expressions aliases, false otherwise
*/
template<typename E>
bool alias(const E& rhs) const noexcept {
return value.alias(rhs);
}
/*!
* \brief Return a GPU computed version of this expression
* \return a GPU-computed ETL expression for this expression
*/
auto& gpu_compute(){
return value;
}
/*!
* \brief Return a GPU computed version of this expression
* \return a GPU-computed ETL expression for this expression
*/
const auto& gpu_compute() const {
return value;
}
// Assignment functions
/*!
* \brief Assign to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
std_assign_evaluate(value, lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(value, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(value, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(value, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(value, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(value, lhs);
}
// Internals
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::evaluator_visitor& visitor) const {
cpp_unused(visitor);
}
/*!
* \brief Return GPU memory of this expression, if any.
* \return a pointer to the GPU memory or nullptr if not allocated in GPU.
*/
value_type* gpu_memory() const noexcept {
return value.gpu_memory();
}
/*!
* \brief Evict the expression from GPU.
*/
void gpu_evict() const noexcept {
value.gpu_evict();
}
/*!
* \brief Invalidates the CPU memory
*/
void invalidate_cpu() const noexcept {
value.invalidate_cpu();
}
/*!
* \brief Invalidates the GPU memory
*/
void invalidate_gpu() const noexcept {
value.invalidate_gpu();
}
/*!
* \brief Validates the CPU memory
*/
void validate_cpu() const noexcept {
value.validate_cpu();
}
/*!
* \brief Validates the GPU memory
*/
void validate_gpu() const noexcept {
value.validate_gpu();
}
/*!
* \brief Ensures that the GPU memory is allocated and that the GPU memory
* is up to date (to undefined value).
*/
void ensure_gpu_allocated() const {
value.ensure_gpu_allocated();
}
/*!
* \brief Allocate memory on the GPU for the expression and copy the values into the GPU.
*/
void ensure_gpu_up_to_date() const {
value.ensure_gpu_up_to_date();
}
/*!
* \brief Copy back from the GPU to the expression memory if
* necessary.
*/
void ensure_cpu_up_to_date() const {
value.ensure_cpu_up_to_date();
}
/*!
* \brief Copy from GPU to GPU
* \param gpu_memory Pointer to CPU memory
*/
void gpu_copy_from(const value_type* gpu_memory) const {
value.gpu_copy_from(gpu_memory);
}
/*!
* \brief Indicates if the CPU memory is up to date.
* \return true if the CPU memory is up to date, false otherwise.
*/
bool is_cpu_up_to_date() const noexcept {
return value.is_cpu_up_to_date();
}
/*!
* \brief Indicates if the GPU memory is up to date.
* \return true if the GPU memory is up to date, false otherwise.
*/
bool is_gpu_up_to_date() const noexcept {
return value.is_gpu_up_to_date();
}
/*!
* \brief Returns the number of dimensions of the matrix
* \return the number of dimensions of the matrix
*/
static constexpr size_t dimensions() noexcept {
return 2;
}
};
} //end of namespace etl
<|endoftext|>
|
<commit_before>#include "DistormHelper.hpp"
#include <distorm.h>
#include <mnemonics.h>
extern "C"
{
#include <../src/instructions.h>
}
bool AreOperandsStatic(const _DInst &instruction, const int prefixLength)
{
const auto fc = META_GET_FC(instruction.meta);
if (fc == FC_UNC_BRANCH || fc == FC_CND_BRANCH)
{
if (instruction.size - prefixLength < 5)
{
return true;
}
}
const auto ops = instruction.ops;
for (auto i = 0; i < OPERANDS_NO; i++)
{
switch (ops[i].type)
{
case O_NONE:
case O_REG:
case O_IMM1:
case O_IMM2:
continue;
case O_IMM:
if (ops[i].size < 32)
{
continue;
}
return false;
case O_DISP:
case O_SMEM:
case O_MEM:
if (instruction.dispSize < 32)
{
continue;
}
#ifdef RECLASSNET64
if (ops[i].index == R_RIP)
{
continue;
}
#endif
return false;
case O_PC:
case O_PTR:
return false;
}
}
return true;
}
int GetStaticInstructionBytes(const _DInst &instruction, const uint8_t *data)
{
_CodeInfo info = {};
info.codeOffset = reinterpret_cast<_OffsetType>(data);
info.code = data;
info.codeLen = instruction.size;
info.features = DF_NONE;
#ifdef RECLASSNET32
info.dt = Decode32Bits;
#else
info.dt = Decode64Bits;
#endif
_PrefixState ps = {};
memset(ps.pfxIndexer, PFXIDX_NONE, sizeof(int) * PFXIDX_MAX);
ps.start = data;
ps.last = data;
prefixes_decode(data, info.codeLen, &ps, info.dt);
info.codeOffset = reinterpret_cast<_OffsetType>(ps.last);
info.code = ps.last;
const auto prefixLength = static_cast<int>(ps.start - ps.last);
info.codeLen -= prefixLength;
inst_lookup(&info, &ps);
if (AreOperandsStatic(instruction, prefixLength))
{
return instruction.size;
}
return instruction.size - info.codeLen;
}
_CodeInfo CreateCodeInfo(const RC_Pointer address, const RC_Size length, const RC_Pointer virtualAddress)
{
_CodeInfo info = {};
info.codeOffset = reinterpret_cast<_OffsetType>(virtualAddress);
info.code = reinterpret_cast<const uint8_t*>(address);
info.codeLen = length;
info.features = DF_NONE;
#ifdef RECLASSNET32
info.dt = Decode32Bits;
#else
info.dt = Decode64Bits;
#endif
return info;
}
void FillInstructionData(const RC_Pointer address, const _DInst& instruction, const _DecodedInst& instructionInfo, const bool determineStaticInstructionBytes, InstructionData* data)
{
data->Address = reinterpret_cast<RC_Pointer>(instruction.addr);
data->Length = instructionInfo.size;
std::memcpy(data->Data, address, instructionInfo.size);
MultiByteToUnicode(
reinterpret_cast<const char*>(instructionInfo.mnemonic.p),
data->Instruction,
instructionInfo.mnemonic.length
);
if (instructionInfo.operands.length != 0)
{
data->Instruction[instructionInfo.mnemonic.length] = ' ';
MultiByteToUnicode(
reinterpret_cast<const char*>(instructionInfo.operands.p),
0,
data->Instruction,
instructionInfo.mnemonic.length + 1,
std::min<int>(64 - 1 - instructionInfo.mnemonic.length, instructionInfo.operands.length)
);
}
if (determineStaticInstructionBytes)
{
data->StaticInstructionBytes = GetStaticInstructionBytes(
instruction,
reinterpret_cast<const uint8_t*>(address)
);
}
else
{
data->StaticInstructionBytes = -1;
}
}
bool DisassembleInstructionsImpl(const RC_Pointer address, const RC_Size length, const RC_Pointer virtualAddress, const bool determineStaticInstructionBytes, EnumerateInstructionCallback callback)
{
auto info = CreateCodeInfo(address, length, virtualAddress);
const unsigned MaxInstructions = 50;
_DInst decodedInstructions[MaxInstructions] = {};
unsigned count = 0;
auto instructionAddress = static_cast<uint8_t*>(address);
while (true)
{
const auto res = distorm_decompose(&info, decodedInstructions, MaxInstructions, &count);
if (res == DECRES_INPUTERR)
{
return false;
}
for (auto i = 0u; i < count; ++i)
{
_DecodedInst instructionInfo = {};
distorm_format(&info, &decodedInstructions[i], &instructionInfo);
InstructionData data;
FillInstructionData(instructionAddress, decodedInstructions[i], instructionInfo, determineStaticInstructionBytes, &data);
if (callback(&data) == false)
{
return true;
}
instructionAddress += decodedInstructions[i].size;
}
if (res == DECRES_SUCCESS || count == 0)
{
return true;
}
const auto offset = static_cast<unsigned>(decodedInstructions[count - 1].addr - info.codeOffset);
info.codeOffset += offset;
info.code += offset;
info.codeLen -= offset;
}
}
<commit_msg>Fixed uninitialized data.<commit_after>#include "DistormHelper.hpp"
#include <distorm.h>
#include <mnemonics.h>
extern "C"
{
#include <../src/instructions.h>
}
bool AreOperandsStatic(const _DInst &instruction, const int prefixLength)
{
const auto fc = META_GET_FC(instruction.meta);
if (fc == FC_UNC_BRANCH || fc == FC_CND_BRANCH)
{
if (instruction.size - prefixLength < 5)
{
return true;
}
}
const auto ops = instruction.ops;
for (auto i = 0; i < OPERANDS_NO; i++)
{
switch (ops[i].type)
{
case O_NONE:
case O_REG:
case O_IMM1:
case O_IMM2:
continue;
case O_IMM:
if (ops[i].size < 32)
{
continue;
}
return false;
case O_DISP:
case O_SMEM:
case O_MEM:
if (instruction.dispSize < 32)
{
continue;
}
#ifdef RECLASSNET64
if (ops[i].index == R_RIP)
{
continue;
}
#endif
return false;
case O_PC:
case O_PTR:
return false;
}
}
return true;
}
int GetStaticInstructionBytes(const _DInst &instruction, const uint8_t *data)
{
_CodeInfo info = {};
info.codeOffset = reinterpret_cast<_OffsetType>(data);
info.code = data;
info.codeLen = instruction.size;
info.features = DF_NONE;
#ifdef RECLASSNET32
info.dt = Decode32Bits;
#else
info.dt = Decode64Bits;
#endif
_PrefixState ps = {};
memset(ps.pfxIndexer, PFXIDX_NONE, sizeof(int) * PFXIDX_MAX);
ps.start = data;
ps.last = data;
prefixes_decode(data, info.codeLen, &ps, info.dt);
info.codeOffset = reinterpret_cast<_OffsetType>(ps.last);
info.code = ps.last;
const auto prefixLength = static_cast<int>(ps.start - ps.last);
info.codeLen -= prefixLength;
inst_lookup(&info, &ps);
if (AreOperandsStatic(instruction, prefixLength))
{
return instruction.size;
}
return instruction.size - info.codeLen;
}
_CodeInfo CreateCodeInfo(const RC_Pointer address, const RC_Size length, const RC_Pointer virtualAddress)
{
_CodeInfo info = {};
info.codeOffset = reinterpret_cast<_OffsetType>(virtualAddress);
info.code = reinterpret_cast<const uint8_t*>(address);
info.codeLen = length;
info.features = DF_NONE;
#ifdef RECLASSNET32
info.dt = Decode32Bits;
#else
info.dt = Decode64Bits;
#endif
return info;
}
void FillInstructionData(const RC_Pointer address, const _DInst& instruction, const _DecodedInst& instructionInfo, const bool determineStaticInstructionBytes, InstructionData* data)
{
data->Address = reinterpret_cast<RC_Pointer>(instruction.addr);
data->Length = instructionInfo.size;
std::memcpy(data->Data, address, instructionInfo.size);
MultiByteToUnicode(
reinterpret_cast<const char*>(instructionInfo.mnemonic.p),
data->Instruction,
instructionInfo.mnemonic.length
);
if (instructionInfo.operands.length != 0)
{
data->Instruction[instructionInfo.mnemonic.length] = ' ';
MultiByteToUnicode(
reinterpret_cast<const char*>(instructionInfo.operands.p),
0,
data->Instruction,
instructionInfo.mnemonic.length + 1,
std::min<int>(64 - 1 - instructionInfo.mnemonic.length, instructionInfo.operands.length)
);
}
if (determineStaticInstructionBytes)
{
data->StaticInstructionBytes = GetStaticInstructionBytes(
instruction,
reinterpret_cast<const uint8_t*>(address)
);
}
else
{
data->StaticInstructionBytes = -1;
}
}
bool DisassembleInstructionsImpl(const RC_Pointer address, const RC_Size length, const RC_Pointer virtualAddress, const bool determineStaticInstructionBytes, EnumerateInstructionCallback callback)
{
auto info = CreateCodeInfo(address, length, virtualAddress);
const unsigned MaxInstructions = 50;
_DInst decodedInstructions[MaxInstructions] = {};
unsigned count = 0;
auto instructionAddress = static_cast<uint8_t*>(address);
while (true)
{
const auto res = distorm_decompose(&info, decodedInstructions, MaxInstructions, &count);
if (res == DECRES_INPUTERR)
{
return false;
}
for (auto i = 0u; i < count; ++i)
{
_DecodedInst instructionInfo = {};
distorm_format(&info, &decodedInstructions[i], &instructionInfo);
InstructionData data = {};
FillInstructionData(instructionAddress, decodedInstructions[i], instructionInfo, determineStaticInstructionBytes, &data);
if (callback(&data) == false)
{
return true;
}
instructionAddress += decodedInstructions[i].size;
}
if (res == DECRES_SUCCESS || count == 0)
{
return true;
}
const auto offset = static_cast<unsigned>(decodedInstructions[count - 1].addr - info.codeOffset);
info.codeOffset += offset;
info.code += offset;
info.codeLen -= offset;
}
}
<|endoftext|>
|
<commit_before>/**
* @file directed_graph.tcc
* @author Sean Massung
*/
namespace meta
{
namespace graph
{
template <class Node, class Edge>
auto directed_graph
<Node, Edge>::outgoing(node_id id) const -> const adjacency_list &
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return nodes_[id].second;
}
template <class Node, class Edge>
const std::vector<node_id>& directed_graph
<Node, Edge>::incoming(node_id id) const
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return incoming_.at(id);
}
template <class Node, class Edge>
Node& directed_graph<Node, Edge>::node(node_id id)
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return nodes_[id].first;
}
template <class Node, class Edge>
typename util::optional<Edge> directed_graph
<Node, Edge>::edge(node_id source, node_id dest)
{
if (source >= size() || dest >= size())
throw directed_graph_exception{"node_id out of range"};
auto& list = nodes_[source].second;
auto it = std::find_if(list.begin(), list.end(),
[&](const std::pair<node_id, Edge>& p)
{ return p.first == dest; });
if (it != list.end())
return {it->second};
return {util::nullopt};
}
template <class Node, class Edge>
node_id directed_graph<Node, Edge>::insert(const Node& node)
{
nodes_.emplace_back(node, adjacency_list{});
incoming_.emplace_back(std::vector<node_id>{});
return node_id{nodes_.size() - 1};
}
template <class Node, class Edge>
void directed_graph
<Node, Edge>::add_edge(const Edge& edge, node_id source, node_id dest)
{
if (source >= size() || dest >= size())
throw directed_graph_exception{"node_id out of range"};
auto& list = nodes_[source].second;
auto it = std::find_if(list.begin(), list.end(),
[&](const std::pair<node_id, Edge>& p)
{ return p.first == dest; });
if (it != list.end())
throw directed_graph_exception{"attempted to add existing edge"};
list.emplace_back(dest, edge); // add outgoing edge from source to dest
incoming_[source].push_back(dest); // add incoming edge to source
}
template <class Node, class Edge>
void directed_graph<Node, Edge>::add_edge(node_id source, node_id dest)
{
add_edge(Edge{}, source, dest);
}
template <class Node, class Edge>
uint64_t directed_graph<Node, Edge>::size() const
{
return nodes_.size();
}
}
}
<commit_msg>clang-format directed_graph.tcc<commit_after>/**
* @file directed_graph.tcc
* @author Sean Massung
*/
namespace meta
{
namespace graph
{
template <class Node, class Edge>
auto directed_graph<Node, Edge>::outgoing(node_id id) const -> const
adjacency_list &
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return nodes_[id].second;
}
template <class Node, class Edge>
const std::vector<node_id>&
directed_graph<Node, Edge>::incoming(node_id id) const
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return incoming_.at(id);
}
template <class Node, class Edge>
Node& directed_graph<Node, Edge>::node(node_id id)
{
if (id >= size())
throw directed_graph_exception{"node_id out of range"};
return nodes_[id].first;
}
template <class Node, class Edge>
typename util::optional<Edge> directed_graph<Node, Edge>::edge(node_id source,
node_id dest)
{
if (source >= size() || dest >= size())
throw directed_graph_exception{"node_id out of range"};
auto& list = nodes_[source].second;
auto it = std::find_if(list.begin(), list.end(),
[&](const std::pair<node_id, Edge>& p)
{
return p.first == dest;
});
if (it != list.end())
return {it->second};
return {util::nullopt};
}
template <class Node, class Edge>
node_id directed_graph<Node, Edge>::insert(const Node& node)
{
nodes_.emplace_back(node, adjacency_list{});
incoming_.emplace_back(std::vector<node_id>{});
return node_id{nodes_.size() - 1};
}
template <class Node, class Edge>
void directed_graph<Node, Edge>::add_edge(const Edge& edge, node_id source,
node_id dest)
{
if (source >= size() || dest >= size())
throw directed_graph_exception{"node_id out of range"};
auto& list = nodes_[source].second;
auto it = std::find_if(list.begin(), list.end(),
[&](const std::pair<node_id, Edge>& p)
{
return p.first == dest;
});
if (it != list.end())
throw directed_graph_exception{"attempted to add existing edge"};
list.emplace_back(dest, edge); // add outgoing edge from source to dest
incoming_[source].push_back(dest); // add incoming edge to source
}
template <class Node, class Edge>
void directed_graph<Node, Edge>::add_edge(node_id source, node_id dest)
{
add_edge(Edge{}, source, dest);
}
template <class Node, class Edge>
uint64_t directed_graph<Node, Edge>::size() const
{
return nodes_.size();
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 ScyllaDB
*/
#include "build_id.hh"
#include <fmt/printf.h>
#include <link.h>
#include <seastar/core/align.hh>
#include <sstream>
using namespace seastar;
static const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) {
auto base = info->dlpi_addr;
const auto* h = info->dlpi_phdr;
auto num_headers = info->dlpi_phnum;
for (int i = 0; i != num_headers; ++i, ++h) {
if (h->p_type != PT_NOTE) {
continue;
}
auto* p = reinterpret_cast<const char*>(base) + h->p_vaddr;
auto* e = p + h->p_memsz;
while (p != e) {
const auto* n = reinterpret_cast<const Elf64_Nhdr*>(p);
if (n->n_type == NT_GNU_BUILD_ID) {
return n;
}
p += sizeof(Elf64_Nhdr);
p += n->n_namesz;
p = align_up(p, 4);
p += n->n_descsz;
p = align_up(p, 4);
}
}
assert(0 && "no NT_GNU_BUILD_ID note");
}
static int callback(dl_phdr_info* info, size_t size, void* data) {
std::string& ret = *(std::string*)data;
std::ostringstream os;
// The first DSO is always the main program, which has an empty name.
assert(strlen(info->dlpi_name) == 0);
auto* n = get_nt_build_id(info);
auto* p = reinterpret_cast<const char*>(n);
p += sizeof(Elf64_Nhdr);
p += n->n_namesz;
p = align_up(p, 4);
const char* desc = p;
for (unsigned i = 0; i < n->n_descsz; ++i) {
fmt::fprintf(os, "%02x", (unsigned char)*(desc + i));
}
ret = os.str();
return 1;
}
std::string get_build_id() {
std::string ret;
int r = dl_iterate_phdr(callback, &ret);
assert(r == 1);
return ret;
}
<commit_msg>build_id: add missing include for assert()<commit_after>/*
* Copyright (C) 2019 ScyllaDB
*/
#include "build_id.hh"
#include <fmt/printf.h>
#include <link.h>
#include <seastar/core/align.hh>
#include <sstream>
#include <cassert>
using namespace seastar;
static const Elf64_Nhdr* get_nt_build_id(dl_phdr_info* info) {
auto base = info->dlpi_addr;
const auto* h = info->dlpi_phdr;
auto num_headers = info->dlpi_phnum;
for (int i = 0; i != num_headers; ++i, ++h) {
if (h->p_type != PT_NOTE) {
continue;
}
auto* p = reinterpret_cast<const char*>(base) + h->p_vaddr;
auto* e = p + h->p_memsz;
while (p != e) {
const auto* n = reinterpret_cast<const Elf64_Nhdr*>(p);
if (n->n_type == NT_GNU_BUILD_ID) {
return n;
}
p += sizeof(Elf64_Nhdr);
p += n->n_namesz;
p = align_up(p, 4);
p += n->n_descsz;
p = align_up(p, 4);
}
}
assert(0 && "no NT_GNU_BUILD_ID note");
}
static int callback(dl_phdr_info* info, size_t size, void* data) {
std::string& ret = *(std::string*)data;
std::ostringstream os;
// The first DSO is always the main program, which has an empty name.
assert(strlen(info->dlpi_name) == 0);
auto* n = get_nt_build_id(info);
auto* p = reinterpret_cast<const char*>(n);
p += sizeof(Elf64_Nhdr);
p += n->n_namesz;
p = align_up(p, 4);
const char* desc = p;
for (unsigned i = 0; i < n->n_descsz; ++i) {
fmt::fprintf(os, "%02x", (unsigned char)*(desc + i));
}
ret = os.str();
return 1;
}
std::string get_build_id() {
std::string ret;
int r = dl_iterate_phdr(callback, &ret);
assert(r == 1);
return ret;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include <algorithm>
class MessageAssembler
{
public:
virtual void createHeader() = 0;
virtual void createBody() = 0;
virtual void createFooter() = 0;
const std::vector<std::string>& getMessage() const {return mMesssage;}
protected:
std::vector<std::string> mMesssage;
};
class XmlMessageAssembler : public MessageAssembler
{
public:
virtual void createHeader()
{
mMesssage.push_back(std::string("<header>foobar_header</header>"));
}
virtual void createBody()
{
mMesssage.push_back(std::string("<body>foo</body>"));
mMesssage.push_back(std::string("<body>bar</body>"));
mMesssage.push_back(std::string("<body>foobar</body>"));
}
virtual void createFooter()
{
mMesssage.push_back(std::string("<footer>foobar_footer</footer>"));
}
};
class TxtMessageAssembler : public MessageAssembler
{
public:
virtual void createHeader()
{
mMesssage.push_back(std::string("foobar_header"));
}
virtual void createBody()
{
mMesssage.push_back(std::string("foo"));
mMesssage.push_back(std::string("bar"));
mMesssage.push_back(std::string("foobar"));
}
virtual void createFooter()
{
mMesssage.push_back(std::string("foobar_footer"));
}
};
class MessageBuilder
{
public:
const std::vector<std::string>& buildMessage(MessageAssembler* assembler) const
{
assembler->createHeader();
assembler->createBody();
assembler->createFooter();
return assembler->getMessage();
}
};
int main()
{
std::cout << "Builder GoF Kata" << std::endl;
MessageBuilder messageBuilder;
std::vector<std::string> result;
MessageAssembler* messageAssembler = NULL;
messageAssembler = new XmlMessageAssembler();
result = messageBuilder.buildMessage(messageAssembler);
std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n")); // love it or hate!
delete messageAssembler; messageAssembler = NULL;
std::cout << std::endl;
messageAssembler = new TxtMessageAssembler();
result = messageBuilder.buildMessage(messageAssembler);
std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n")); // love it or hate!
delete messageAssembler; messageAssembler = NULL;
}
<commit_msg>added putMessage to clean interface<commit_after>#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include <algorithm>
class MessageAssembler
{
public:
virtual void createHeader() = 0;
virtual void createBody() = 0;
virtual void createFooter() = 0;
void putMessage(const std::string& msg) {mMesssage.push_back(msg);}
const std::vector<std::string>& getMessage() const {return mMesssage;}
private:
std::vector<std::string> mMesssage;
};
class XmlMessageAssembler : public MessageAssembler
{
public:
virtual void createHeader()
{
putMessage("<header>foobar_header</header>");
}
virtual void createBody()
{
putMessage("<body>foo</body>");
putMessage("<body>bar</body>");
putMessage("<body>foobar</body>");
}
virtual void createFooter()
{
putMessage("<footer>foobar_footer</footer>");
}
};
class TxtMessageAssembler : public MessageAssembler
{
public:
virtual void createHeader()
{
putMessage("foobar_header");
}
virtual void createBody()
{
putMessage("foo");
putMessage("bar");
putMessage("foobar");
}
virtual void createFooter()
{
putMessage("foobar_footer");
}
};
class MessageBuilder
{
public:
const std::vector<std::string>& buildMessage(MessageAssembler* assembler) const
{
assembler->createHeader();
assembler->createBody();
assembler->createFooter();
return assembler->getMessage();
}
};
int main()
{
std::cout << "Builder GoF Kata" << std::endl;
MessageBuilder messageBuilder;
std::vector<std::string> result;
MessageAssembler* messageAssembler = NULL;
messageAssembler = new XmlMessageAssembler();
result = messageBuilder.buildMessage(messageAssembler);
std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n")); // love it or hate!
delete messageAssembler; messageAssembler = NULL;
std::cout << std::endl;
messageAssembler = new TxtMessageAssembler();
result = messageBuilder.buildMessage(messageAssembler);
std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n")); // love it or hate!
delete messageAssembler; messageAssembler = NULL;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "calendardemo.h"
#include <QtGui>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CalendarDemo w;
w.show();
return a.exec();
}
<commit_msg>Make sure we maximize on Symbian.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "calendardemo.h"
#include <QtGui>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CalendarDemo w;
#ifdef Q_OS_SYMBIAN
w.showMaximized();
#else
w.show();
#endif
return a.exec();
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include "parser/parser.h"
using namespace std;
using namespace lars;
int main(int argc, char ** argv){
parsing_expression_grammar_builder<double> g;
using expression = expression<double>;
g["Expression"] << "Sum" << [](expression e){ e.value() = e[0].get_value(); };
g["Sum" ] << "Add | Subtract | Product" << [](expression e){ e.value() = e[0].get_value(); };
g["Add" ] << "Sum '+' Product" << [](expression e){ e.value() = e[0].get_value() + e[1].get_value(); };
g["Subtract" ] << "Sum '-' Product" << [](expression e){ e.value() = e[0].get_value() - e[1].get_value(); };
g["Product" ] << "Multiply | Divide | Atomic" << [](expression e){ e.value() = e[0].get_value(); };
g["Multiply" ] << "Product '*' Atomic" << [](expression e){ e.value() = e[0].get_value() * e[1].get_value(); };
g["Divide" ] << "Product '/' Atomic" << [](expression e){ e.value() = e[0].get_value() / e[1].get_value(); };
g["Atomic" ] << "Number | Brackets" << [](expression e){ e.value() = e[0].get_value(); };
g["Brackets" ] << "'(' Sum ')'" << [](expression e){ e.value() = e[0].get_value(); };
g["Number" ] << "'-'? [0-9]+ ('.' [0-9]+)?" << [](expression e){ e.value() = stod(e.string()); };
g.set_starting_rule("Expression");
g["Whitespace"] << "[ \t]";
g.set_separator_rule("Whitespace");
auto p = g.get_parser();
while (true) {
string str;
cout << "> ";
std::getline(std::cin,str);
if(str == "q" || str == "quit")break;
cout << " -> ";
try { cout << p.parse(str).get_value(); }
catch (const char * error){ std::cout << error; }
cout << std::endl;
}
return 0;
}
<commit_msg>now the memory is actually allocated<commit_after>
#include <iostream>
#include "parser/parser.h"
using namespace std;
using namespace lars;
int main(int argc, char ** argv){
parsing_expression_grammar_builder<double> g;
using expression = expression<double>;
g["Expression"] << "Sum" << [](expression e){ e.value() = e[0].get_value(); };
g["Sum" ] << "Add | Subtract | Product" << [](expression e){ e.value() = e[0].get_value(); };
g["Add" ] << "Sum '+' Product" << [](expression e){ e.value() = e[0].get_value() + e[1].get_value(); };
g["Subtract" ] << "Sum '-' Product" << [](expression e){ e.value() = e[0].get_value() - e[1].get_value(); };
g["Product" ] << "Multiply | Divide | Atomic" << [](expression e){ e.value() = e[0].get_value(); };
g["Multiply" ] << "Product '*' Atomic" << [](expression e){ e.value() = e[0].get_value() * e[1].get_value(); };
g["Divide" ] << "Product '/' Atomic" << [](expression e){ e.value() = e[0].get_value() / e[1].get_value(); };
g["Atomic" ] << "Number | Brackets" << [](expression e){ e.value() = e[0].get_value(); };
g["Brackets" ] << "'(' Sum ')'" << [](expression e){ e.value() = e[0].get_value(); };
g["Number" ] << "'-'? [0-9]+ ('.' [0-9]+)?" << [](expression e){ e.value() = stod(e.string()); };
g.set_starting_rule("Expression");
g["Whitespace"] << "[ \t]";
g.set_separator_rule("Whitespace");
auto p = g.get_parser();
while (true) {
string str;
cout << "> ";
std::getline(std::cin,str);
if(str == "q" || str == "quit")break;
cout << " -> ";
try { cout << *p.parse(str).evaluate(); }
catch (const char * error){ std::cout << error; }
cout << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HELPER_HPP_INCLUDE
#define HELPER_HPP_INCLUDE
#include <string>
#include <memory>
#include <utility>
#include <vector>
namespace geopm
{
/// @brief Implementation of std::make_unique (C++14) for C++11.
/// Note that this version will only work for non-array
/// types.
template <class Type, class ...Args>
std::unique_ptr<Type> make_unique(Args &&...args)
{
return std::unique_ptr<Type>(new Type(std::forward<Args>(args)...));
}
/// @brief Reads the specified file and returns the contents in a string.
/// @param [in] path The path of the file to read.
/// @return The contents of the file at path.
std::string read_file(const std::string &path);
/// @brief Read a file and return a double read from the file.
/// @details If a double cannot be read from the file or the units reported
/// in the file do not match the expected units, an exception is
/// thrown.
/// @param [in] path The path of the file to read.
/// @param [in] expected_units Expected units to follow the double. Provide
/// an empty string if no units are expected.
/// @return The value read from the file.
double read_double_from_file(const std::string &path,
const std::string &expected_units);
/// @brief Writes a string to a file. This will replace the file
/// if it exists or create it if it does not exist.
/// @param [in] path The path to the file to write to.
/// @param [in] contents The string to write to the file.
void write_file(const std::string &path, const std::string &contents);
/// @brief Splits a string according to a delimiter.
/// @param [in] str The string to be split.
/// @param [in] delim The delimiter to use to divide the string.
/// Cannot be empty.
/// @return A vector of string pieces.
std::vector<std::string> string_split(const std::string &str,
const std::string &delim);
/// @brief Joins a vector of strings together with a delimter.
/// @param [in] string_list The list of strings to be joined.
/// @param [in] delim The delimiter to use to join the strings.
/// @return The joined string.
std::string string_join(const std::vector<std::string> &string_list,
const std::string &delim);
/// @brief Returns the current hostname as a string.
std::string hostname(void);
/// @brief List all files in the given directory.
/// @param [in] path Path to the directory.
std::vector<std::string> list_directory_files(const std::string &path);
/// @brief Returns whether one string begins with another.
bool string_begins_with(const std::string &str, const std::string &key);
/// @brief Returns whether one string ends with another.
bool string_ends_with(std::string str, std::string key);
/// @brief Format a string to best represent a signal encoding a
/// double precision floating point number.
/// @param [in] signal A real number that requires many
/// significant digits to accurately represent.
/// @return A well-formatted string representation of the signal.
std::string string_format_double(double signal);
/// @brief Format a string to best represent a signal encoding a
/// single precision floating point number.
/// @param [in] signal A real number that requires a few
/// significant digits to accurately represent.
/// @return A well formatted string representation of the signal.
std::string string_format_float(double signal);
/// @brief Format a string to best represent a signal encoding a
/// decimal integer.
/// @param [in] signal An integer that is best represented as a
/// decimal number.
/// @return A well formatted string representation of the signal.
std::string string_format_integer(double signal);
/// @brief Format a string to best represent a signal encoding an
/// unsigned hexadecimal integer.
/// @param [in] signal An unsigned integer that is best
/// represented as a hexadecimal number and has been
/// assigned to a double precision number
/// @return A well formatted string representation of the signal.
std::string string_format_hex(double signal);
/// @brief Format a string to represent the raw memory supporting
/// a signal as an unsigned hexadecimal integer.
/// @param [in] signal A 64-bit unsigned integer that has been
/// byte-wise copied into the memory of signal.
/// @return A well formatted string representation of the signal.
std::string string_format_raw64(double signal);
std::string string_format_hint(double signal);
}
#endif
<commit_msg>Add doxygen to string_format_hint() function<commit_after>/*
* Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef HELPER_HPP_INCLUDE
#define HELPER_HPP_INCLUDE
#include <string>
#include <memory>
#include <utility>
#include <vector>
namespace geopm
{
/// @brief Implementation of std::make_unique (C++14) for C++11.
/// Note that this version will only work for non-array
/// types.
template <class Type, class ...Args>
std::unique_ptr<Type> make_unique(Args &&...args)
{
return std::unique_ptr<Type>(new Type(std::forward<Args>(args)...));
}
/// @brief Reads the specified file and returns the contents in a string.
/// @param [in] path The path of the file to read.
/// @return The contents of the file at path.
std::string read_file(const std::string &path);
/// @brief Read a file and return a double read from the file.
/// @details If a double cannot be read from the file or the units reported
/// in the file do not match the expected units, an exception is
/// thrown.
/// @param [in] path The path of the file to read.
/// @param [in] expected_units Expected units to follow the double. Provide
/// an empty string if no units are expected.
/// @return The value read from the file.
double read_double_from_file(const std::string &path,
const std::string &expected_units);
/// @brief Writes a string to a file. This will replace the file
/// if it exists or create it if it does not exist.
/// @param [in] path The path to the file to write to.
/// @param [in] contents The string to write to the file.
void write_file(const std::string &path, const std::string &contents);
/// @brief Splits a string according to a delimiter.
/// @param [in] str The string to be split.
/// @param [in] delim The delimiter to use to divide the string.
/// Cannot be empty.
/// @return A vector of string pieces.
std::vector<std::string> string_split(const std::string &str,
const std::string &delim);
/// @brief Joins a vector of strings together with a delimter.
/// @param [in] string_list The list of strings to be joined.
/// @param [in] delim The delimiter to use to join the strings.
/// @return The joined string.
std::string string_join(const std::vector<std::string> &string_list,
const std::string &delim);
/// @brief Returns the current hostname as a string.
std::string hostname(void);
/// @brief List all files in the given directory.
/// @param [in] path Path to the directory.
std::vector<std::string> list_directory_files(const std::string &path);
/// @brief Returns whether one string begins with another.
bool string_begins_with(const std::string &str, const std::string &key);
/// @brief Returns whether one string ends with another.
bool string_ends_with(std::string str, std::string key);
/// @brief Format a string to best represent a signal encoding a
/// double precision floating point number.
/// @param [in] signal A real number that requires many
/// significant digits to accurately represent.
/// @return A well-formatted string representation of the signal.
std::string string_format_double(double signal);
/// @brief Format a string to best represent a signal encoding a
/// single precision floating point number.
/// @param [in] signal A real number that requires a few
/// significant digits to accurately represent.
/// @return A well formatted string representation of the signal.
std::string string_format_float(double signal);
/// @brief Format a string to best represent a signal encoding a
/// decimal integer.
/// @param [in] signal An integer that is best represented as a
/// decimal number.
/// @return A well formatted string representation of the signal.
std::string string_format_integer(double signal);
/// @brief Format a string to best represent a signal encoding an
/// unsigned hexadecimal integer.
/// @param [in] signal An unsigned integer that is best
/// represented as a hexadecimal number and has been
/// assigned to a double precision number
/// @return A well formatted string representation of the signal.
std::string string_format_hex(double signal);
/// @brief Format a string to represent the raw memory supporting
/// a signal as an unsigned hexadecimal integer.
/// @param [in] signal A 64-bit unsigned integer that has been
/// byte-wise copied into the memory of signal.
/// @return A well formatted string representation of the signal.
std::string string_format_raw64(double signal);
/// @brief Format a string to represent a hint enum from the
/// geopm_region_hint_e.
/// @param [in] signal One of the hint enum values cast to a
/// double.
/// @return A shortened string representation of the hint enum:
/// e.g. GEOPM_REGION_HINT_MEMORY => "MEMORY".
std::string string_format_hint(double signal);
}
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
** This file is part of the Ovi services plugin for the Maps and
** Navigation API. The use of these services, whether by use of the
** plugin or by other means, is governed by the terms and conditions
** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in
** this package, located in the directory containing the Ovi services
** plugin source code.
**
****************************************************************************/
#include "qplacerestmanager.h"
#include <QtNetwork>
#include <QHash>
#include <qplacesearchquery.h>
#include <qgeoboundingcircle.h>
#include <qgeoboundingbox.h>
#include "qplacerestreply.h"
#if defined(QT_PLACES_LOGGING)
#include <QDebug>
#endif
QT_USE_NAMESPACE
const char *placesServerUrl = "http://places.maps.ovi.com/rest/v1/places/";
const char *searchServerUrl = "http://where.desktop.mos.svc.ovi.com/NOSe/json";
const char *recomendation = "/recommendations/nearby";
const char *reviews = "/reviews";
const char *images = "/images";
const char *categoriesTree = "categories/find-places/grouped";
const char *const_query = "&q=";
const char *const_lat = "&lat=";
const char *const_lon = "&lon=";
const char *const_top = "&vpn=";
const char *const_bottom = "&vps=";
const char *const_left = "&vpw=";
const char *const_right = "&vpe=";
const char *const_limit = "&to=";
const char *const_offset = "&of=";
const char *const_dym = "&dym=";
const char *const_views = "?vi=where"; // address, poi or where (both)
const char *const_deviceproductid = "&dv=oviMaps"; // oviMaps, ml, rv
const char *const_review_start = ";start=";
const char *const_review_limit = ";limit=";
static QString searchServer;
static QString placeServer;
QPlaceRestManager *QPlaceRestManager::mInstance = NULL;
/*!
Constructor.
*/
QPlaceRestManager::QPlaceRestManager(QObject *parent) :
QObject(parent),
mLocale(QLocale())
{
mManager = new QNetworkAccessManager(this);
if (searchServer.isNull()) {
QSettings settings("Nokia");
// no app name, they are in Nokia/OrganizationDefaults
searchServer = settings.value("searchURI").toString();
if (searchServer.isEmpty()) {
searchServer = searchServerUrl;
}
placeServer = settings.value("placesURI").toString();
if (placeServer.isEmpty()) {
placeServer = placesServerUrl;
}
}
}
/*!
Method creating instance of rest provider.
*/
QPlaceRestManager *QPlaceRestManager::instance()
{
if (!mInstance) {
mInstance = new QPlaceRestManager();
}
return mInstance;
}
/*!
Predefines a places request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendPlaceRequest(const QString &placeId)
{
return sendGeneralRequest(placeServer + placeId);
}
QPlaceRestReply *QPlaceRestManager::sendPlaceImagesRequest(const QString &placeId, const QPlaceQuery ¶ms)
{
QString query = placeServer + placeId + images;
if (params.offset() > -1) {
query += const_review_start + QString::number(params.offset());
}
if (params.limit() > 0) {
query += const_review_limit + QString::number(params.limit());
}
return sendGeneralRequest(query);
}
/*!
Predefines a review request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendPlaceReviewRequest(const QString &placeId, const QPlaceQuery ¶ms)
{
QString query = placeServer + placeId + reviews;
if (params.offset() > -1) {
query += const_review_start + QString::number(params.offset());
}
if (params.limit() > 0) {
query += const_review_limit + QString::number(params.limit());
}
return sendGeneralRequest(query);
}
/*!
Predefines a recomendation request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendRecommendationRequest(const QPlaceSearchQuery &query, const QString &userId)
{
Q_UNUSED(userId);
return sendGeneralRequest(placeServer + query.searchTerm() + recomendation);
}
/*!
Predefines a categories tree request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendCategoriesTreeRequest()
{
return sendGeneralRequest(placeServer + categoriesTree);
}
/*!
Predefines a suggestion request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendSuggestionRequest(const QPlaceSearchQuery &query)
{
return sendGeneralRequest(prepareSearchRequest(query)
+ const_query + query.searchTerm() + "&lh=1");
}
/*!
Predefines a search request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendSearchRequest(const QPlaceSearchQuery &query)
{
return sendGeneralRequest(prepareSearchRequest(query)
+ const_query + query.searchTerm());
}
QPlaceRestReply *QPlaceRestManager::postRatingRequest(const QString &placeId, const QString &userId, const int &value)
{
QNetworkRequest request;
QString url = placesServerUrl + placeId + "/ugc/ratings";
request.setUrl(url);
QByteArray language;
language.append(mLocale.name().toLatin1());
language.append(",");
language.append(mLocale.name().left(2).toLatin1());
request.setRawHeader("Accept-Language", language);
request.setRawHeader("Content-Type", "application/json");
request.setRawHeader("Accept", "application/json");
request.setRawHeader("X-Ovi-NcimUser", userId.toUtf8());
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: " + url;
#endif
QByteArray data = "{ratings:{rating:[{value:" + QString::number(value).toAscii() + ",type:OVERALL}]}}";
return new QPlaceRestReply(mManager->post(request, data));
}
QLocale QPlaceRestManager::locale() const
{
return mLocale;
}
void QPlaceRestManager::setLocale(const QLocale &locale)
{
mLocale = locale;
}
/*!
Sends a general predefined request. Is private.
*/
QPlaceRestReply *QPlaceRestManager::sendGeneralRequest(const QUrl &url)
{
QNetworkRequest request;
request.setUrl(url);
QByteArray language;
language.append(mLocale.name().toLatin1());
language.append(",");
language.append(mLocale.name().left(2).toLatin1());
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: Language - " + language;
#endif
request.setRawHeader("Accept-Language", language);
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: " + url.toString();
#endif
return new QPlaceRestReply(mManager->get(request));
}
/*!
Returns prepared search string.
*/
QString QPlaceRestManager::prepareSearchRequest(const QPlaceSearchQuery &query)
{
QString searchString(searchServer);
// add view and device parameters
searchString += const_views;
searchString += const_deviceproductid;
// process search center
if (query.searchArea() != NULL) {
if (query.searchArea()->type() == QGeoBoundingArea::CircleType) {
QGeoBoundingCircle * circle = static_cast<QGeoBoundingCircle *>(query.searchArea());
searchString += const_lat + QString::number(circle->center().latitude());
searchString += const_lon + QString::number(circle->center().longitude());
} else if (query.searchArea()->type() == QGeoBoundingArea::BoxType) {
QGeoBoundingBox *box = static_cast<QGeoBoundingBox *> (query.searchArea());
searchString += const_top + QString::number(box->topLeft().latitude());
searchString += const_left + QString::number(box->topLeft().longitude());
searchString += const_bottom + QString::number(box->bottomRight().latitude());
searchString += const_right + QString::number(box->bottomRight().longitude());
}
}
// processing limit
if (query.limit() > 0){
searchString += const_limit + QString::number(query.limit());
}
// processing offset
if (query.offset() > -1){
searchString += const_offset + QString::number(query.offset());
}
// process DYM
if (query.didYouMeanSuggestionNumber() > 0){
searchString += const_dym + QString::number(query.didYouMeanSuggestionNumber());
}
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::prepareSearchRequest: " + searchString;
#endif
return searchString;
}
<commit_msg>Fix REST query for reviews and media.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
** This file is part of the Ovi services plugin for the Maps and
** Navigation API. The use of these services, whether by use of the
** plugin or by other means, is governed by the terms and conditions
** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in
** this package, located in the directory containing the Ovi services
** plugin source code.
**
****************************************************************************/
#include "qplacerestmanager.h"
#include <QtNetwork>
#include <QHash>
#include <qplacesearchquery.h>
#include <qgeoboundingcircle.h>
#include <qgeoboundingbox.h>
#include "qplacerestreply.h"
#if defined(QT_PLACES_LOGGING)
#include <QDebug>
#endif
QT_USE_NAMESPACE
const char *placesServerUrl = "http://places.maps.ovi.com/rest/v1/places/";
const char *searchServerUrl = "http://where.desktop.mos.svc.ovi.com/NOSe/json";
const char *recomendation = "/recommendations/nearby";
const char *reviews = "/reviews?";
const char *images = "/images?";
const char *categoriesTree = "categories/find-places/grouped";
const char *const_query = "&q=";
const char *const_lat = "&lat=";
const char *const_lon = "&lon=";
const char *const_top = "&vpn=";
const char *const_bottom = "&vps=";
const char *const_left = "&vpw=";
const char *const_right = "&vpe=";
const char *const_limit = "&to=";
const char *const_offset = "&of=";
const char *const_dym = "&dym=";
const char *const_views = "?vi=where"; // address, poi or where (both)
const char *const_deviceproductid = "&dv=oviMaps"; // oviMaps, ml, rv
const char *const_review_start = "&start=";
const char *const_review_limit = "&limit=";
static QString searchServer;
static QString placeServer;
QPlaceRestManager *QPlaceRestManager::mInstance = NULL;
/*!
Constructor.
*/
QPlaceRestManager::QPlaceRestManager(QObject *parent) :
QObject(parent),
mLocale(QLocale())
{
mManager = new QNetworkAccessManager(this);
if (searchServer.isNull()) {
QSettings settings("Nokia");
// no app name, they are in Nokia/OrganizationDefaults
searchServer = settings.value("searchURI").toString();
if (searchServer.isEmpty()) {
searchServer = searchServerUrl;
}
placeServer = settings.value("placesURI").toString();
if (placeServer.isEmpty()) {
placeServer = placesServerUrl;
}
}
}
/*!
Method creating instance of rest provider.
*/
QPlaceRestManager *QPlaceRestManager::instance()
{
if (!mInstance) {
mInstance = new QPlaceRestManager();
}
return mInstance;
}
/*!
Predefines a places request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendPlaceRequest(const QString &placeId)
{
return sendGeneralRequest(placeServer + placeId);
}
QPlaceRestReply *QPlaceRestManager::sendPlaceImagesRequest(const QString &placeId, const QPlaceQuery ¶ms)
{
QString query = placeServer + placeId + images;
if (params.offset() > -1) {
query += const_review_start + QString::number(params.offset());
}
if (params.limit() > 0) {
query += const_review_limit + QString::number(params.limit());
}
return sendGeneralRequest(query);
}
/*!
Predefines a review request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendPlaceReviewRequest(const QString &placeId, const QPlaceQuery ¶ms)
{
QString query = placeServer + placeId + reviews;
if (params.offset() > -1) {
query += const_review_start + QString::number(params.offset());
}
if (params.limit() > 0) {
query += const_review_limit + QString::number(params.limit());
}
return sendGeneralRequest(query);
}
/*!
Predefines a recomendation request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendRecommendationRequest(const QPlaceSearchQuery &query, const QString &userId)
{
Q_UNUSED(userId);
return sendGeneralRequest(placeServer + query.searchTerm() + recomendation);
}
/*!
Predefines a categories tree request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendCategoriesTreeRequest()
{
return sendGeneralRequest(placeServer + categoriesTree);
}
/*!
Predefines a suggestion request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendSuggestionRequest(const QPlaceSearchQuery &query)
{
return sendGeneralRequest(prepareSearchRequest(query)
+ const_query + query.searchTerm() + "&lh=1");
}
/*!
Predefines a search request and executes sendGeneralRequest().
*/
QPlaceRestReply *QPlaceRestManager::sendSearchRequest(const QPlaceSearchQuery &query)
{
return sendGeneralRequest(prepareSearchRequest(query)
+ const_query + query.searchTerm());
}
QPlaceRestReply *QPlaceRestManager::postRatingRequest(const QString &placeId, const QString &userId, const int &value)
{
QNetworkRequest request;
QString url = placesServerUrl + placeId + "/ugc/ratings";
request.setUrl(url);
QByteArray language;
language.append(mLocale.name().toLatin1());
language.append(",");
language.append(mLocale.name().left(2).toLatin1());
request.setRawHeader("Accept-Language", language);
request.setRawHeader("Content-Type", "application/json");
request.setRawHeader("Accept", "application/json");
request.setRawHeader("X-Ovi-NcimUser", userId.toUtf8());
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: " + url;
#endif
QByteArray data = "{ratings:{rating:[{value:" + QString::number(value).toAscii() + ",type:OVERALL}]}}";
return new QPlaceRestReply(mManager->post(request, data));
}
QLocale QPlaceRestManager::locale() const
{
return mLocale;
}
void QPlaceRestManager::setLocale(const QLocale &locale)
{
mLocale = locale;
}
/*!
Sends a general predefined request. Is private.
*/
QPlaceRestReply *QPlaceRestManager::sendGeneralRequest(const QUrl &url)
{
QNetworkRequest request;
request.setUrl(url);
QByteArray language;
language.append(mLocale.name().toLatin1());
language.append(",");
language.append(mLocale.name().left(2).toLatin1());
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: Language - " + language;
#endif
request.setRawHeader("Accept-Language", language);
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::sendGeneralRequest: " + url.toString();
#endif
return new QPlaceRestReply(mManager->get(request));
}
/*!
Returns prepared search string.
*/
QString QPlaceRestManager::prepareSearchRequest(const QPlaceSearchQuery &query)
{
QString searchString(searchServer);
// add view and device parameters
searchString += const_views;
searchString += const_deviceproductid;
// process search center
if (query.searchArea() != NULL) {
if (query.searchArea()->type() == QGeoBoundingArea::CircleType) {
QGeoBoundingCircle * circle = static_cast<QGeoBoundingCircle *>(query.searchArea());
searchString += const_lat + QString::number(circle->center().latitude());
searchString += const_lon + QString::number(circle->center().longitude());
} else if (query.searchArea()->type() == QGeoBoundingArea::BoxType) {
QGeoBoundingBox *box = static_cast<QGeoBoundingBox *> (query.searchArea());
searchString += const_top + QString::number(box->topLeft().latitude());
searchString += const_left + QString::number(box->topLeft().longitude());
searchString += const_bottom + QString::number(box->bottomRight().latitude());
searchString += const_right + QString::number(box->bottomRight().longitude());
}
}
// processing limit
if (query.limit() > 0){
searchString += const_limit + QString::number(query.limit());
}
// processing offset
if (query.offset() > -1){
searchString += const_offset + QString::number(query.offset());
}
// process DYM
if (query.didYouMeanSuggestionNumber() > 0){
searchString += const_dym + QString::number(query.didYouMeanSuggestionNumber());
}
#if defined(QPLACES_LOGGING)
qDebug() << "QRestDataProvider::prepareSearchRequest: " + searchString;
#endif
return searchString;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdirectfbwindowsurface.h"
#include "qdirectfbscreen.h"
#include "qdirectfbpaintengine.h"
#include <private/qwidget_p.h>
#include <qwidget.h>
#include <qwindowsystem_qws.h>
#include <qpaintdevice.h>
#include <qvarlengtharray.h>
#ifndef QT_NO_QWS_DIRECTFB
QT_BEGIN_NAMESPACE
QDirectFBWindowSurface::QDirectFBWindowSurface(DFBSurfaceFlipFlags flip, QDirectFBScreen *scr)
: QDirectFBPaintDevice(scr)
, sibling(0)
#ifndef QT_NO_DIRECTFB_WM
, dfbWindow(0)
#endif
, flipFlags(flip)
, boundingRectFlip(scr->directFBFlags() & QDirectFBScreen::BoundingRectFlip)
{
#ifdef QT_NO_DIRECTFB_WM
mode = Offscreen;
#endif
setSurfaceFlags(Opaque | Buffered);
#ifdef QT_DIRECTFB_TIMING
frames = 0;
timer.start();
#endif
}
QDirectFBWindowSurface::QDirectFBWindowSurface(DFBSurfaceFlipFlags flip, QDirectFBScreen *scr, QWidget *widget)
: QWSWindowSurface(widget), QDirectFBPaintDevice(scr)
, sibling(0)
#ifndef QT_NO_DIRECTFB_WM
, dfbWindow(0)
#endif
, flipFlags(flip)
, boundingRectFlip(scr->directFBFlags() & QDirectFBScreen::BoundingRectFlip)
{
SurfaceFlags flags = 0;
if (!widget || widget->window()->windowOpacity() == 0xff)
flags |= Opaque;
#ifdef QT_NO_DIRECTFB_WM
if (widget && widget->testAttribute(Qt::WA_PaintOnScreen)) {
flags = RegionReserved;
mode = Primary;
} else {
mode = Offscreen;
flags = Buffered;
}
#else
noSystemBackground = widget && widget->testAttribute(Qt::WA_NoSystemBackground);
if (noSystemBackground)
flags &= ~Opaque;
#endif
setSurfaceFlags(flags);
#ifdef QT_DIRECTFB_TIMING
frames = 0;
timer.start();
#endif
}
QDirectFBWindowSurface::~QDirectFBWindowSurface()
{
releaseSurface();
// these are not tracked by QDirectFBScreen so we don't want QDirectFBPaintDevice to release it
}
bool QDirectFBWindowSurface::isValid() const
{
return true;
}
#ifdef QT_DIRECTFB_WM
void QDirectFBWindowSurface::raise()
{
if (IDirectFBWindow *window = directFBWindow()) {
window->RaiseToTop(window);
}
}
IDirectFBWindow *QDirectFBWindowSurface::directFBWindow() const
{
return (dfbWindow ? dfbWindow : (sibling ? sibling->dfbWindow : 0));
}
void QDirectFBWindowSurface::createWindow(const QRect &rect)
{
IDirectFBDisplayLayer *layer = screen->dfbDisplayLayer();
if (!layer)
qFatal("QDirectFBWindowSurface: Unable to get primary display layer!");
DFBWindowDescription description;
memset(&description, 0, sizeof(DFBWindowDescription));
description.caps = DWCAPS_NODECORATION|DWCAPS_DOUBLEBUFFER;
description.flags = DWDESC_CAPS|DWDESC_SURFACE_CAPS|DWDESC_PIXELFORMAT|DWDESC_HEIGHT|DWDESC_WIDTH|DWDESC_POSX|DWDESC_POSY;
#if (Q_DIRECTFB_VERSION >= 0x010200)
description.flags |= DWDESC_OPTIONS;
#endif
if (noSystemBackground) {
description.caps |= DWCAPS_ALPHACHANNEL;
#if (Q_DIRECTFB_VERSION >= 0x010200)
description.options |= DWOP_ALPHACHANNEL;
#endif
}
description.posx = rect.x();
description.posy = rect.y();
description.width = rect.width();
description.height = rect.height();
description.surface_caps = DSCAPS_NONE;
if (screen->directFBFlags() & QDirectFBScreen::VideoOnly)
description.surface_caps |= DSCAPS_VIDEOONLY;
const QImage::Format format = (noSystemBackground ? screen->alphaPixmapFormat() : screen->pixelFormat());
description.pixelformat = QDirectFBScreen::getSurfacePixelFormat(format);
if (QDirectFBScreen::isPremultiplied(format))
description.surface_caps = DSCAPS_PREMULTIPLIED;
DFBResult result = layer->CreateWindow(layer, &description, &dfbWindow);
if (result != DFB_OK)
DirectFBErrorFatal("QDirectFBWindowSurface::createWindow", result);
Q_ASSERT(!dfbSurface);
dfbWindow->GetSurface(dfbWindow, &dfbSurface);
updateFormat();
}
static DFBResult setWindowGeometry(IDirectFBWindow *dfbWindow, const QRect &old, const QRect &rect)
{
DFBResult result = DFB_OK;
const bool isMove = old.isEmpty() || rect.topLeft() != old.topLeft();
const bool isResize = rect.size() != old.size();
#if (Q_DIRECTFB_VERSION >= 0x010000)
if (isResize && isMove) {
result = dfbWindow->SetBounds(dfbWindow, rect.x(), rect.y(),
rect.width(), rect.height());
} else if (isResize) {
result = dfbWindow->Resize(dfbWindow,
rect.width(), rect.height());
} else if (isMove) {
result = dfbWindow->MoveTo(dfbWindow, rect.x(), rect.y());
}
#else
if (isResize) {
result = dfbWindow->Resize(dfbWindow,
rect.width(), rect.height());
}
if (isMove) {
result = dfbWindow->MoveTo(dfbWindow, rect.x(), rect.y());
}
#endif
return result;
}
#endif // QT_NO_DIRECTFB_WM
void QDirectFBWindowSurface::setGeometry(const QRect &rect)
{
const QRect oldRect = geometry();
if (oldRect == rect)
return;
IDirectFBSurface *oldSurface = dfbSurface;
const bool sizeChanged = oldRect.size() != rect.size();
if (sizeChanged) {
delete engine;
engine = 0;
releaseSurface();
Q_ASSERT(!dfbSurface);
}
if (rect.isNull()) {
#ifndef QT_NO_DIRECTFB_WM
if (dfbWindow) {
dfbWindow->Release(dfbWindow);
dfbWindow = 0;
}
#endif
Q_ASSERT(!dfbSurface);
#ifdef QT_DIRECTFB_SUBSURFACE
Q_ASSERT(!subSurface);
#endif
} else {
#ifdef QT_DIRECTFB_WM
if (!dfbWindow) {
createWindow(rect);
} else {
setWindowGeometry(dfbWindow, oldRect, rect);
Q_ASSERT(!sizeChanged || !dfbSurface);
if (sizeChanged)
dfbWindow->GetSurface(dfbWindow, &dfbSurface);
}
#else
IDirectFBSurface *primarySurface = screen->primarySurface();
DFBResult result = DFB_OK;
if (mode == Primary) {
Q_ASSERT(primarySurface);
if (rect == screen->region().boundingRect()) {
dfbSurface = primarySurface;
} else {
const DFBRectangle r = { rect.x(), rect.y(),
rect.width(), rect.height() };
result = primarySurface->GetSubSurface(primarySurface, &r, &dfbSurface);
}
} else { // mode == Offscreen
if (!dfbSurface) {
dfbSurface = screen->createDFBSurface(rect.size(), screen->pixelFormat(), QDirectFBScreen::DontTrackSurface);
}
}
if (result != DFB_OK)
DirectFBErrorFatal("QDirectFBWindowSurface::setGeometry()", result);
#endif
}
if (oldSurface != dfbSurface)
updateFormat();
if (oldRect.size() != rect.size()) {
QWSWindowSurface::setGeometry(rect);
} else {
QWindowSurface::setGeometry(rect);
}
}
QByteArray QDirectFBWindowSurface::permanentState() const
{
QByteArray state(sizeof(this), 0);
*reinterpret_cast<const QDirectFBWindowSurface**>(state.data()) = this;
return state;
}
void QDirectFBWindowSurface::setPermanentState(const QByteArray &state)
{
if (state.size() == sizeof(this)) {
sibling = *reinterpret_cast<QDirectFBWindowSurface *const*>(state.constData());
Q_ASSERT(sibling);
sibling->setSurfaceFlags(surfaceFlags());
}
}
static inline void scrollSurface(IDirectFBSurface *surface, const QRect &r, int dx, int dy)
{
const DFBRectangle rect = { r.x(), r.y(), r.width(), r.height() };
surface->Blit(surface, surface, &rect, r.x() + dx, r.y() + dy);
const DFBRegion region = { rect.x + dx, rect.y + dy, r.right() + dx, r.bottom() + dy };
surface->Flip(surface, ®ion, DSFLIP_BLIT);
}
bool QDirectFBWindowSurface::scroll(const QRegion ®ion, int dx, int dy)
{
if (!dfbSurface || !(flipFlags & DSFLIP_BLIT) || region.isEmpty())
return false;
dfbSurface->SetBlittingFlags(dfbSurface, DSBLIT_NOFX);
if (region.numRects() == 1) {
scrollSurface(dfbSurface, region.boundingRect(), dx, dy);
} else {
const QVector<QRect> rects = region.rects();
const int n = rects.size();
for (int i=0; i<n; ++i) {
scrollSurface(dfbSurface, rects.at(i), dx, dy);
}
}
return true;
}
bool QDirectFBWindowSurface::move(const QPoint &moveBy)
{
setGeometry(geometry().translated(moveBy));
return true;
}
void QDirectFBWindowSurface::setOpaque(bool opaque)
{
SurfaceFlags flags = surfaceFlags();
if (opaque != (flags & Opaque)) {
if (opaque) {
flags |= Opaque;
} else {
flags &= ~Opaque;
}
setSurfaceFlags(flags);
}
}
void QDirectFBWindowSurface::flush(QWidget *widget, const QRegion ®ion,
const QPoint &offset)
{
QWidget *win = window();
if (!win)
return;
QWExtra *extra = qt_widget_private(widget)->extraData();
if (extra && extra->proxyWidget)
return;
const quint8 windowOpacity = quint8(win->windowOpacity() * 0xff);
const QRect windowGeometry = geometry();
#ifdef QT_DIRECTFB_WM
const bool wasNoSystemBackground = noSystemBackground;
noSystemBackground = win->testAttribute(Qt::WA_NoSystemBackground);
quint8 currentOpacity;
Q_ASSERT(dfbWindow);
dfbWindow->GetOpacity(dfbWindow, ¤tOpacity);
if (currentOpacity != windowOpacity) {
dfbWindow->SetOpacity(dfbWindow, windowOpacity);
}
setOpaque(noSystemBackground || windowOpacity != 0xff);
if (wasNoSystemBackground != noSystemBackground) {
releaseSurface();
dfbWindow->Release(dfbWindow);
dfbWindow = 0;
createWindow(windowGeometry);
win->update();
return;
}
screen->flipSurface(dfbSurface, flipFlags, region, offset);
if (noSystemBackground) {
dfbSurface->Clear(dfbSurface, 0, 0, 0, 0);
}
#else
setOpaque(windowOpacity != 0xff);
if (mode == Offscreen) {
screen->exposeRegion(region.translated(offset + geometry().topLeft()), 0);
} else {
screen->flipSurface(dfbSurface, flipFlags, region, offset);
}
#endif
#ifdef QT_DIRECTFB_TIMING
enum { Secs = 3 };
++frames;
if (timer.elapsed() >= Secs * 1000) {
qDebug("%d fps", int(double(frames) / double(Secs)));
frames = 0;
timer.restart();
}
#endif
}
void QDirectFBWindowSurface::beginPaint(const QRegion &)
{
if (!engine) {
engine = new QDirectFBPaintEngine(this);
}
}
void QDirectFBWindowSurface::endPaint(const QRegion &)
{
#ifdef QT_NO_DIRECTFB_SUBSURFACE
unlockSurface();
#endif
}
IDirectFBSurface *QDirectFBWindowSurface::directFBSurface() const
{
if (!dfbSurface && sibling && sibling->dfbSurface)
return sibling->dfbSurface;
return dfbSurface;
}
IDirectFBSurface *QDirectFBWindowSurface::surfaceForWidget(const QWidget *widget, QRect *rect) const
{
Q_ASSERT(widget);
if (!dfbSurface) {
if (sibling && (!sibling->sibling || sibling->dfbSurface))
return sibling->surfaceForWidget(widget, rect);
return 0;
}
QWidget *win = window();
Q_ASSERT(win);
if (rect) {
if (win == widget) {
*rect = widget->rect();
} else {
*rect = QRect(widget->mapTo(win, QPoint(0, 0)), widget->size());
}
}
Q_ASSERT(win == widget || win->isAncestorOf(widget));
return dfbSurface;
}
void QDirectFBWindowSurface::updateFormat()
{
imageFormat = dfbSurface ? QDirectFBScreen::getImageFormat(dfbSurface) : QImage::Format_Invalid;
}
void QDirectFBWindowSurface::releaseSurface()
{
if (dfbSurface) {
#ifdef QT_DIRECTFB_SUBSURFACE
releaseSubSurface();
#else
unlockSurface();
#endif
#ifdef QT_NO_DIRECTFB_WM
Q_ASSERT(screen->primarySurface());
if (dfbSurface != screen->primarySurface())
#endif
dfbSurface->Release(dfbSurface);
dfbSurface = 0;
}
}
QT_END_NAMESPACE
#endif // QT_NO_QWS_DIRECTFB
<commit_msg>Store DirectFB winID as a dynamic property<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdirectfbwindowsurface.h"
#include "qdirectfbscreen.h"
#include "qdirectfbpaintengine.h"
#include <private/qwidget_p.h>
#include <qwidget.h>
#include <qwindowsystem_qws.h>
#include <qpaintdevice.h>
#include <qvarlengtharray.h>
#ifndef QT_NO_QWS_DIRECTFB
QT_BEGIN_NAMESPACE
QDirectFBWindowSurface::QDirectFBWindowSurface(DFBSurfaceFlipFlags flip, QDirectFBScreen *scr)
: QDirectFBPaintDevice(scr)
, sibling(0)
#ifndef QT_NO_DIRECTFB_WM
, dfbWindow(0)
#endif
, flipFlags(flip)
, boundingRectFlip(scr->directFBFlags() & QDirectFBScreen::BoundingRectFlip)
{
#ifdef QT_NO_DIRECTFB_WM
mode = Offscreen;
#endif
setSurfaceFlags(Opaque | Buffered);
#ifdef QT_DIRECTFB_TIMING
frames = 0;
timer.start();
#endif
}
QDirectFBWindowSurface::QDirectFBWindowSurface(DFBSurfaceFlipFlags flip, QDirectFBScreen *scr, QWidget *widget)
: QWSWindowSurface(widget), QDirectFBPaintDevice(scr)
, sibling(0)
#ifndef QT_NO_DIRECTFB_WM
, dfbWindow(0)
#endif
, flipFlags(flip)
, boundingRectFlip(scr->directFBFlags() & QDirectFBScreen::BoundingRectFlip)
{
SurfaceFlags flags = 0;
if (!widget || widget->window()->windowOpacity() == 0xff)
flags |= Opaque;
#ifdef QT_NO_DIRECTFB_WM
if (widget && widget->testAttribute(Qt::WA_PaintOnScreen)) {
flags = RegionReserved;
mode = Primary;
} else {
mode = Offscreen;
flags = Buffered;
}
#else
noSystemBackground = widget && widget->testAttribute(Qt::WA_NoSystemBackground);
if (noSystemBackground)
flags &= ~Opaque;
#endif
setSurfaceFlags(flags);
#ifdef QT_DIRECTFB_TIMING
frames = 0;
timer.start();
#endif
}
QDirectFBWindowSurface::~QDirectFBWindowSurface()
{
releaseSurface();
// these are not tracked by QDirectFBScreen so we don't want QDirectFBPaintDevice to release it
}
bool QDirectFBWindowSurface::isValid() const
{
return true;
}
#ifdef QT_DIRECTFB_WM
void QDirectFBWindowSurface::raise()
{
if (IDirectFBWindow *window = directFBWindow()) {
window->RaiseToTop(window);
}
}
IDirectFBWindow *QDirectFBWindowSurface::directFBWindow() const
{
return (dfbWindow ? dfbWindow : (sibling ? sibling->dfbWindow : 0));
}
void QDirectFBWindowSurface::createWindow(const QRect &rect)
{
IDirectFBDisplayLayer *layer = screen->dfbDisplayLayer();
if (!layer)
qFatal("QDirectFBWindowSurface: Unable to get primary display layer!");
DFBWindowDescription description;
memset(&description, 0, sizeof(DFBWindowDescription));
description.caps = DWCAPS_NODECORATION|DWCAPS_DOUBLEBUFFER;
description.flags = DWDESC_CAPS|DWDESC_SURFACE_CAPS|DWDESC_PIXELFORMAT|DWDESC_HEIGHT|DWDESC_WIDTH|DWDESC_POSX|DWDESC_POSY;
#if (Q_DIRECTFB_VERSION >= 0x010200)
description.flags |= DWDESC_OPTIONS;
#endif
if (noSystemBackground) {
description.caps |= DWCAPS_ALPHACHANNEL;
#if (Q_DIRECTFB_VERSION >= 0x010200)
description.options |= DWOP_ALPHACHANNEL;
#endif
}
description.posx = rect.x();
description.posy = rect.y();
description.width = rect.width();
description.height = rect.height();
description.surface_caps = DSCAPS_NONE;
if (screen->directFBFlags() & QDirectFBScreen::VideoOnly)
description.surface_caps |= DSCAPS_VIDEOONLY;
const QImage::Format format = (noSystemBackground ? screen->alphaPixmapFormat() : screen->pixelFormat());
description.pixelformat = QDirectFBScreen::getSurfacePixelFormat(format);
if (QDirectFBScreen::isPremultiplied(format))
description.surface_caps = DSCAPS_PREMULTIPLIED;
DFBResult result = layer->CreateWindow(layer, &description, &dfbWindow);
if (result != DFB_OK)
DirectFBErrorFatal("QDirectFBWindowSurface::createWindow", result);
if (window()) {
DFBWindowID winid;
result = dfbWindow->GetID(dfbWindow, &winid);
if (result != DFB_OK) {
DirectFBError("QDirectFBWindowSurface::createWindow. Can't get ID", result);
} else {
window()->setProperty("_q_DirectFBWindowID", winid);
}
}
Q_ASSERT(!dfbSurface);
dfbWindow->GetSurface(dfbWindow, &dfbSurface);
updateFormat();
}
static DFBResult setWindowGeometry(IDirectFBWindow *dfbWindow, const QRect &old, const QRect &rect)
{
DFBResult result = DFB_OK;
const bool isMove = old.isEmpty() || rect.topLeft() != old.topLeft();
const bool isResize = rect.size() != old.size();
#if (Q_DIRECTFB_VERSION >= 0x010000)
if (isResize && isMove) {
result = dfbWindow->SetBounds(dfbWindow, rect.x(), rect.y(),
rect.width(), rect.height());
} else if (isResize) {
result = dfbWindow->Resize(dfbWindow,
rect.width(), rect.height());
} else if (isMove) {
result = dfbWindow->MoveTo(dfbWindow, rect.x(), rect.y());
}
#else
if (isResize) {
result = dfbWindow->Resize(dfbWindow,
rect.width(), rect.height());
}
if (isMove) {
result = dfbWindow->MoveTo(dfbWindow, rect.x(), rect.y());
}
#endif
return result;
}
#endif // QT_NO_DIRECTFB_WM
void QDirectFBWindowSurface::setGeometry(const QRect &rect)
{
const QRect oldRect = geometry();
if (oldRect == rect)
return;
IDirectFBSurface *oldSurface = dfbSurface;
const bool sizeChanged = oldRect.size() != rect.size();
if (sizeChanged) {
delete engine;
engine = 0;
releaseSurface();
Q_ASSERT(!dfbSurface);
}
if (rect.isNull()) {
#ifndef QT_NO_DIRECTFB_WM
if (dfbWindow) {
if (window())
window()->setProperty("_q_DirectFBWindowID", QVariant());
dfbWindow->Release(dfbWindow);
dfbWindow = 0;
}
#endif
Q_ASSERT(!dfbSurface);
#ifdef QT_DIRECTFB_SUBSURFACE
Q_ASSERT(!subSurface);
#endif
} else {
#ifdef QT_DIRECTFB_WM
if (!dfbWindow) {
createWindow(rect);
} else {
setWindowGeometry(dfbWindow, oldRect, rect);
Q_ASSERT(!sizeChanged || !dfbSurface);
if (sizeChanged)
dfbWindow->GetSurface(dfbWindow, &dfbSurface);
}
#else
IDirectFBSurface *primarySurface = screen->primarySurface();
DFBResult result = DFB_OK;
if (mode == Primary) {
Q_ASSERT(primarySurface);
if (rect == screen->region().boundingRect()) {
dfbSurface = primarySurface;
} else {
const DFBRectangle r = { rect.x(), rect.y(),
rect.width(), rect.height() };
result = primarySurface->GetSubSurface(primarySurface, &r, &dfbSurface);
}
} else { // mode == Offscreen
if (!dfbSurface) {
dfbSurface = screen->createDFBSurface(rect.size(), screen->pixelFormat(), QDirectFBScreen::DontTrackSurface);
}
}
if (result != DFB_OK)
DirectFBErrorFatal("QDirectFBWindowSurface::setGeometry()", result);
#endif
}
if (oldSurface != dfbSurface)
updateFormat();
if (oldRect.size() != rect.size()) {
QWSWindowSurface::setGeometry(rect);
} else {
QWindowSurface::setGeometry(rect);
}
}
QByteArray QDirectFBWindowSurface::permanentState() const
{
QByteArray state(sizeof(this), 0);
*reinterpret_cast<const QDirectFBWindowSurface**>(state.data()) = this;
return state;
}
void QDirectFBWindowSurface::setPermanentState(const QByteArray &state)
{
if (state.size() == sizeof(this)) {
sibling = *reinterpret_cast<QDirectFBWindowSurface *const*>(state.constData());
Q_ASSERT(sibling);
sibling->setSurfaceFlags(surfaceFlags());
}
}
static inline void scrollSurface(IDirectFBSurface *surface, const QRect &r, int dx, int dy)
{
const DFBRectangle rect = { r.x(), r.y(), r.width(), r.height() };
surface->Blit(surface, surface, &rect, r.x() + dx, r.y() + dy);
const DFBRegion region = { rect.x + dx, rect.y + dy, r.right() + dx, r.bottom() + dy };
surface->Flip(surface, ®ion, DSFLIP_BLIT);
}
bool QDirectFBWindowSurface::scroll(const QRegion ®ion, int dx, int dy)
{
if (!dfbSurface || !(flipFlags & DSFLIP_BLIT) || region.isEmpty())
return false;
dfbSurface->SetBlittingFlags(dfbSurface, DSBLIT_NOFX);
if (region.numRects() == 1) {
scrollSurface(dfbSurface, region.boundingRect(), dx, dy);
} else {
const QVector<QRect> rects = region.rects();
const int n = rects.size();
for (int i=0; i<n; ++i) {
scrollSurface(dfbSurface, rects.at(i), dx, dy);
}
}
return true;
}
bool QDirectFBWindowSurface::move(const QPoint &moveBy)
{
setGeometry(geometry().translated(moveBy));
return true;
}
void QDirectFBWindowSurface::setOpaque(bool opaque)
{
SurfaceFlags flags = surfaceFlags();
if (opaque != (flags & Opaque)) {
if (opaque) {
flags |= Opaque;
} else {
flags &= ~Opaque;
}
setSurfaceFlags(flags);
}
}
void QDirectFBWindowSurface::flush(QWidget *widget, const QRegion ®ion,
const QPoint &offset)
{
QWidget *win = window();
if (!win)
return;
QWExtra *extra = qt_widget_private(widget)->extraData();
if (extra && extra->proxyWidget)
return;
const quint8 windowOpacity = quint8(win->windowOpacity() * 0xff);
const QRect windowGeometry = geometry();
#ifdef QT_DIRECTFB_WM
const bool wasNoSystemBackground = noSystemBackground;
noSystemBackground = win->testAttribute(Qt::WA_NoSystemBackground);
quint8 currentOpacity;
Q_ASSERT(dfbWindow);
dfbWindow->GetOpacity(dfbWindow, ¤tOpacity);
if (currentOpacity != windowOpacity) {
dfbWindow->SetOpacity(dfbWindow, windowOpacity);
}
setOpaque(noSystemBackground || windowOpacity != 0xff);
if (wasNoSystemBackground != noSystemBackground) {
releaseSurface();
dfbWindow->Release(dfbWindow);
dfbWindow = 0;
createWindow(windowGeometry);
win->update();
return;
}
screen->flipSurface(dfbSurface, flipFlags, region, offset);
if (noSystemBackground) {
dfbSurface->Clear(dfbSurface, 0, 0, 0, 0);
}
#else
setOpaque(windowOpacity != 0xff);
if (mode == Offscreen) {
screen->exposeRegion(region.translated(offset + geometry().topLeft()), 0);
} else {
screen->flipSurface(dfbSurface, flipFlags, region, offset);
}
#endif
#ifdef QT_DIRECTFB_TIMING
enum { Secs = 3 };
++frames;
if (timer.elapsed() >= Secs * 1000) {
qDebug("%d fps", int(double(frames) / double(Secs)));
frames = 0;
timer.restart();
}
#endif
}
void QDirectFBWindowSurface::beginPaint(const QRegion &)
{
if (!engine) {
engine = new QDirectFBPaintEngine(this);
}
}
void QDirectFBWindowSurface::endPaint(const QRegion &)
{
#ifdef QT_NO_DIRECTFB_SUBSURFACE
unlockSurface();
#endif
}
IDirectFBSurface *QDirectFBWindowSurface::directFBSurface() const
{
if (!dfbSurface && sibling && sibling->dfbSurface)
return sibling->dfbSurface;
return dfbSurface;
}
IDirectFBSurface *QDirectFBWindowSurface::surfaceForWidget(const QWidget *widget, QRect *rect) const
{
Q_ASSERT(widget);
if (!dfbSurface) {
if (sibling && (!sibling->sibling || sibling->dfbSurface))
return sibling->surfaceForWidget(widget, rect);
return 0;
}
QWidget *win = window();
Q_ASSERT(win);
if (rect) {
if (win == widget) {
*rect = widget->rect();
} else {
*rect = QRect(widget->mapTo(win, QPoint(0, 0)), widget->size());
}
}
Q_ASSERT(win == widget || win->isAncestorOf(widget));
return dfbSurface;
}
void QDirectFBWindowSurface::updateFormat()
{
imageFormat = dfbSurface ? QDirectFBScreen::getImageFormat(dfbSurface) : QImage::Format_Invalid;
}
void QDirectFBWindowSurface::releaseSurface()
{
if (dfbSurface) {
#ifdef QT_DIRECTFB_SUBSURFACE
releaseSubSurface();
#else
unlockSurface();
#endif
#ifdef QT_NO_DIRECTFB_WM
Q_ASSERT(screen->primarySurface());
if (dfbSurface != screen->primarySurface())
#endif
dfbSurface->Release(dfbSurface);
dfbSurface = 0;
}
}
QT_END_NAMESPACE
#endif // QT_NO_QWS_DIRECTFB
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "drt.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/directlighting.h"
#include "renderer/kernel/lighting/imagebasedlighting.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/environment/environment.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/mis.h"
#include "foundation/math/population.h"
#include "foundation/utility/memory.h"
#include "foundation/utility/string.h"
// Forward declarations.
namespace renderer { class EnvironmentEDF; }
namespace renderer { class InputParams; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Distribution Ray Tracing (DRT) lighting engine.
//
class DRTLightingEngine
: public ILightingEngine
{
public:
DRTLightingEngine(
const LightSampler& light_sampler,
const ParamArray& params)
: m_params(params)
, m_light_sampler(light_sampler)
{
}
~DRTLightingEngine()
{
RENDERER_LOG_DEBUG(
"distribution ray tracing statistics:\n"
" paths %s\n"
" ray tree depth avg %.1f min %s max %s dev %.1f\n",
pretty_uint(m_stats.m_path_count).c_str(),
m_stats.m_ray_tree_depth.get_avg(),
pretty_uint(m_stats.m_ray_tree_depth.get_min()).c_str(),
pretty_uint(m_stats.m_ray_tree_depth.get_max()).c_str(),
m_stats.m_ray_tree_depth.get_dev());
}
virtual void release()
{
delete this;
}
virtual void compute_lighting(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
Spectrum& radiance) // output radiance, in W.sr^-1.m^-2
{
typedef PathTracer<
PathVisitor,
BSDF::Glossy | BSDF::Specular,
false // not adjoint
> PathTracer;
PathVisitor path_visitor(
m_params,
m_light_sampler,
m_light_samples,
shading_context,
shading_point.get_scene(),
radiance);
PathTracer path_tracer(
path_visitor,
m_params.m_minimum_path_length);
const size_t path_length =
path_tracer.trace(
sampling_context,
shading_context.get_intersector(),
shading_context.get_texture_cache(),
shading_point);
// Update statistics.
++m_stats.m_path_count;
m_stats.m_ray_tree_depth.insert(path_length);
}
private:
struct Parameters
{
const size_t m_max_reflection_depth; // maximum reflection depth
const size_t m_max_refraction_depth; // maximum refraction depth
const size_t m_minimum_path_length; // minimum path length before Russian Roulette is used
const size_t m_dl_sample_count; // number of samples used to estimate direct illumination
const size_t m_ibl_bsdf_sample_count; // number of samples (in BSDF sampling) used to estimate IBL
const size_t m_ibl_env_sample_count; // number of samples (in environment sampling) used to estimate IBL
// Constructor, extract parameters.
explicit Parameters(const ParamArray& params)
: m_max_reflection_depth ( params.get_optional<size_t>("max_reflection_depth", 8) )
, m_max_refraction_depth ( params.get_optional<size_t>("max_refraction_depth", 8) )
, m_minimum_path_length ( params.get_optional<size_t>("minimum_path_length", 3) )
, m_dl_sample_count ( params.get_optional<size_t>("dl_samples", 1) )
, m_ibl_bsdf_sample_count ( params.get_optional<size_t>("ibl_bsdf_samples", 2) )
, m_ibl_env_sample_count ( params.get_optional<size_t>("ibl_env_samples", 2) )
{
}
};
struct Statistics
{
uint64 m_path_count; // number of paths
Population<size_t> m_ray_tree_depth; // ray tree depth
Statistics()
: m_path_count(0)
{
}
};
class PathVisitor
{
public:
PathVisitor(
const Parameters& params,
const LightSampler& light_sampler,
LightSampleVector& light_samples,
const ShadingContext& shading_context,
const Scene& scene,
Spectrum& path_radiance)
: m_params(params)
, m_light_sampler(light_sampler)
, m_light_samples(light_samples)
, m_shading_context(shading_context)
, m_texture_cache(shading_context.get_texture_cache())
, m_path_radiance(path_radiance)
{
const Environment* environment = scene.get_environment();
m_env_edf = environment ? environment->get_environment_edf() : 0;
m_path_radiance.set(0.0f);
}
bool visit_vertex(
SamplingContext& sampling_context,
const ShadingPoint& shading_point,
const Vector3d& outgoing,
const BSDF* bsdf,
const void* bsdf_data,
const BSDF::Mode bsdf_mode,
const double bsdf_prob,
const Spectrum& throughput)
{
const Vector3d& point = shading_point.get_point();
const Vector3d& geometric_normal = shading_point.get_geometric_normal();
const Vector3d& shading_normal = shading_point.get_shading_normal();
const Basis3d& shading_basis = shading_point.get_shading_basis();
const Material* material = shading_point.get_material();
const InputParams& input_params = shading_point.get_input_params();
// Generate light samples.
clear_keep_memory(m_light_samples);
m_light_sampler.sample(
sampling_context,
m_params.m_dl_sample_count,
m_light_samples);
// Compute direct lighting.
Spectrum vertex_radiance;
compute_direct_lighting(
sampling_context,
m_shading_context,
point,
geometric_normal,
shading_basis,
outgoing,
*bsdf,
bsdf_data,
m_light_samples,
vertex_radiance,
&shading_point);
if (m_env_edf)
{
// Compute image-based lighting.
Spectrum ibl_radiance;
compute_image_based_lighting(
sampling_context,
m_shading_context,
*m_env_edf,
point,
geometric_normal,
shading_basis,
outgoing,
*bsdf,
bsdf_data,
m_params.m_ibl_bsdf_sample_count,
m_params.m_ibl_env_sample_count,
ibl_radiance,
&shading_point);
vertex_radiance += ibl_radiance;
}
// Retrieve the EDF.
const EDF* edf = material->get_edf();
if (edf)
{
// Evaluate the input values of the EDF (if any).
InputEvaluator edf_input_evaluator(m_texture_cache);
const void* edf_data =
edf_input_evaluator.evaluate(
edf->get_inputs(),
input_params);
// Compute the emitted radiance.
Spectrum emitted_radiance;
edf->evaluate(
edf_data,
geometric_normal,
shading_basis,
outgoing,
emitted_radiance);
const double distance = shading_point.get_distance();
if (bsdf_mode != BSDF::Specular && distance > 0.0)
{
// Compute the probability density with respect to surface area
// of choosing this point through sampling of the light sources.
const double sample_probability =
m_light_sampler.evaluate_pdf(shading_point);
// Compute the probability density with respect to surface area
// of the direction obtained through sampling of the BSDF.
double px = bsdf_prob;
px *= max(dot(outgoing, shading_normal), 0.0);
px /= square(distance);
// Multiply the emitted radiance by the MIS weight.
const double mis_weight = mis_power2(px, sample_probability);
emitted_radiance *= static_cast<float>(mis_weight);
}
vertex_radiance += emitted_radiance;
}
// Update the path radiance.
vertex_radiance *= throughput;
m_path_radiance += vertex_radiance;
// Proceed with this path.
return true;
}
void visit_environment(
const ShadingPoint& shading_point,
const Vector3d& outgoing,
const Spectrum& throughput)
{
}
private:
const Parameters& m_params;
const LightSampler& m_light_sampler;
LightSampleVector& m_light_samples;
const ShadingContext& m_shading_context;
TextureCache& m_texture_cache;
const EnvironmentEDF* m_env_edf;
Spectrum& m_path_radiance;
};
const Parameters m_params;
Statistics m_stats;
const LightSampler& m_light_sampler;
LightSampleVector m_light_samples;
};
}
//
// DRTLightingEngineFactory class implementation.
//
DRTLightingEngineFactory::DRTLightingEngineFactory(
const LightSampler& light_sampler,
const ParamArray& params)
: m_light_sampler(light_sampler)
, m_params(params)
{
}
void DRTLightingEngineFactory::release()
{
delete this;
}
ILightingEngine* DRTLightingEngineFactory::create()
{
return new DRTLightingEngine(m_light_sampler, m_params);
}
ILightingEngine* DRTLightingEngineFactory::create(
const LightSampler& light_sampler,
const ParamArray& params)
{
return new DRTLightingEngine(light_sampler, params);
}
} // namespace renderer
<commit_msg>removed unused parameters.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "drt.h"
// appleseed.renderer headers.
#include "renderer/kernel/lighting/directlighting.h"
#include "renderer/kernel/lighting/imagebasedlighting.h"
#include "renderer/kernel/lighting/lightsampler.h"
#include "renderer/kernel/lighting/pathtracer.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bsdf/bsdf.h"
#include "renderer/modeling/edf/edf.h"
#include "renderer/modeling/environment/environment.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/mis.h"
#include "foundation/math/population.h"
#include "foundation/utility/memory.h"
#include "foundation/utility/string.h"
// Forward declarations.
namespace renderer { class EnvironmentEDF; }
namespace renderer { class InputParams; }
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
//
// Distribution Ray Tracing (DRT) lighting engine.
//
class DRTLightingEngine
: public ILightingEngine
{
public:
DRTLightingEngine(
const LightSampler& light_sampler,
const ParamArray& params)
: m_params(params)
, m_light_sampler(light_sampler)
{
}
~DRTLightingEngine()
{
RENDERER_LOG_DEBUG(
"distribution ray tracing statistics:\n"
" paths %s\n"
" ray tree depth avg %.1f min %s max %s dev %.1f\n",
pretty_uint(m_stats.m_path_count).c_str(),
m_stats.m_ray_tree_depth.get_avg(),
pretty_uint(m_stats.m_ray_tree_depth.get_min()).c_str(),
pretty_uint(m_stats.m_ray_tree_depth.get_max()).c_str(),
m_stats.m_ray_tree_depth.get_dev());
}
virtual void release()
{
delete this;
}
virtual void compute_lighting(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
Spectrum& radiance) // output radiance, in W.sr^-1.m^-2
{
typedef PathTracer<
PathVisitor,
BSDF::Glossy | BSDF::Specular,
false // not adjoint
> PathTracer;
PathVisitor path_visitor(
m_params,
m_light_sampler,
m_light_samples,
shading_context,
shading_point.get_scene(),
radiance);
PathTracer path_tracer(
path_visitor,
m_params.m_minimum_path_length);
const size_t path_length =
path_tracer.trace(
sampling_context,
shading_context.get_intersector(),
shading_context.get_texture_cache(),
shading_point);
// Update statistics.
++m_stats.m_path_count;
m_stats.m_ray_tree_depth.insert(path_length);
}
private:
struct Parameters
{
const size_t m_minimum_path_length; // minimum path length before Russian Roulette is used
const size_t m_dl_sample_count; // number of samples used to estimate direct illumination
const size_t m_ibl_bsdf_sample_count; // number of samples (in BSDF sampling) used to estimate IBL
const size_t m_ibl_env_sample_count; // number of samples (in environment sampling) used to estimate IBL
// Constructor, extract parameters.
explicit Parameters(const ParamArray& params)
: m_minimum_path_length ( params.get_optional<size_t>("minimum_path_length", 3) )
, m_dl_sample_count ( params.get_optional<size_t>("dl_samples", 1) )
, m_ibl_bsdf_sample_count ( params.get_optional<size_t>("ibl_bsdf_samples", 2) )
, m_ibl_env_sample_count ( params.get_optional<size_t>("ibl_env_samples", 2) )
{
}
};
struct Statistics
{
uint64 m_path_count; // number of paths
Population<size_t> m_ray_tree_depth; // ray tree depth
Statistics()
: m_path_count(0)
{
}
};
class PathVisitor
{
public:
PathVisitor(
const Parameters& params,
const LightSampler& light_sampler,
LightSampleVector& light_samples,
const ShadingContext& shading_context,
const Scene& scene,
Spectrum& path_radiance)
: m_params(params)
, m_light_sampler(light_sampler)
, m_light_samples(light_samples)
, m_shading_context(shading_context)
, m_texture_cache(shading_context.get_texture_cache())
, m_path_radiance(path_radiance)
{
const Environment* environment = scene.get_environment();
m_env_edf = environment ? environment->get_environment_edf() : 0;
m_path_radiance.set(0.0f);
}
bool visit_vertex(
SamplingContext& sampling_context,
const ShadingPoint& shading_point,
const Vector3d& outgoing,
const BSDF* bsdf,
const void* bsdf_data,
const BSDF::Mode bsdf_mode,
const double bsdf_prob,
const Spectrum& throughput)
{
const Vector3d& point = shading_point.get_point();
const Vector3d& geometric_normal = shading_point.get_geometric_normal();
const Vector3d& shading_normal = shading_point.get_shading_normal();
const Basis3d& shading_basis = shading_point.get_shading_basis();
const Material* material = shading_point.get_material();
const InputParams& input_params = shading_point.get_input_params();
// Generate light samples.
clear_keep_memory(m_light_samples);
m_light_sampler.sample(
sampling_context,
m_params.m_dl_sample_count,
m_light_samples);
// Compute direct lighting.
Spectrum vertex_radiance;
compute_direct_lighting(
sampling_context,
m_shading_context,
point,
geometric_normal,
shading_basis,
outgoing,
*bsdf,
bsdf_data,
m_light_samples,
vertex_radiance,
&shading_point);
if (m_env_edf)
{
// Compute image-based lighting.
Spectrum ibl_radiance;
compute_image_based_lighting(
sampling_context,
m_shading_context,
*m_env_edf,
point,
geometric_normal,
shading_basis,
outgoing,
*bsdf,
bsdf_data,
m_params.m_ibl_bsdf_sample_count,
m_params.m_ibl_env_sample_count,
ibl_radiance,
&shading_point);
vertex_radiance += ibl_radiance;
}
// Retrieve the EDF.
const EDF* edf = material->get_edf();
if (edf)
{
// Evaluate the input values of the EDF (if any).
InputEvaluator edf_input_evaluator(m_texture_cache);
const void* edf_data =
edf_input_evaluator.evaluate(
edf->get_inputs(),
input_params);
// Compute the emitted radiance.
Spectrum emitted_radiance;
edf->evaluate(
edf_data,
geometric_normal,
shading_basis,
outgoing,
emitted_radiance);
const double distance = shading_point.get_distance();
if (bsdf_mode != BSDF::Specular && distance > 0.0)
{
// Compute the probability density with respect to surface area
// of choosing this point through sampling of the light sources.
const double sample_probability =
m_light_sampler.evaluate_pdf(shading_point);
// Compute the probability density with respect to surface area
// of the direction obtained through sampling of the BSDF.
double px = bsdf_prob;
px *= max(dot(outgoing, shading_normal), 0.0);
px /= square(distance);
// Multiply the emitted radiance by the MIS weight.
const double mis_weight = mis_power2(px, sample_probability);
emitted_radiance *= static_cast<float>(mis_weight);
}
vertex_radiance += emitted_radiance;
}
// Update the path radiance.
vertex_radiance *= throughput;
m_path_radiance += vertex_radiance;
// Proceed with this path.
return true;
}
void visit_environment(
const ShadingPoint& shading_point,
const Vector3d& outgoing,
const Spectrum& throughput)
{
}
private:
const Parameters& m_params;
const LightSampler& m_light_sampler;
LightSampleVector& m_light_samples;
const ShadingContext& m_shading_context;
TextureCache& m_texture_cache;
const EnvironmentEDF* m_env_edf;
Spectrum& m_path_radiance;
};
const Parameters m_params;
Statistics m_stats;
const LightSampler& m_light_sampler;
LightSampleVector m_light_samples;
};
}
//
// DRTLightingEngineFactory class implementation.
//
DRTLightingEngineFactory::DRTLightingEngineFactory(
const LightSampler& light_sampler,
const ParamArray& params)
: m_light_sampler(light_sampler)
, m_params(params)
{
}
void DRTLightingEngineFactory::release()
{
delete this;
}
ILightingEngine* DRTLightingEngineFactory::create()
{
return new DRTLightingEngine(m_light_sampler, m_params);
}
ILightingEngine* DRTLightingEngineFactory::create(
const LightSampler& light_sampler,
const ParamArray& params)
{
return new DRTLightingEngine(light_sampler, params);
}
} // namespace renderer
<|endoftext|>
|
<commit_before>#include <cmath>
#include <cstddef>
#include <iostream>
#include <vector>
#include <algorithm>
#include "../test_helpers.h"
template<class T, class ArrayLike>
void sort_insertion(ArrayLike& v) {
for(std::size_t k = 1; k < v.size(); ++k) {
// invariant: v[0..k) is sorted
for(std::size_t i = k; i > 0 && v[i - 1] > v[i]; --i) {
// invariant:
// i > 0 && v[i - 1] > v[i]
// v[0..i) is sorted
// all v[i..k] >= v[i]
std::swap(v[i - 1], v[i]);
}
}
}
template<class T, class ArrayLike>
void sort_bubble(ArrayLike& v) {
for(std::size_t k = v.size(); k > 0; --k) {
// invariant:
// v[k..] is sorted
// all v[0..k) <= all v[k..]
for(std::size_t i = 0; i < k - 1; ++i) {
// invariant:
// v[i] >= all v[0..i]
if(v[i] > v[i + 1]) {
std::swap(v[i + 1], v[i]);
}
}
}
}
template<class T, class ArrayLike>
void sort_selection(ArrayLike& v) {
for(std::size_t k = 0; k < v.size(); ++k) {
// invariant:
// v[0..k) is sorted
// all v[0..k) <= all v[k..)
std::size_t min_idx = k;
for(std::size_t i = k; i < v.size(); ++i) {
// invariant:
// v[min_idx] <= all v[k..i)
if(v[i] < v[min_idx]) {
min_idx = i;
}
}
std::swap(v[k], v[min_idx]);
}
}
void test_sort(TestHelper& th, std::function<void(std::vector<int>&)> my_sort) {
th.message("Testing on random vectors");
for(auto i = 0; i < 2000; ++i) {
std::vector<int> v(std::rand() % 1000);
std::generate(v.begin(), v.end(), std::rand);
std::vector<int> vtest(v);
std::sort(vtest.begin(), vtest.end());
my_sort(v);
th.tassert(v == vtest, true, "Vector equality", true);
}
th.tassert();
}
int main(int argc, char const *argv[]) {
TestHelper th;
std::srand((unsigned int)std::time(0));
std::cout << "\n[[ Insertion Sort ]]" << std::endl << std::endl;
test_sort(th, sort_insertion<int, std::vector<int>>);
std::cout << "\n[[ Bubble Sort ]]" << std::endl << std::endl;
test_sort(th, sort_bubble<int, std::vector<int>>);
std::cout << "\n[[ Selection Sort ]]" << std::endl << std::endl;
test_sort(th, sort_selection<int, std::vector<int>>);
th.summary();
return 0;
}
<commit_msg>Quicksort<commit_after>#include <cmath>
#include <cstddef>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include "../test_helpers.h"
template<class T, class ArrayLike>
void sort_insertion(ArrayLike& v) {
for(std::size_t k = 1; k < v.size(); ++k) {
// invariant: v[0..k) is sorted
for(std::size_t i = k; i > 0 && v[i - 1] > v[i]; --i) {
// invariant:
// i > 0 && v[i - 1] > v[i]
// v[0..i) is sorted
// all v[i..k] >= v[i]
std::swap(v[i - 1], v[i]);
}
}
}
template<class T, class ArrayLike>
void sort_bubble(ArrayLike& v) {
for(std::size_t k = v.size(); k > 0; --k) {
// invariant:
// v[k..] is sorted
// all v[0..k) <= all v[k..]
for(std::size_t i = 0; i < k - 1; ++i) {
// invariant:
// v[i] >= all v[0..i]
if(v[i] > v[i + 1]) {
std::swap(v[i + 1], v[i]);
}
}
}
}
template<class T, class ArrayLike>
void sort_selection(ArrayLike& v) {
for(std::size_t k = 0; k < v.size(); ++k) {
// invariant:
// v[0..k) is sorted
// all v[0..k) <= all v[k..)
std::size_t min_idx = k;
for(std::size_t i = k; i < v.size(); ++i) {
// invariant:
// v[min_idx] <= all v[k..i)
if(v[i] < v[min_idx]) {
min_idx = i;
}
}
std::swap(v[k], v[min_idx]);
}
}
template<class T, class ArrayLike>
std::size_t sort_quick_partition(ArrayLike& v, std::size_t p, std::size_t r) {
// v[r] = x is the pivot
// all [p..i) <= x
// all [i..j) > x
// [j..r] unrestricted
// randomize pivot
std::swap(v[p + (std::rand() % (r-p+1))], v[r]);
T pivot = v[r];
std::size_t i = p;
for (std::size_t j = p; j <= r; ++j) {
if (v[j] <= pivot) {
// put in the first segment
std::swap(v[j], v[i]);
i++;
}
}
return i - 1;
}
template<class T, class ArrayLike>
void sort_quick(ArrayLike& v) {
// as we are using UNSIGNED size_t, we need size to be >0 for size-1 to
// make sense
if (v.empty()) {
return;
}
std::stack<std::pair<std::size_t, std::size_t>> s;
s.push({ 0, v.size() - 1 });
while (!s.empty()) {
std::size_t p, r;
std::tie(p, r) = s.top();
s.pop();
if (p < r) {
auto pivot_idx = sort_quick_partition<T,ArrayLike>(v, p, r);
if (pivot_idx > p) {
s.push({ p, pivot_idx - 1 });
}
if (pivot_idx < r) {
s.push({ pivot_idx + 1, r });
}
}
}
}
void test_sort(TestHelper& th, std::function<void(std::vector<int>&)> my_sort) {
th.message("Testing on random vectors");
for(auto i = 0; i < 2000; ++i) {
std::vector<int> v(std::rand() % 1000);
std::generate(v.begin(), v.end(), std::rand);
std::vector<int> vtest(v);
std::sort(vtest.begin(), vtest.end());
my_sort(v);
th.tassert(v == vtest, true, "Vector equality", true);
}
th.tassert();
}
int main(int argc, char const *argv[]) {
TestHelper th;
std::srand((unsigned int)std::time(0));
std::cout << "\n[[ Insertion Sort ]]" << std::endl << std::endl;
test_sort(th, sort_insertion<int, std::vector<int>>);
std::cout << "\n[[ Bubble Sort ]]" << std::endl << std::endl;
test_sort(th, sort_bubble<int, std::vector<int>>);
std::cout << "\n[[ Selection Sort ]]" << std::endl << std::endl;
test_sort(th, sort_selection<int, std::vector<int>>);
std::cout << "\n[[ Quick Sort ]]" << std::endl << std::endl;
test_sort(th, sort_quick<int, std::vector<int>>);
th.summary();
return 0;
}
<|endoftext|>
|
<commit_before>// IconBar.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: IconBar.hh,v 1.9 2002/12/01 13:41:57 rathnor Exp $
#ifndef ICONBAR_HH
#define ICONBAR_HH
#include "Window.hh"
#include <list>
/**
Icon object in IconBar
*/
class IconBarObj
{
public:
IconBarObj(FluxboxWindow *fluxboxwin, Window iconwin);
~IconBarObj();
Window getIconWin() const { return m_iconwin; }
FluxboxWindow *getFluxboxWin() { return m_fluxboxwin; }
const FluxboxWindow *getFluxboxWin() const { return m_fluxboxwin; }
unsigned int width() const;
private:
FluxboxWindow *m_fluxboxwin;
Window m_iconwin;
};
/**
Icon container
*/
class IconBar
{
public:
IconBar(BScreen *scrn, Window parent);
~IconBar();
void draw(); //TODO
void reconfigure();
Window addIcon(FluxboxWindow *fluxboxwin);
Window delIcon(FluxboxWindow *fluxboxwin);
void buttonPressEvent(XButtonEvent *be);
FluxboxWindow *findWindow(Window w);
IconBarObj *findIcon(FluxboxWindow * const fluxboxwin);
const IconBarObj *findIcon(const FluxboxWindow * const fluxboxwin) const;
void exposeEvent(XExposeEvent *ee);
void draw(const IconBarObj * const obj, int width) const;
private:
typedef std::list<IconBarObj *> IconList;
// void draw(IconBarObj *obj, int width);
void loadTheme(unsigned int width, unsigned int height);
void decorate(Window win);
// IconBarObj *findIcon(FluxboxWindow *fluxboxwin);
void repositionIcons();
Window createIconWindow(FluxboxWindow *fluxboxwin, Window parent);
BScreen *m_screen;
Display *m_display;
Window m_parent;
IconList m_iconlist;
Pixmap m_focus_pm;
unsigned long m_focus_pixel;
};
#endif // ICONBAR_HH
<commit_msg>fixed vertical text and font<commit_after>// IconBar.hh for Fluxbox Window Manager
// Copyright (c) 2001 - 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: IconBar.hh,v 1.10 2003/02/23 00:50:53 fluxgen Exp $
#ifndef ICONBAR_HH
#define ICONBAR_HH
#include "Window.hh"
#include <list>
/**
Icon object in IconBar
*/
class IconBarObj
{
public:
IconBarObj(FluxboxWindow *fluxboxwin, Window iconwin);
~IconBarObj();
Window getIconWin() const { return m_iconwin; }
FluxboxWindow *getFluxboxWin() { return m_fluxboxwin; }
const FluxboxWindow *getFluxboxWin() const { return m_fluxboxwin; }
unsigned int width() const;
unsigned int height() const;
private:
FluxboxWindow *m_fluxboxwin;
Window m_iconwin;
};
/**
Icon container
*/
class IconBar
{
public:
IconBar(BScreen *scrn, Window parent, FbTk::Font &font);
~IconBar();
void draw(); //TODO
void reconfigure();
Window addIcon(FluxboxWindow *fluxboxwin);
Window delIcon(FluxboxWindow *fluxboxwin);
void buttonPressEvent(XButtonEvent *be);
FluxboxWindow *findWindow(Window w);
IconBarObj *findIcon(FluxboxWindow * const fluxboxwin);
const IconBarObj *findIcon(const FluxboxWindow * const fluxboxwin) const;
void exposeEvent(XExposeEvent *ee);
void draw(const IconBarObj * const obj, int width) const;
void setVertical(bool value) { m_vertical = value; }
private:
typedef std::list<IconBarObj *> IconList;
// void draw(IconBarObj *obj, int width);
void loadTheme(unsigned int width, unsigned int height);
void decorate(Window win);
// IconBarObj *findIcon(FluxboxWindow *fluxboxwin);
void repositionIcons();
Window createIconWindow(FluxboxWindow *fluxboxwin, Window parent);
BScreen *m_screen;
Display *m_display;
Window m_parent;
IconList m_iconlist;
Pixmap m_focus_pm;
unsigned long m_focus_pixel;
bool m_vertical;
FbTk::Font &m_font;
};
#endif // ICONBAR_HH
<|endoftext|>
|
<commit_before>/*
cmdline.cpp
ப
*/
/* Revision: 1.02 13.09.2000 $ */
/*
Modify:
13.09.2000 tran 1.02
+ COL_COMMANDLINEPREFIX
02.08.2000 tran 1.01
- 䨪 - 室 CtrlF10, 䠩 ᬮ
Alt-F11, keybar
ᥣ CtrlObject->Redraw()
25.06.2000 SVS
! ⮢ Master Copy
! 뤥 ⢥ ᠬ⥫쭮
*/
#include "headers.hpp"
#pragma hdrstop
/* $ 30.06.2000 IS
⠭
*/
#include "internalheaders.hpp"
/* IS $ */
CommandLine::CommandLine()
{
*CurDir=0;
CmdStr.SetEditBeyondEnd(FALSE);
LastCmdPartLength=-1;
*LastCmdStr=0;
}
void CommandLine::DisplayObject()
{
char TruncDir[NM];
GetPrompt(TruncDir);
TruncPathStr(TruncDir,(X2-X1)/2);
GotoXY(X1,Y1);
SetColor(COL_COMMANDLINEPREFIX);
Text(TruncDir);
CmdStr.SetObjectColor(COL_COMMANDLINE,COL_COMMANDLINESELECTED);
CmdStr.SetLeftPos(0);
CmdStr.SetPosition(X1+strlen(TruncDir),Y1,X2,Y2);
CmdStr.Show();
}
void CommandLine::SetCurPos(int Pos)
{
CmdStr.SetLeftPos(0);
CmdStr.SetCurPos(Pos);
CmdStr.Redraw();
}
int CommandLine::ProcessKey(int Key)
{
char Str[512];
if (Key==KEY_CTRLEND && CmdStr.GetCurPos()==CmdStr.GetLength())
{
char Command[1024];
if (LastCmdPartLength==-1)
strncpy(LastCmdStr,CmdStr.GetStringAddr(),sizeof(LastCmdStr));
strcpy(Command,LastCmdStr);
int CurCmdPartLength=strlen(Command);
CtrlObject->CmdHistory->GetSimilar(Command,LastCmdPartLength);
if (LastCmdPartLength==-1)
{
LastCmdPartLength=CurCmdPartLength;
strncpy(LastCmdStr,CmdStr.GetStringAddr(),sizeof(LastCmdStr));
}
CmdStr.SetString(Command);
Show();
return(TRUE);
}
switch(Key)
{
case KEY_UP:
if (CtrlObject->LeftPanel->IsVisible() || CtrlObject->RightPanel->IsVisible())
return(FALSE);
case KEY_CTRLE:
{
char Str[1024];
CtrlObject->CmdHistory->GetPrev(Str);
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
LastCmdPartLength=-1;
return(TRUE);
case KEY_DOWN:
if (CtrlObject->LeftPanel->IsVisible() || CtrlObject->RightPanel->IsVisible())
return(FALSE);
case KEY_CTRLX:
{
char Str[1024];
CtrlObject->CmdHistory->GetNext(Str);
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
LastCmdPartLength=-1;
return(TRUE);
case KEY_F2:
ProcessUserMenu(0);
return(TRUE);
case KEY_ALTF8:
{
char Str[1024];
int Type;
switch(CtrlObject->CmdHistory->Select(MSG(MHistoryTitle),"History",Str,Type))
{
case 1:
ExecString(Str,FALSE,FALSE);
CtrlObject->CmdHistory->AddToHistory(Str);
break;
case 2:
ExecString(Str,FALSE,TRUE);
CtrlObject->CmdHistory->AddToHistory(Str);
break;
case 3:
SetString(Str);
break;
}
}
return(TRUE);
case KEY_SHIFTF9:
SaveConfig(1);
return(TRUE);
case KEY_F10:
CtrlObject->ExitMainLoop(TRUE);
return(TRUE);
case KEY_ALTF10:
{
char NewFolder[NM];
{
FolderTree Tree(NewFolder,MODALTREE_ACTIVE,4,2,ScrX-4,ScrY-4);
}
if (*NewFolder)
{
Panel *ActivePanel=CtrlObject->ActivePanel;
ActivePanel->SetCurDir(NewFolder,TRUE);
ActivePanel->Show();
if (ActivePanel->GetType()==TREE_PANEL)
ActivePanel->ProcessKey(KEY_ENTER);
}
}
return(TRUE);
case KEY_F11:
CtrlObject->Plugins.CommandsMenu(FALSE,FALSE,0);
return(TRUE);
case KEY_ALTF11:
{
char Str[1024],ItemTitle[256];
int Type,SelectType;
if ((SelectType=CtrlObject->ViewHistory->Select(MSG(MViewHistoryTitle),"CmdMenu",Str,Type,ItemTitle))==1 || SelectType==2)
{
if (SelectType!=2)
CtrlObject->ViewHistory->AddToHistory(Str,ItemTitle,Type);
CtrlObject->ViewHistory->SetAddMode(FALSE,1,TRUE);
switch(Type)
{
case 0:
{
FileViewer *ShellViewer=new FileViewer(Str,TRUE);
CtrlObject->ModalManager.AddModal(ShellViewer);
break;
}
case 1:
{
FileEditor *ShellEditor=new FileEditor(Str,FALSE,TRUE);
CtrlObject->ModalManager.AddModal(ShellEditor);
break;
}
case 2:
case 3:
{
if (*Str!='@')
ExecString(Str,Type-2);
else
{
SaveScreen SaveScr;
CtrlObject->LeftPanel->CloseFile();
CtrlObject->RightPanel->CloseFile();
Execute(Str+1,Type-2);
}
break;
}
}
CtrlObject->ViewHistory->SetAddMode(TRUE,1,TRUE);
}
else
if (SelectType==3)
SetString(Str);
}
CtrlObject->Redraw();
return(TRUE);
case KEY_F12:
CtrlObject->ModalManager.SelectModal();
CtrlObject->ModalManager.NextModal(0);
return(TRUE);
case KEY_ALTF12:
{
char Str[1024];
int Type,SelectType;
if ((SelectType=CtrlObject->FolderHistory->Select(MSG(MFolderHistoryTitle),"CmdMenu",Str,Type))==1 || SelectType==2)
{
if (SelectType==2)
CtrlObject->FolderHistory->SetAddMode(FALSE,2,TRUE);
CtrlObject->ActivePanel->SetCurDir(Str,Type==0 ? TRUE:FALSE);
CtrlObject->ActivePanel->Redraw();
CtrlObject->FolderHistory->SetAddMode(TRUE,2,TRUE);
}
else
if (SelectType==3)
SetString(Str);
}
return(TRUE);
case KEY_ENTER:
case KEY_SHIFTENTER:
{
Panel *ActivePanel=CtrlObject->ActivePanel;
CmdStr.GetString(Str,sizeof(Str));
if (*Str==0)
break;
ActivePanel->SetCurPath();
CtrlObject->CmdHistory->AddToHistory(Str);
if (!ActivePanel->ProcessPluginEvent(FE_COMMAND,(void *)Str))
CmdExecute(Str,FALSE,Key==KEY_SHIFTENTER,FALSE);
}
return(TRUE);
case KEY_ESC:
CmdStr.SetString("");
CmdStr.SetLeftPos(0);
CmdStr.Show();
LastCmdPartLength=-1;
return(TRUE);
default:
if (!CmdStr.ProcessKey(Key))
break;
LastCmdPartLength=-1;
return(TRUE);
}
return(FALSE);
}
void CommandLine::SetCurDir(char *CurDir)
{
strcpy(CommandLine::CurDir,CurDir);
}
void CommandLine::GetCurDir(char *CurDir)
{
strcpy(CurDir,CommandLine::CurDir);
}
int CommandLine::CmdExecute(char *CmdLine,int AlwaysWaitFinish,
int SeparateWindow,int DirectRun)
{
LastCmdPartLength=-1;
if (!SeparateWindow && CtrlObject->Plugins.ProcessCommandLine(CmdLine))
{
CmdStr.SetString("");
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
Show();
ScrBuf.Flush();
return(-1);
}
int Code;
{
RedrawDesktop Redraw;
CtrlObject->LeftPanel->CloseChangeNotification();
CtrlObject->RightPanel->CloseChangeNotification();
CtrlObject->LeftPanel->CloseFile();
CtrlObject->RightPanel->CloseFile();
ScrollScreen(1);
MoveCursor(X1,Y1);
if (CurDir[0] && CurDir[1]==':')
chdir(CurDir);
CmdStr.SetString("");
if (ProcessOSCommands(CmdLine))
Code=-1;
else
Code=Execute(CmdLine,AlwaysWaitFinish,SeparateWindow,DirectRun);
int CurX,CurY;
GetCursorPos(CurX,CurY);
if (CurY>=Y1-1)
ScrollScreen(Min(CurY-Y1+2,Opt.ShowKeyBar ? 2:1));
CtrlObject->LeftPanel->Update(UPDATE_KEEP_SELECTION);
CtrlObject->RightPanel->Update(UPDATE_KEEP_SELECTION);
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
}
ScrBuf.Flush();
return(Code);
}
int CommandLine::ProcessOSCommands(char *CmdLine)
{
Panel *SetPanel;
int Length;
SetPanel=CtrlObject->ActivePanel;
if (SetPanel->GetType()!=FILE_PANEL && CtrlObject->GetAnotherPanel(SetPanel)->GetType()==FILE_PANEL)
SetPanel=CtrlObject->GetAnotherPanel(SetPanel);
RemoveTrailingSpaces(CmdLine);
if (isalpha(CmdLine[0]) && CmdLine[1]==':' && CmdLine[2]==0)
{
int NewDisk=toupper(CmdLine[0])-'A';
setdisk(NewDisk);
if (getdisk()!=NewDisk)
{
char NewDir[10];
sprintf(NewDir,"%c:\\",NewDisk+'A');
chdir(NewDir);
setdisk(NewDisk);
}
SetPanel->ChangeDirToCurrent();
return(TRUE);
}
if (strnicmp(CmdLine,"SET ",4)==0)
{
char Cmd[1024];
strcpy(Cmd,CmdLine+4);
char *Value=strchr(Cmd,'=');
if (Value==NULL)
return(FALSE);
*Value=0;
if (Value[1]==0)
SetEnvironmentVariable(Cmd,NULL);
else
{
char ExpandedStr[8192];
if (ExpandEnvironmentStrings(Value+1,ExpandedStr,sizeof(ExpandedStr))!=0)
SetEnvironmentVariable(Cmd,ExpandedStr);
}
return(TRUE);
}
if ((strnicmp(CmdLine,"CD",Length=2)==0 || strnicmp(CmdLine,"CHDIR",Length=5)==0) &&
(isspace(CmdLine[Length]) || CmdLine[Length]=='\\' || strcmp(CmdLine+Length,"..")==0))
{
int ChDir=(Length==5);
while (isspace(CmdLine[Length]))
Length++;
if (CmdLine[Length]=='\"')
Length++;
char NewDir[NM];
strcpy(NewDir,&CmdLine[Length]);
if (CtrlObject->Plugins.ProcessCommandLine(NewDir))
{
CmdStr.SetString("");
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
Show();
return(TRUE);
}
char *ChPtr=strrchr(NewDir,'\"');
if (ChPtr!=NULL)
*ChPtr=0;
if (SetPanel->GetType()==FILE_PANEL && SetPanel->GetMode()==PLUGIN_PANEL)
{
SetPanel->SetCurDir(NewDir,ChDir);
return(TRUE);
}
char ExpandedDir[8192];
if (ExpandEnvironmentStrings(NewDir,ExpandedDir,sizeof(ExpandedDir))!=0)
if (chdir(ExpandedDir)==-1)
return(FALSE);
SetPanel->ChangeDirToCurrent();
if (!SetPanel->IsVisible())
SetPanel->SetTitle();
return(TRUE);
}
return(FALSE);
}
void CommandLine::GetString(char *Str,int MaxSize)
{
CmdStr.GetString(Str,MaxSize);
}
void CommandLine::SetString(char *Str)
{
LastCmdPartLength=-1;
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
void CommandLine::ExecString(char *Str,int AlwaysWaitFinish,int SeparateWindow,
int DirectRun)
{
SetString(Str);
CmdExecute(Str,AlwaysWaitFinish,SeparateWindow,DirectRun);
}
void CommandLine::InsertString(char *Str)
{
LastCmdPartLength=-1;
CmdStr.InsertString(Str);
CmdStr.Show();
}
int CommandLine::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
return(CmdStr.ProcessMouse(MouseEvent));
}
void CommandLine::GetPrompt(char *DestStr)
{
char FormatStr[512],ExpandedFormatStr[512];
strcpy(FormatStr,Opt.UsePromptFormat ? Opt.PromptFormat:"$p$g");
char *Format=FormatStr;
if (Opt.UsePromptFormat)
{
ExpandEnvironmentStrings(FormatStr,ExpandedFormatStr,sizeof(ExpandedFormatStr));
Format=ExpandedFormatStr;
}
while (*Format)
{
if (*Format=='$')
{
Format++;
switch(*Format)
{
case '$':
*(DestStr++)='$';
break;
case 'p':
strcpy(DestStr,CurDir);
DestStr+=strlen(CurDir);
break;
case 'n':
if (isalpha(CurDir[0]) && CurDir[1]==':' && CurDir[2]=='\\')
*(DestStr++)=LocalUpper(*CurDir);
else
*(DestStr++)='?';
break;
case 'g':
*(DestStr++)='>';
break;
}
Format++;
}
else
*(DestStr++)=*(Format++);
}
*DestStr=0;
}
int CommandLine::GetCurPos()
{
return(CmdStr.GetCurPos());
}
<commit_msg>FAR patch 00204.cmdline.cpp Дата : 19.09.2000 Сделал : Valentin Skirdin Описание : Alt-F8 & Plugins Измененные файлы : cmdline.cpp Состав : 00204.cmdline.cpp.txt cmdline.cpp.204.diff Основан на патче : 203 Дополнение :<commit_after>/*
cmdline.cpp
ப
*/
/* Revision: 1.03 19.09.2000 $ */
/*
Modify:
19.09.2000 SVS
- 롮 History ( Alt-F8) 砫 ࠢ!
13.09.2000 tran 1.02
+ COL_COMMANDLINEPREFIX
02.08.2000 tran 1.01
- 䨪 - 室 CtrlF10, 䠩 ᬮ
Alt-F11, keybar
ᥣ CtrlObject->Redraw()
25.06.2000 SVS
! ⮢ Master Copy
! 뤥 ⢥ ᠬ⥫쭮
*/
#include "headers.hpp"
#pragma hdrstop
/* $ 30.06.2000 IS
⠭
*/
#include "internalheaders.hpp"
/* IS $ */
CommandLine::CommandLine()
{
*CurDir=0;
CmdStr.SetEditBeyondEnd(FALSE);
LastCmdPartLength=-1;
*LastCmdStr=0;
}
void CommandLine::DisplayObject()
{
char TruncDir[NM];
GetPrompt(TruncDir);
TruncPathStr(TruncDir,(X2-X1)/2);
GotoXY(X1,Y1);
SetColor(COL_COMMANDLINEPREFIX);
Text(TruncDir);
CmdStr.SetObjectColor(COL_COMMANDLINE,COL_COMMANDLINESELECTED);
CmdStr.SetLeftPos(0);
CmdStr.SetPosition(X1+strlen(TruncDir),Y1,X2,Y2);
CmdStr.Show();
}
void CommandLine::SetCurPos(int Pos)
{
CmdStr.SetLeftPos(0);
CmdStr.SetCurPos(Pos);
CmdStr.Redraw();
}
int CommandLine::ProcessKey(int Key)
{
char Str[512];
if (Key==KEY_CTRLEND && CmdStr.GetCurPos()==CmdStr.GetLength())
{
char Command[1024];
if (LastCmdPartLength==-1)
strncpy(LastCmdStr,CmdStr.GetStringAddr(),sizeof(LastCmdStr));
strcpy(Command,LastCmdStr);
int CurCmdPartLength=strlen(Command);
CtrlObject->CmdHistory->GetSimilar(Command,LastCmdPartLength);
if (LastCmdPartLength==-1)
{
LastCmdPartLength=CurCmdPartLength;
strncpy(LastCmdStr,CmdStr.GetStringAddr(),sizeof(LastCmdStr));
}
CmdStr.SetString(Command);
Show();
return(TRUE);
}
switch(Key)
{
case KEY_UP:
if (CtrlObject->LeftPanel->IsVisible() || CtrlObject->RightPanel->IsVisible())
return(FALSE);
case KEY_CTRLE:
{
char Str[1024];
CtrlObject->CmdHistory->GetPrev(Str);
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
LastCmdPartLength=-1;
return(TRUE);
case KEY_DOWN:
if (CtrlObject->LeftPanel->IsVisible() || CtrlObject->RightPanel->IsVisible())
return(FALSE);
case KEY_CTRLX:
{
char Str[1024];
CtrlObject->CmdHistory->GetNext(Str);
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
LastCmdPartLength=-1;
return(TRUE);
case KEY_F2:
ProcessUserMenu(0);
return(TRUE);
case KEY_ALTF8:
{
char Str[1024];
int Type;
/* $ 19.09.2000 SVS
- 롮 History ( Alt-F8) 砫 ࠢ!
*/
switch(CtrlObject->CmdHistory->Select(MSG(MHistoryTitle),"History",Str,Type))
{
case 1:
SetString(Str);
ProcessKey(KEY_ENTER);
//ExecString(Str,FALSE,FALSE);
//CtrlObject->CmdHistory->AddToHistory(Str);
break;
case 2:
SetString(Str);
ProcessKey(KEY_SHIFTENTER);
//ExecString(Str,FALSE,TRUE);
//CtrlObject->CmdHistory->AddToHistory(Str);
break;
case 3:
SetString(Str);
break;
}
/* SVS $ */
}
return(TRUE);
case KEY_SHIFTF9:
SaveConfig(1);
return(TRUE);
case KEY_F10:
CtrlObject->ExitMainLoop(TRUE);
return(TRUE);
case KEY_ALTF10:
{
char NewFolder[NM];
{
FolderTree Tree(NewFolder,MODALTREE_ACTIVE,4,2,ScrX-4,ScrY-4);
}
if (*NewFolder)
{
Panel *ActivePanel=CtrlObject->ActivePanel;
ActivePanel->SetCurDir(NewFolder,TRUE);
ActivePanel->Show();
if (ActivePanel->GetType()==TREE_PANEL)
ActivePanel->ProcessKey(KEY_ENTER);
}
}
return(TRUE);
case KEY_F11:
CtrlObject->Plugins.CommandsMenu(FALSE,FALSE,0);
return(TRUE);
case KEY_ALTF11:
{
char Str[1024],ItemTitle[256];
int Type,SelectType;
if ((SelectType=CtrlObject->ViewHistory->Select(MSG(MViewHistoryTitle),"CmdMenu",Str,Type,ItemTitle))==1 || SelectType==2)
{
if (SelectType!=2)
CtrlObject->ViewHistory->AddToHistory(Str,ItemTitle,Type);
CtrlObject->ViewHistory->SetAddMode(FALSE,1,TRUE);
switch(Type)
{
case 0:
{
FileViewer *ShellViewer=new FileViewer(Str,TRUE);
CtrlObject->ModalManager.AddModal(ShellViewer);
break;
}
case 1:
{
FileEditor *ShellEditor=new FileEditor(Str,FALSE,TRUE);
CtrlObject->ModalManager.AddModal(ShellEditor);
break;
}
case 2:
case 3:
{
if (*Str!='@')
ExecString(Str,Type-2);
else
{
SaveScreen SaveScr;
CtrlObject->LeftPanel->CloseFile();
CtrlObject->RightPanel->CloseFile();
Execute(Str+1,Type-2);
}
break;
}
}
CtrlObject->ViewHistory->SetAddMode(TRUE,1,TRUE);
}
else
if (SelectType==3)
SetString(Str);
}
CtrlObject->Redraw();
return(TRUE);
case KEY_F12:
CtrlObject->ModalManager.SelectModal();
CtrlObject->ModalManager.NextModal(0);
return(TRUE);
case KEY_ALTF12:
{
char Str[1024];
int Type,SelectType;
if ((SelectType=CtrlObject->FolderHistory->Select(MSG(MFolderHistoryTitle),"CmdMenu",Str,Type))==1 || SelectType==2)
{
if (SelectType==2)
CtrlObject->FolderHistory->SetAddMode(FALSE,2,TRUE);
CtrlObject->ActivePanel->SetCurDir(Str,Type==0 ? TRUE:FALSE);
CtrlObject->ActivePanel->Redraw();
CtrlObject->FolderHistory->SetAddMode(TRUE,2,TRUE);
}
else
if (SelectType==3)
SetString(Str);
}
return(TRUE);
case KEY_ENTER:
case KEY_SHIFTENTER:
{
Panel *ActivePanel=CtrlObject->ActivePanel;
CmdStr.GetString(Str,sizeof(Str));
if (*Str==0)
break;
ActivePanel->SetCurPath();
CtrlObject->CmdHistory->AddToHistory(Str);
if (!ActivePanel->ProcessPluginEvent(FE_COMMAND,(void *)Str))
CmdExecute(Str,FALSE,Key==KEY_SHIFTENTER,FALSE);
}
return(TRUE);
case KEY_ESC:
CmdStr.SetString("");
CmdStr.SetLeftPos(0);
CmdStr.Show();
LastCmdPartLength=-1;
return(TRUE);
default:
if (!CmdStr.ProcessKey(Key))
break;
LastCmdPartLength=-1;
return(TRUE);
}
return(FALSE);
}
void CommandLine::SetCurDir(char *CurDir)
{
strcpy(CommandLine::CurDir,CurDir);
}
void CommandLine::GetCurDir(char *CurDir)
{
strcpy(CurDir,CommandLine::CurDir);
}
int CommandLine::CmdExecute(char *CmdLine,int AlwaysWaitFinish,
int SeparateWindow,int DirectRun)
{
LastCmdPartLength=-1;
if (!SeparateWindow && CtrlObject->Plugins.ProcessCommandLine(CmdLine))
{
CmdStr.SetString("");
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
Show();
ScrBuf.Flush();
return(-1);
}
int Code;
{
RedrawDesktop Redraw;
CtrlObject->LeftPanel->CloseChangeNotification();
CtrlObject->RightPanel->CloseChangeNotification();
CtrlObject->LeftPanel->CloseFile();
CtrlObject->RightPanel->CloseFile();
ScrollScreen(1);
MoveCursor(X1,Y1);
if (CurDir[0] && CurDir[1]==':')
chdir(CurDir);
CmdStr.SetString("");
if (ProcessOSCommands(CmdLine))
Code=-1;
else
Code=Execute(CmdLine,AlwaysWaitFinish,SeparateWindow,DirectRun);
int CurX,CurY;
GetCursorPos(CurX,CurY);
if (CurY>=Y1-1)
ScrollScreen(Min(CurY-Y1+2,Opt.ShowKeyBar ? 2:1));
CtrlObject->LeftPanel->Update(UPDATE_KEEP_SELECTION);
CtrlObject->RightPanel->Update(UPDATE_KEEP_SELECTION);
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
}
ScrBuf.Flush();
return(Code);
}
int CommandLine::ProcessOSCommands(char *CmdLine)
{
Panel *SetPanel;
int Length;
SetPanel=CtrlObject->ActivePanel;
if (SetPanel->GetType()!=FILE_PANEL && CtrlObject->GetAnotherPanel(SetPanel)->GetType()==FILE_PANEL)
SetPanel=CtrlObject->GetAnotherPanel(SetPanel);
RemoveTrailingSpaces(CmdLine);
if (isalpha(CmdLine[0]) && CmdLine[1]==':' && CmdLine[2]==0)
{
int NewDisk=toupper(CmdLine[0])-'A';
setdisk(NewDisk);
if (getdisk()!=NewDisk)
{
char NewDir[10];
sprintf(NewDir,"%c:\\",NewDisk+'A');
chdir(NewDir);
setdisk(NewDisk);
}
SetPanel->ChangeDirToCurrent();
return(TRUE);
}
if (strnicmp(CmdLine,"SET ",4)==0)
{
char Cmd[1024];
strcpy(Cmd,CmdLine+4);
char *Value=strchr(Cmd,'=');
if (Value==NULL)
return(FALSE);
*Value=0;
if (Value[1]==0)
SetEnvironmentVariable(Cmd,NULL);
else
{
char ExpandedStr[8192];
if (ExpandEnvironmentStrings(Value+1,ExpandedStr,sizeof(ExpandedStr))!=0)
SetEnvironmentVariable(Cmd,ExpandedStr);
}
return(TRUE);
}
if ((strnicmp(CmdLine,"CD",Length=2)==0 || strnicmp(CmdLine,"CHDIR",Length=5)==0) &&
(isspace(CmdLine[Length]) || CmdLine[Length]=='\\' || strcmp(CmdLine+Length,"..")==0))
{
int ChDir=(Length==5);
while (isspace(CmdLine[Length]))
Length++;
if (CmdLine[Length]=='\"')
Length++;
char NewDir[NM];
strcpy(NewDir,&CmdLine[Length]);
if (CtrlObject->Plugins.ProcessCommandLine(NewDir))
{
CmdStr.SetString("");
GotoXY(X1,Y1);
mprintf("%*s",X2-X1+1,"");
Show();
return(TRUE);
}
char *ChPtr=strrchr(NewDir,'\"');
if (ChPtr!=NULL)
*ChPtr=0;
if (SetPanel->GetType()==FILE_PANEL && SetPanel->GetMode()==PLUGIN_PANEL)
{
SetPanel->SetCurDir(NewDir,ChDir);
return(TRUE);
}
char ExpandedDir[8192];
if (ExpandEnvironmentStrings(NewDir,ExpandedDir,sizeof(ExpandedDir))!=0)
if (chdir(ExpandedDir)==-1)
return(FALSE);
SetPanel->ChangeDirToCurrent();
if (!SetPanel->IsVisible())
SetPanel->SetTitle();
return(TRUE);
}
return(FALSE);
}
void CommandLine::GetString(char *Str,int MaxSize)
{
CmdStr.GetString(Str,MaxSize);
}
void CommandLine::SetString(char *Str)
{
LastCmdPartLength=-1;
CmdStr.SetString(Str);
CmdStr.SetLeftPos(0);
CmdStr.Show();
}
void CommandLine::ExecString(char *Str,int AlwaysWaitFinish,int SeparateWindow,
int DirectRun)
{
SetString(Str);
CmdExecute(Str,AlwaysWaitFinish,SeparateWindow,DirectRun);
}
void CommandLine::InsertString(char *Str)
{
LastCmdPartLength=-1;
CmdStr.InsertString(Str);
CmdStr.Show();
}
int CommandLine::ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent)
{
return(CmdStr.ProcessMouse(MouseEvent));
}
void CommandLine::GetPrompt(char *DestStr)
{
char FormatStr[512],ExpandedFormatStr[512];
strcpy(FormatStr,Opt.UsePromptFormat ? Opt.PromptFormat:"$p$g");
char *Format=FormatStr;
if (Opt.UsePromptFormat)
{
ExpandEnvironmentStrings(FormatStr,ExpandedFormatStr,sizeof(ExpandedFormatStr));
Format=ExpandedFormatStr;
}
while (*Format)
{
if (*Format=='$')
{
Format++;
switch(*Format)
{
case '$':
*(DestStr++)='$';
break;
case 'p':
strcpy(DestStr,CurDir);
DestStr+=strlen(CurDir);
break;
case 'n':
if (isalpha(CurDir[0]) && CurDir[1]==':' && CurDir[2]=='\\')
*(DestStr++)=LocalUpper(*CurDir);
else
*(DestStr++)='?';
break;
case 'g':
*(DestStr++)='>';
break;
}
Format++;
}
else
*(DestStr++)=*(Format++);
}
*DestStr=0;
}
int CommandLine::GetCurPos()
{
return(CmdStr.GetCurPos());
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <netdb.h>
#include "EchoRequest.h"
#include "EchoIndication.h"
EchoRequestProxy *echoRequestProxy;
EchoIndicationProxy *sIndicationProxy;
static int daemon_trace;// = 1;
class EchoIndication : public EchoIndicationWrapper
{
public:
void heard(uint32_t v) {
if (daemon_trace)
fprintf(stderr, "daemon: heard an echo: %d\n", v);
sIndicationProxy->heard(v);
}
void heard2(uint32_t a, uint32_t b) {
if (daemon_trace)
fprintf(stderr, "daemon: heard an echo2: %d %d\n", a, b);
sIndicationProxy->heard2(a, b);
}
EchoIndication(unsigned int id, PortalItemFunctions *item, void *param) : EchoIndicationWrapper(id, item, param) {}
};
class EchoRequest : public EchoRequestWrapper
{
public:
void say ( const uint32_t v ) {
if (daemon_trace)
fprintf(stderr, "daemon[%s:%d]\n", __FUNCTION__, __LINE__);
echoRequestProxy->say(v);
}
void say2 ( const uint32_t a, const uint32_t b ) {
if (daemon_trace)
fprintf(stderr, "daemon[%s:%d]\n", __FUNCTION__, __LINE__);
echoRequestProxy->say2(a, b);
}
void setLeds ( const uint32_t v ) {
fprintf(stderr, "daemon[%s:%d]\n", __FUNCTION__, __LINE__);
echoRequestProxy->setLeds(v);
sleep(1);
exit(1);
}
EchoRequest(unsigned int id, PortalItemFunctions *item, void *param) : EchoRequestWrapper(id, item, param) {}
};
int main(int argc, const char **argv)
{
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
EchoRequest *mcommon = new EchoRequest(IfcNames_EchoRequest, &socketfuncResp, ¶mSocket);
param.pint = &mcommon->pint;
sIndicationProxy = new EchoIndicationProxy(IfcNames_EchoIndication, &muxfuncResp, ¶m);
EchoRequest *sRequest = new EchoRequest(IfcNames_EchoRequest, &muxfuncResp, ¶m);
EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, NULL, NULL);
echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);
portalExec_start();
printf("[%s:%d] daemon sleeping...\n", __FUNCTION__, __LINE__);
while(1)
sleep(100);
return 0;
}
<commit_msg>cleaned up debug printf in echomux daemon<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <netdb.h>
#include "EchoRequest.h"
#include "EchoIndication.h"
EchoRequestProxy *echoRequestProxy;
EchoIndicationProxy *sIndicationProxy;
static int daemon_trace;// = 1;
class EchoIndication : public EchoIndicationWrapper
{
public:
void heard(uint32_t v) {
if (daemon_trace)
fprintf(stderr, "daemon: heard an echo: %d\n", v);
sIndicationProxy->heard(v);
}
void heard2(uint32_t a, uint32_t b) {
if (daemon_trace)
fprintf(stderr, "daemon: heard an echo2: %d %d\n", a, b);
sIndicationProxy->heard2(a, b);
}
EchoIndication(unsigned int id, PortalItemFunctions *item, void *param) : EchoIndicationWrapper(id, item, param) {}
};
class EchoRequest : public EchoRequestWrapper
{
public:
void say ( const uint32_t v ) {
if (daemon_trace)
fprintf(stderr, "daemon[%s] %d\n", __FUNCTION__, v);
echoRequestProxy->say(v);
}
void say2 ( const uint32_t a, const uint32_t b ) {
if (daemon_trace)
fprintf(stderr, "daemon[%s] %d %d\n", __FUNCTION__, a, b);
echoRequestProxy->say2(a, b);
}
void setLeds ( const uint32_t v ) {
fprintf(stderr, "daemon[%s] %d\n", __FUNCTION__, __LINE__, v);
echoRequestProxy->setLeds(v);
sleep(1);
exit(1);
}
EchoRequest(unsigned int id, PortalItemFunctions *item, void *param) : EchoRequestWrapper(id, item, param) {}
};
int main(int argc, const char **argv)
{
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
EchoIndicationProxy *mcommon = new EchoIndicationProxy(IfcNames_EchoRequest, &socketfuncResp, ¶mSocket);
param.pint = &mcommon->pint;
sIndicationProxy = new EchoIndicationProxy(IfcNames_EchoIndication, &muxfuncResp, ¶m);
EchoRequest *sRequest = new EchoRequest(IfcNames_EchoRequest, &muxfuncResp, ¶m);
EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication, NULL, NULL);
echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);
portalExec_start();
printf("[%s:%d] daemon sleeping...\n", __FUNCTION__, __LINE__);
while(1)
sleep(100);
return 0;
}
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* @version dev
* @date January, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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.
*
*
* @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <inverse/hpiFit/hpifit.h>
#include <utils/ioutils.h>
#include <utils/generics/applicationlogger.h>
#include <utils/mnemath.h>
#include <fwd/fwd_coil_set.h>
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QGenericMatrix>
#include <QElapsedTimer>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace INVERSELIB;
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace Eigen;
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
qInstallMessageHandler(ApplicationLogger::customLogWriter);
QElapsedTimer timer;
QCoreApplication a(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("hpiFit Example");
parser.addHelpOption();
qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin.";
QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");
parser.addOption(inputOption);
parser.process(a);
// Init data loading and writing
QFile t_fileIn(parser.value(inputOption));
FiffRawData raw(t_fileIn);
QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info));
// Setup comparison of transformation matrices
FiffCoordTrans devHeadTrans = pFiffInfo->dev_head_t; // transformation that only updates after big head movements
float threshRot = 5; // in degree
float threshTrans = 0.005; // in m
// Set up the reading parameters
RowVectorXi picks = pFiffInfo->pick_types(true, false, false);
MatrixXd matData;
MatrixXd times;
fiff_int_t from;
fiff_int_t to;
fiff_int_t first = raw.first_samp;
fiff_int_t last = raw.last_samp;
float dT_sec = 0.1; // time between hpi fits
float quantum_sec = 0.2f; // read and write in 200 ms junks
fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);
// create time vector that specifies when to fit
int N = ceil((last-first)/quantum);
RowVectorXf time = RowVectorXf::LinSpaced(N, 0, N-1) * dT_sec;
// To fit at specific times outcommend the following block
// // Read Quaternion File
// MatrixXd pos;
// qInfo() << "Specify the path to your position file (.txt)";
// IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");
// RowVectorXd time = pos.col(0);
MatrixXd position; // Position matrix to save quaternions etc.
// setup informations for HPI fit (VectorView)
// QVector<int> vFreqs {166,154,161,158};
QVector<int> vFreqs {154,158,161,166};
QVector<double> vError;
VectorXd vGoF;
FiffDigPointSet fittedPointSet;
// Use SSP + SGM + calibration
MatrixXd matProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
//Do a copy here because we are going to change the activity flags of the SSP's
FiffInfo infoTemp = *(pFiffInfo.data());
//Turn on all SSP
for(int i = 0; i < infoTemp.projs.size(); ++i) {
infoTemp.projs[i].active = true;
}
//Create the projector for all SSP's on
infoTemp.make_projector(matProjectors);
//set columns of matrix to zero depending on bad channels indexes
for(qint32 j = 0; j < infoTemp.bads.size(); ++j) {
matProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero();
}
// if debugging files are necessary set bDoDebug = true;
QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
bool bDoDebug = false;
// initial fit and ordering of frequencies
from = first + time(0)*pFiffInfo->sfreq;
to = from + quantum;
if(!raw.read_raw_segment(matData, times, from, to)) {
qCritical("error during read_raw_segment");
return -1;
}
qInfo() << "[done]";
qInfo() << "Find Order...";
timer.start();
HPIFit::findOrder(matData,
matProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo);
qInfo() << "Ordered Frequencies: ";
qInfo() << vFreqs;
qInfo() << "The HPI-Fit took" << timer.elapsed() << "milliseconds";
qInfo() << "[done]";
// // read and fit
// for(int i = 1; i < time.size(); i++) {
// from = first + time(i)*pFiffInfo->sfreq;
// to = from + quantum;
// if (to > last) {
// to = last;
// qWarning() << "Block size < quantum " << quantum;
// }
// // Reading
// if(!raw.read_raw_segment(matData, times, from, to)) {
// qCritical("error during read_raw_segment");
// return -1;
// }
// qInfo() << "[done]";
// qInfo() << "HPI-Fit...";
// timer.start();
// HPIFit::fitHPI(matData,
// matProjectors,
// pFiffInfo->dev_head_t,
// vFreqs,
// vError,
// vGoF,
// fittedPointSet,
// pFiffInfo,
// bDoDebug,
// sHPIResourceDir);
// qInfo() << "The HPI-Fit took" << timer.elapsed() << "milliseconds";
// qInfo() << "[done]";
// HPIFit::storeHeadPosition(time(i), pFiffInfo->dev_head_t.trans, position, vGoF, vError);
// // if big head displacement occures, update debHeadTrans
// if(MNEMath::compareTransformation(devHeadTrans.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {
// devHeadTrans = pFiffInfo->dev_head_t;
// qInfo() << "dev_head_t has been updated.";
// }
// }
// IOUtils::write_eigen_matrix(position, QCoreApplication::applicationDirPath() + "/MNE-sample-data/position.txt");
}
<commit_msg>MAINT: style changes and undo outcommets<commit_after>//=============================================================================================================
/**
* @file main.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>;
* @version dev
* @date January, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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.
*
*
* @brief Example for cHPI fitting on raw data with SSP. The result is written to a .txt file for comparison with MaxFilter's .pos file.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <iostream>
#include <vector>
#include <fiff/fiff.h>
#include <fiff/fiff_info.h>
#include <fiff/fiff_dig_point_set.h>
#include <inverse/hpiFit/hpifit.h>
#include <utils/ioutils.h>
#include <utils/generics/applicationlogger.h>
#include <utils/mnemath.h>
#include <fwd/fwd_coil_set.h>
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QCommandLineParser>
#include <QDebug>
#include <QGenericMatrix>
#include <QElapsedTimer>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace INVERSELIB;
using namespace FIFFLIB;
using namespace UTILSLIB;
using namespace Eigen;
//=============================================================================================================
// MAIN
//=============================================================================================================
//=============================================================================================================
/**
* The function main marks the entry point of the program.
* By default, main has the storage class extern.
*
* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.
* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.
* @return the value that was set to exit() (which is 0 if exit() is called via quit()).
*/
int main(int argc, char *argv[])
{
qInstallMessageHandler(ApplicationLogger::customLogWriter);
QElapsedTimer timer;
QCoreApplication a(argc, argv);
// Command Line Parser
QCommandLineParser parser;
parser.setApplicationDescription("hpiFit Example");
parser.addHelpOption();
qInfo() << "Please download the mne-cpp-test-data folder from Github (mne-tools) into mne-cpp/bin.";
QCommandLineOption inputOption("fileIn", "The input file <in>.", "in", QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/MEG/sample/test_hpiFit_raw.fif");
parser.addOption(inputOption);
parser.process(a);
// Init data loading and writing
QFile t_fileIn(parser.value(inputOption));
FiffRawData raw(t_fileIn);
QSharedPointer<FiffInfo> pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(raw.info));
// Setup comparison of transformation matrices
FiffCoordTrans devHeadTrans = pFiffInfo->dev_head_t; // transformation that only updates after big head movements
float threshRot = 5; // in degree
float threshTrans = 0.005; // in m
// Set up the reading parameters
RowVectorXi picks = pFiffInfo->pick_types(true, false, false);
MatrixXd matData;
MatrixXd times;
fiff_int_t from;
fiff_int_t to;
fiff_int_t first = raw.first_samp;
fiff_int_t last = raw.last_samp;
float dT_sec = 0.1; // time between hpi fits
float quantum_sec = 0.2f; // read and write in 200 ms junks
fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);
// create time vector that specifies when to fit
int N = ceil((last-first)/quantum);
RowVectorXf time = RowVectorXf::LinSpaced(N, 0, N-1) * dT_sec;
// To fit at specific times outcommend the following block
// // Read Quaternion File
// MatrixXd pos;
// qInfo() << "Specify the path to your position file (.txt)";
// IOUtils::read_eigen_matrix(pos, QCoreApplication::applicationDirPath() + "/mne-cpp-test-data/Result/ref_hpiFit_pos.txt");
// RowVectorXd time = pos.col(0);
MatrixXd position; // Position matrix to save quaternions etc.
// setup informations for HPI fit (VectorView)
QVector<int> vFreqs {154,158,161,166};
QVector<double> vError;
VectorXd vGoF;
FiffDigPointSet fittedPointSet;
// Use SSP + SGM + calibration
MatrixXd matProjectors = MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());
//Do a copy here because we are going to change the activity flags of the SSP's
FiffInfo infoTemp = *(pFiffInfo.data());
//Turn on all SSP
for(int i = 0; i < infoTemp.projs.size(); ++i) {
infoTemp.projs[i].active = true;
}
//Create the projector for all SSP's on
infoTemp.make_projector(matProjectors);
//set columns of matrix to zero depending on bad channels indexes
for(qint32 j = 0; j < infoTemp.bads.size(); ++j) {
matProjectors.col(infoTemp.ch_names.indexOf(infoTemp.bads.at(j))).setZero();
}
// if debugging files are necessary set bDoDebug = true;
QString sHPIResourceDir = QCoreApplication::applicationDirPath() + "/HPIFittingDebug";
bool bDoDebug = false;
// initial fit and ordering of frequencies
from = first + time(0)*pFiffInfo->sfreq;
to = from + quantum;
if(!raw.read_raw_segment(matData, times, from, to)) {
qCritical("error during read_raw_segment");
return -1;
}
qInfo() << "[done]";
// order frequencies
qInfo() << "Find Order...";
timer.start();
HPIFit::findOrder(matData,
matProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo);
qInfo() << "Ordered Frequencies: ";
qInfo() << "findOrder() took" << timer.elapsed() << "milliseconds";
qInfo() << "[done]";
// read and fit
for(int i = 0; i < time.size(); i++) {
from = first + time(i)*pFiffInfo->sfreq;
to = from + quantum;
if (to > last) {
to = last;
qWarning() << "Block size < quantum " << quantum;
}
// Reading
if(!raw.read_raw_segment(matData, times, from, to)) {
qCritical("error during read_raw_segment");
return -1;
}
qInfo() << "[done]";
qInfo() << "HPI-Fit...";
timer.start();
HPIFit::fitHPI(matData,
matProjectors,
pFiffInfo->dev_head_t,
vFreqs,
vError,
vGoF,
fittedPointSet,
pFiffInfo,
bDoDebug,
sHPIResourceDir);
qInfo() << "The HPI-Fit took" << timer.elapsed() << "milliseconds";
qInfo() << "[done]";
HPIFit::storeHeadPosition(time(i), pFiffInfo->dev_head_t.trans, position, vGoF, vError);
// if big head displacement occures, update debHeadTrans
if(MNEMath::compareTransformation(devHeadTrans.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {
devHeadTrans = pFiffInfo->dev_head_t;
qInfo() << "dev_head_t has been updated.";
}
}
// IOUtils::write_eigen_matrix(position, QCoreApplication::applicationDirPath() + "/MNE-sample-data/position.txt");
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "lobbychat.h"
#define IN_INCLUDE_LIBIRC_H
#include <core/libircclient/include/libirc_rfcnumeric.h>
#include <net/socket_msg.h>
#include "gamelobbydialogimpl.h"
#include "session.h"
using namespace std;
LobbyChat::LobbyChat(gameLobbyDialogImpl* l) : myLobby(l)
{
}
LobbyChat::~LobbyChat()
{
}
void LobbyChat::sendMessage() {
if (myNick.size())
{
QString tmpMsg(myLobby->lineEdit_ChatInput->text());
if (tmpMsg.size())
{
myLobby->getSession().sendIrcChatMessage(tmpMsg.toUtf8().constData());
myLobby->lineEdit_ChatInput->setText("");
displayMessage(myNick, tmpMsg);
}
}
}
void LobbyChat::connected(QString server)
{
myLobby->textBrowser_ChatDisplay->append(tr("Successfully connected to") + " " + server + ".");
}
void LobbyChat::selfJoined(QString ownName, QString channel)
{
myNick = ownName;
myLobby->textBrowser_ChatDisplay->append(tr("Joined channel:") + " " + channel + " " + tr("as user") + " " + ownName + ".");
myLobby->textBrowser_ChatDisplay->append("");
myLobby->lineEdit_ChatInput->setEnabled(true);
myLobby->lineEdit_ChatInput->setFocus();
}
void LobbyChat::playerJoined(QString playerName)
{
QTreeWidgetItem *item = new QTreeWidgetItem(myLobby->treeWidget_NickList, 0);
item->setData(0, Qt::DisplayRole, playerName);
myLobby->treeWidget_NickList->sortItems(0, Qt::AscendingOrder);
}
void LobbyChat::playerChanged(QString oldNick, QString newNick)
{
QList<QTreeWidgetItem *> tmpList(myLobby->treeWidget_NickList->findItems(oldNick, Qt::MatchExactly));
if (!tmpList.empty())
tmpList.front()->setData(0, Qt::DisplayRole, newNick);
if (myNick == oldNick)
myNick = newNick;
}
void LobbyChat::playerKicked(QString nickName, QString byWhom, QString reason)
{
if (myNick == nickName)
{
myLobby->accept();
QMessageBox::warning(myLobby, tr("Network Notification"),
tr("You were kicked from the server."),
QMessageBox::Close);
}
else
myLobby->textBrowser_ChatDisplay->append(nickName + " " + tr("was kicked from the server by") + " " + byWhom + " (" + reason + ")");
}
void LobbyChat::playerLeft(QString playerName)
{
QList<QTreeWidgetItem *> tmpList(myLobby->treeWidget_NickList->findItems(playerName, Qt::MatchExactly));
if (!tmpList.empty())
myLobby->treeWidget_NickList->takeTopLevelItem(myLobby->treeWidget_NickList->indexOfTopLevelItem(tmpList.front()));
myLobby->treeWidget_NickList->sortItems(0, Qt::AscendingOrder);
}
void LobbyChat::displayMessage(QString playerName, QString message) {
myLobby->textBrowser_ChatDisplay->append(playerName + ": " + message);
}
void LobbyChat::checkInputLength(QString string) {
if(string.toUtf8().length() > 120) myLobby->lineEdit_ChatInput->setMaxLength(string.length());
}
void LobbyChat::clearChat() {
myNick = "";
myLobby->treeWidget_NickList->clear();
myLobby->textBrowser_ChatDisplay->clear();
myLobby->textBrowser_ChatDisplay->append(tr("Connecting to IRC server..."));
myLobby->lineEdit_ChatInput->setEnabled(false);
/* QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta";*/
// QCompleter *completer = new QCompleter(wordList, this);
// completer->setCaseSensitivity(Qt::CaseInsensitive);
// completer->setCompletionMode(QCompleter::InlineCompletion);
// // lineEdit_ChatInput->setCompleter(completer);
}
void LobbyChat::chatError(int errorCode)
{
QString errorMsg;
switch (errorCode)
{
case ERR_IRC_INTERNAL :
case ERR_IRC_SELECT_FAILED :
case ERR_IRC_RECV_FAILED :
case ERR_IRC_SEND_FAILED :
case ERR_IRC_INVALID_PARAM :
errorMsg = tr("An internal IRC error has occured:") + " " + QString::number(errorCode);
break;
case ERR_IRC_CONNECT_FAILED :
errorMsg = tr("Could not connect to the IRC server. Chat will be unavailable.");
break;
case ERR_IRC_TERMINATED :
errorMsg = tr("The IRC server terminated the connection. Chat will be unavailable.");
break;
case ERR_IRC_TIMEOUT :
errorMsg = tr("An IRC action timed out.");
break;
}
if (errorMsg.size())
myLobby->textBrowser_ChatDisplay->append(errorMsg);
}
void LobbyChat::chatServerError(int errorCode)
{
QString errorMsg;
switch (errorCode)
{
case LIBIRC_RFC_ERR_NOSUCHNICK :
case LIBIRC_RFC_ERR_NOSUCHCHANNEL :
case LIBIRC_RFC_ERR_CANNOTSENDTOCHAN :
case LIBIRC_RFC_ERR_TOOMANYCHANNELS :
case LIBIRC_RFC_ERR_WASNOSUCHNICK :
case LIBIRC_RFC_ERR_TOOMANYTARGETS :
case LIBIRC_RFC_ERR_NOSUCHSERVICE :
case LIBIRC_RFC_ERR_NOORIGIN :
case LIBIRC_RFC_ERR_NORECIPIENT :
case LIBIRC_RFC_ERR_NOTEXTTOSEND :
case LIBIRC_RFC_ERR_NOTOPLEVEL :
case LIBIRC_RFC_ERR_WILDTOPLEVEL :
case LIBIRC_RFC_ERR_BADMASK :
case LIBIRC_RFC_ERR_UNKNOWNCOMMAND :
case LIBIRC_RFC_ERR_NOMOTD :
case LIBIRC_RFC_ERR_NOADMININFO :
case LIBIRC_RFC_ERR_FILEERROR :
case LIBIRC_RFC_ERR_NONICKNAMEGIVEN :
case LIBIRC_RFC_ERR_ERRONEUSNICKNAME :
case LIBIRC_RFC_ERR_UNAVAILRESOURCE :
case LIBIRC_RFC_ERR_USERNOTINCHANNEL :
case LIBIRC_RFC_ERR_NOTONCHANNEL :
case LIBIRC_RFC_ERR_USERONCHANNEL :
case LIBIRC_RFC_ERR_NOLOGIN :
case LIBIRC_RFC_ERR_SUMMONDISABLED :
case LIBIRC_RFC_ERR_USERSDISABLED :
case LIBIRC_RFC_ERR_NOTREGISTERED :
case LIBIRC_RFC_ERR_NEEDMOREPARAMS :
case LIBIRC_RFC_ERR_ALREADYREGISTRED :
case LIBIRC_RFC_ERR_NOPERMFORHOST :
case LIBIRC_RFC_ERR_PASSWDMISMATCH :
case LIBIRC_RFC_ERR_YOUREBANNEDCREEP :
case LIBIRC_RFC_ERR_YOUWILLBEBANNED :
case LIBIRC_RFC_ERR_KEYSET :
case LIBIRC_RFC_ERR_CHANNELISFULL :
case LIBIRC_RFC_ERR_UNKNOWNMODE :
case LIBIRC_RFC_ERR_INVITEONLYCHAN :
case LIBIRC_RFC_ERR_BANNEDFROMCHAN :
case LIBIRC_RFC_ERR_BADCHANNELKEY :
case LIBIRC_RFC_ERR_BADCHANMASK :
case LIBIRC_RFC_ERR_NOCHANMODES :
case LIBIRC_RFC_ERR_BANLISTFULL :
case LIBIRC_RFC_ERR_NOPRIVILEGES :
case LIBIRC_RFC_ERR_CHANOPRIVSNEEDED :
case LIBIRC_RFC_ERR_CANTKILLSERVER :
case LIBIRC_RFC_ERR_RESTRICTED :
case LIBIRC_RFC_ERR_UNIQOPPRIVSNEEDED :
case LIBIRC_RFC_ERR_NOOPERHOST :
case LIBIRC_RFC_ERR_UMODEUNKNOWNFLAG :
case LIBIRC_RFC_ERR_USERSDONTMATCH :
errorMsg = tr("The IRC server reported an error:") + " " + QString::number(errorCode);
break;
}
// if (errorMsg.size())
// myLobby->textBrowser_ChatDisplay->append(errorMsg);
}
<commit_msg>Fixed irc rename.<commit_after>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "lobbychat.h"
#define IN_INCLUDE_LIBIRC_H
#include <core/libircclient/include/libirc_rfcnumeric.h>
#include <net/socket_msg.h>
#include "gamelobbydialogimpl.h"
#include "session.h"
using namespace std;
LobbyChat::LobbyChat(gameLobbyDialogImpl* l) : myLobby(l)
{
}
LobbyChat::~LobbyChat()
{
}
void LobbyChat::sendMessage() {
if (myNick.size())
{
QString tmpMsg(myLobby->lineEdit_ChatInput->text());
if (tmpMsg.size())
{
myLobby->getSession().sendIrcChatMessage(tmpMsg.toUtf8().constData());
myLobby->lineEdit_ChatInput->setText("");
displayMessage(myNick, tmpMsg);
}
}
}
void LobbyChat::connected(QString server)
{
myLobby->textBrowser_ChatDisplay->append(tr("Successfully connected to") + " " + server + ".");
}
void LobbyChat::selfJoined(QString ownName, QString channel)
{
myNick = ownName;
myLobby->textBrowser_ChatDisplay->append(tr("Joined channel:") + " " + channel + " " + tr("as user") + " " + ownName + ".");
myLobby->textBrowser_ChatDisplay->append("");
myLobby->lineEdit_ChatInput->setEnabled(true);
myLobby->lineEdit_ChatInput->setFocus();
}
void LobbyChat::playerJoined(QString playerName)
{
QTreeWidgetItem *item = new QTreeWidgetItem(myLobby->treeWidget_NickList, 0);
item->setData(0, Qt::DisplayRole, playerName);
myLobby->treeWidget_NickList->sortItems(0, Qt::AscendingOrder);
}
void LobbyChat::playerChanged(QString oldNick, QString newNick)
{
QList<QTreeWidgetItem *> tmpList(myLobby->treeWidget_NickList->findItems(oldNick, Qt::MatchExactly));
if (!tmpList.empty())
tmpList.front()->setData(0, Qt::DisplayRole, newNick);
else
{
tmpList = myLobby->treeWidget_NickList->findItems("@" + oldNick, Qt::MatchExactly);
if (!tmpList.empty())
tmpList.front()->setData(0, Qt::DisplayRole, "@" + newNick);
}
if (myNick == oldNick)
myNick = newNick;
}
void LobbyChat::playerKicked(QString nickName, QString byWhom, QString reason)
{
if (myNick == nickName)
{
myLobby->accept();
QMessageBox::warning(myLobby, tr("Network Notification"),
tr("You were kicked from the server."),
QMessageBox::Close);
}
else
myLobby->textBrowser_ChatDisplay->append(nickName + " " + tr("was kicked from the server by") + " " + byWhom + " (" + reason + ")");
}
void LobbyChat::playerLeft(QString playerName)
{
QList<QTreeWidgetItem *> tmpList(myLobby->treeWidget_NickList->findItems(playerName, Qt::MatchExactly));
if (!tmpList.empty())
myLobby->treeWidget_NickList->takeTopLevelItem(myLobby->treeWidget_NickList->indexOfTopLevelItem(tmpList.front()));
myLobby->treeWidget_NickList->sortItems(0, Qt::AscendingOrder);
}
void LobbyChat::displayMessage(QString playerName, QString message) {
myLobby->textBrowser_ChatDisplay->append(playerName + ": " + message);
}
void LobbyChat::checkInputLength(QString string) {
if(string.toUtf8().length() > 120) myLobby->lineEdit_ChatInput->setMaxLength(string.length());
}
void LobbyChat::clearChat() {
myNick = "";
myLobby->treeWidget_NickList->clear();
myLobby->textBrowser_ChatDisplay->clear();
myLobby->textBrowser_ChatDisplay->append(tr("Connecting to IRC server..."));
myLobby->lineEdit_ChatInput->setEnabled(false);
/* QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta";*/
// QCompleter *completer = new QCompleter(wordList, this);
// completer->setCaseSensitivity(Qt::CaseInsensitive);
// completer->setCompletionMode(QCompleter::InlineCompletion);
// // lineEdit_ChatInput->setCompleter(completer);
}
void LobbyChat::chatError(int errorCode)
{
QString errorMsg;
switch (errorCode)
{
case ERR_IRC_INTERNAL :
case ERR_IRC_SELECT_FAILED :
case ERR_IRC_RECV_FAILED :
case ERR_IRC_SEND_FAILED :
case ERR_IRC_INVALID_PARAM :
errorMsg = tr("An internal IRC error has occured:") + " " + QString::number(errorCode);
break;
case ERR_IRC_CONNECT_FAILED :
errorMsg = tr("Could not connect to the IRC server. Chat will be unavailable.");
break;
case ERR_IRC_TERMINATED :
errorMsg = tr("The IRC server terminated the connection. Chat will be unavailable.");
break;
case ERR_IRC_TIMEOUT :
errorMsg = tr("An IRC action timed out.");
break;
}
if (errorMsg.size())
myLobby->textBrowser_ChatDisplay->append(errorMsg);
}
void LobbyChat::chatServerError(int errorCode)
{
QString errorMsg;
switch (errorCode)
{
case LIBIRC_RFC_ERR_NOSUCHNICK :
case LIBIRC_RFC_ERR_NOSUCHCHANNEL :
case LIBIRC_RFC_ERR_CANNOTSENDTOCHAN :
case LIBIRC_RFC_ERR_TOOMANYCHANNELS :
case LIBIRC_RFC_ERR_WASNOSUCHNICK :
case LIBIRC_RFC_ERR_TOOMANYTARGETS :
case LIBIRC_RFC_ERR_NOSUCHSERVICE :
case LIBIRC_RFC_ERR_NOORIGIN :
case LIBIRC_RFC_ERR_NORECIPIENT :
case LIBIRC_RFC_ERR_NOTEXTTOSEND :
case LIBIRC_RFC_ERR_NOTOPLEVEL :
case LIBIRC_RFC_ERR_WILDTOPLEVEL :
case LIBIRC_RFC_ERR_BADMASK :
case LIBIRC_RFC_ERR_UNKNOWNCOMMAND :
case LIBIRC_RFC_ERR_NOMOTD :
case LIBIRC_RFC_ERR_NOADMININFO :
case LIBIRC_RFC_ERR_FILEERROR :
case LIBIRC_RFC_ERR_NONICKNAMEGIVEN :
case LIBIRC_RFC_ERR_ERRONEUSNICKNAME :
case LIBIRC_RFC_ERR_UNAVAILRESOURCE :
case LIBIRC_RFC_ERR_USERNOTINCHANNEL :
case LIBIRC_RFC_ERR_NOTONCHANNEL :
case LIBIRC_RFC_ERR_USERONCHANNEL :
case LIBIRC_RFC_ERR_NOLOGIN :
case LIBIRC_RFC_ERR_SUMMONDISABLED :
case LIBIRC_RFC_ERR_USERSDISABLED :
case LIBIRC_RFC_ERR_NOTREGISTERED :
case LIBIRC_RFC_ERR_NEEDMOREPARAMS :
case LIBIRC_RFC_ERR_ALREADYREGISTRED :
case LIBIRC_RFC_ERR_NOPERMFORHOST :
case LIBIRC_RFC_ERR_PASSWDMISMATCH :
case LIBIRC_RFC_ERR_YOUREBANNEDCREEP :
case LIBIRC_RFC_ERR_YOUWILLBEBANNED :
case LIBIRC_RFC_ERR_KEYSET :
case LIBIRC_RFC_ERR_CHANNELISFULL :
case LIBIRC_RFC_ERR_UNKNOWNMODE :
case LIBIRC_RFC_ERR_INVITEONLYCHAN :
case LIBIRC_RFC_ERR_BANNEDFROMCHAN :
case LIBIRC_RFC_ERR_BADCHANNELKEY :
case LIBIRC_RFC_ERR_BADCHANMASK :
case LIBIRC_RFC_ERR_NOCHANMODES :
case LIBIRC_RFC_ERR_BANLISTFULL :
case LIBIRC_RFC_ERR_NOPRIVILEGES :
case LIBIRC_RFC_ERR_CHANOPRIVSNEEDED :
case LIBIRC_RFC_ERR_CANTKILLSERVER :
case LIBIRC_RFC_ERR_RESTRICTED :
case LIBIRC_RFC_ERR_UNIQOPPRIVSNEEDED :
case LIBIRC_RFC_ERR_NOOPERHOST :
case LIBIRC_RFC_ERR_UMODEUNKNOWNFLAG :
case LIBIRC_RFC_ERR_USERSDONTMATCH :
errorMsg = tr("The IRC server reported an error:") + " " + QString::number(errorCode);
break;
}
// if (errorMsg.size())
// myLobby->textBrowser_ChatDisplay->append(errorMsg);
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "Foundation.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "EC_OgrePlaceable.h"
#include "EC_OgreMesh.h"
#include <Ogre.h>
namespace OgreRenderer
{
EC_OgreMesh::EC_OgreMesh(Foundation::ModuleInterface* module) :
Foundation::ComponentInterface(module->GetFramework()),
renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()),
entity_(NULL),
adjustment_node_(NULL),
attached_(false),
scale_to_unity_(false)
{
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
adjustment_node_ = scene_mgr->createSceneNode();
}
EC_OgreMesh::~EC_OgreMesh()
{
RemoveMesh();
if (adjustment_node_)
{
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
scene_mgr->destroySceneNode(adjustment_node_);
adjustment_node_ = NULL;
}
}
void EC_OgreMesh::SetPlaceable(Foundation::ComponentPtr placeable)
{
DetachEntity();
placeable_ = placeable;
AttachEntity();
}
void EC_OgreMesh::SetScaleToUnity(bool enable)
{
scale_to_unity_ = enable;
ScaleEntity();
}
void EC_OgreMesh::SetAdjustPosition(const Core::Vector3df& position)
{
adjustment_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z));
}
void EC_OgreMesh::SetAdjustOrientation(const Core::Quaternion& orientation)
{
adjustment_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
}
Core::Vector3df EC_OgreMesh::GetAdjustPosition() const
{
const Ogre::Vector3& pos = adjustment_node_->getPosition();
return Core::Vector3df(pos.x, pos.y, pos.z);
}
Core::Quaternion EC_OgreMesh::GetAdjustOrientation() const
{
const Ogre::Quaternion& orientation = adjustment_node_->getOrientation();
return Core::Quaternion(orientation.x, orientation.y, orientation.z, orientation.w);
}
bool EC_OgreMesh::SetMesh(const std::string& mesh_name)
{
RemoveMesh();
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().getByName(mesh_name);
if (mesh->hasSkeleton())
{
Ogre::SkeletonPtr skeleton = Ogre::SkeletonManager::getSingleton().getByName(mesh->getSkeletonName());
if (skeleton.isNull() || skeleton->getNumBones() == 0)
{
mesh->setSkeletonName("");
}
}
try
{
entity_ = scene_mgr->createEntity(renderer_->GetUniqueObjectName(), mesh_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogError("Could not set mesh " + mesh_name + ": " + std::string(e.what()));
return false;
}
AttachEntity();
ScaleEntity();
return true;
}
void EC_OgreMesh::RemoveMesh()
{
if (!entity_)
return;
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = NULL;
}
Core::uint EC_OgreMesh::GetNumMaterials()
{
if (!entity_)
return 0;
return entity_->getNumSubEntities();
}
const std::string& EC_OgreMesh::GetMaterialName(Core::uint index)
{
const static std::string empty;
if (!entity_)
return empty;
if (index >= entity_->getNumSubEntities())
return empty;
return entity_->getSubEntity(index)->getMaterialName();
}
bool EC_OgreMesh::SetMaterial(Core::uint index, const std::string& material_name)
{
if (!entity_)
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": no mesh");
return false;
}
if (index >= entity_->getNumSubEntities())
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": illegal submesh index " + Core::ToString<Core::uint>(index));
return false;
}
try
{
entity_->getSubEntity(index)->setMaterialName(material_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": " + std::string(e.what()));
return false;
}
return true;
}
void EC_OgreMesh::DetachEntity()
{
if ((!attached_) || (!entity_) || (!placeable_))
return;
EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get());
Ogre::SceneNode* node = placeable->GetSceneNode();
adjustment_node_->detachObject(entity_);
node->removeChild(adjustment_node_);
attached_ = false;
}
void EC_OgreMesh::AttachEntity()
{
if ((attached_) || (!entity_) || (!placeable_))
return;
EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get());
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(adjustment_node_);
adjustment_node_->attachObject(entity_);
attached_ = true;
}
const std::string& EC_OgreMesh::GetMeshName() const
{
static std::string empty_name;
if (!entity_)
return empty_name;
else
return entity_->getMesh()->getName();
}
void EC_OgreMesh::ScaleEntity()
{
if (!entity_)
return;
Ogre::Vector3 scale(1.0, 1.0, 1.0);
if (scale_to_unity_)
{
const Ogre::AxisAlignedBox& bbox = entity_->getBoundingBox();
Ogre::Vector3 size = bbox.getMaximum() - bbox.getMinimum();
if (size.x != 0.0) scale.x /= size.x;
if (size.y != 0.0) scale.y /= size.y;
if (size.z != 0.0) scale.z /= size.z;
}
adjustment_node_->setScale(scale);
}
}<commit_msg>Emit a warning when a skeleton for a mesh was not loaded properly.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "Foundation.h"
#include "OgreRenderingModule.h"
#include "Renderer.h"
#include "EC_OgrePlaceable.h"
#include "EC_OgreMesh.h"
#include <Ogre.h>
namespace OgreRenderer
{
EC_OgreMesh::EC_OgreMesh(Foundation::ModuleInterface* module) :
Foundation::ComponentInterface(module->GetFramework()),
renderer_(checked_static_cast<OgreRenderingModule*>(module)->GetRenderer()),
entity_(NULL),
adjustment_node_(NULL),
attached_(false),
scale_to_unity_(false)
{
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
adjustment_node_ = scene_mgr->createSceneNode();
}
EC_OgreMesh::~EC_OgreMesh()
{
RemoveMesh();
if (adjustment_node_)
{
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
scene_mgr->destroySceneNode(adjustment_node_);
adjustment_node_ = NULL;
}
}
void EC_OgreMesh::SetPlaceable(Foundation::ComponentPtr placeable)
{
DetachEntity();
placeable_ = placeable;
AttachEntity();
}
void EC_OgreMesh::SetScaleToUnity(bool enable)
{
scale_to_unity_ = enable;
ScaleEntity();
}
void EC_OgreMesh::SetAdjustPosition(const Core::Vector3df& position)
{
adjustment_node_->setPosition(Ogre::Vector3(position.x, position.y, position.z));
}
void EC_OgreMesh::SetAdjustOrientation(const Core::Quaternion& orientation)
{
adjustment_node_->setOrientation(Ogre::Quaternion(orientation.w, orientation.x, orientation.y, orientation.z));
}
Core::Vector3df EC_OgreMesh::GetAdjustPosition() const
{
const Ogre::Vector3& pos = adjustment_node_->getPosition();
return Core::Vector3df(pos.x, pos.y, pos.z);
}
Core::Quaternion EC_OgreMesh::GetAdjustOrientation() const
{
const Ogre::Quaternion& orientation = adjustment_node_->getOrientation();
return Core::Quaternion(orientation.x, orientation.y, orientation.z, orientation.w);
}
bool EC_OgreMesh::SetMesh(const std::string& mesh_name)
{
RemoveMesh();
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().getByName(mesh_name);
if (mesh->hasSkeleton())
{
Ogre::SkeletonPtr skeleton = Ogre::SkeletonManager::getSingleton().getByName(mesh->getSkeletonName());
if (skeleton.isNull() || skeleton->getNumBones() == 0)
{
OgreRenderingModule::LogWarning("Mesh " + mesh_name + " has a skeleton with 0 bones. Disabling the skeleton.");
mesh->setSkeletonName("");
}
}
try
{
entity_ = scene_mgr->createEntity(renderer_->GetUniqueObjectName(), mesh_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogError("Could not set mesh " + mesh_name + ": " + std::string(e.what()));
return false;
}
AttachEntity();
ScaleEntity();
return true;
}
void EC_OgreMesh::RemoveMesh()
{
if (!entity_)
return;
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer_->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = NULL;
}
Core::uint EC_OgreMesh::GetNumMaterials()
{
if (!entity_)
return 0;
return entity_->getNumSubEntities();
}
const std::string& EC_OgreMesh::GetMaterialName(Core::uint index)
{
const static std::string empty;
if (!entity_)
return empty;
if (index >= entity_->getNumSubEntities())
return empty;
return entity_->getSubEntity(index)->getMaterialName();
}
bool EC_OgreMesh::SetMaterial(Core::uint index, const std::string& material_name)
{
if (!entity_)
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": no mesh");
return false;
}
if (index >= entity_->getNumSubEntities())
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": illegal submesh index " + Core::ToString<Core::uint>(index));
return false;
}
try
{
entity_->getSubEntity(index)->setMaterialName(material_name);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogError("Could not set material " + material_name + ": " + std::string(e.what()));
return false;
}
return true;
}
void EC_OgreMesh::DetachEntity()
{
if ((!attached_) || (!entity_) || (!placeable_))
return;
EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get());
Ogre::SceneNode* node = placeable->GetSceneNode();
adjustment_node_->detachObject(entity_);
node->removeChild(adjustment_node_);
attached_ = false;
}
void EC_OgreMesh::AttachEntity()
{
if ((attached_) || (!entity_) || (!placeable_))
return;
EC_OgrePlaceable* placeable = checked_static_cast<EC_OgrePlaceable*>(placeable_.get());
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(adjustment_node_);
adjustment_node_->attachObject(entity_);
attached_ = true;
}
const std::string& EC_OgreMesh::GetMeshName() const
{
static std::string empty_name;
if (!entity_)
return empty_name;
else
return entity_->getMesh()->getName();
}
void EC_OgreMesh::ScaleEntity()
{
if (!entity_)
return;
Ogre::Vector3 scale(1.0, 1.0, 1.0);
if (scale_to_unity_)
{
const Ogre::AxisAlignedBox& bbox = entity_->getBoundingBox();
Ogre::Vector3 size = bbox.getMaximum() - bbox.getMinimum();
if (size.x != 0.0) scale.x /= size.x;
if (size.y != 0.0) scale.y /= size.y;
if (size.z != 0.0) scale.z /= size.z;
}
adjustment_node_->setScale(scale);
}
}<|endoftext|>
|
<commit_before>#include "ofMain.h"
#include "testApp.h"
#include "ofAppGlutWindow.h"
//========================================================================
int main( ){
ofAppGlutWindow window;
ofSetupOpenGL(&window, 1024 ,768, OF_WINDOW); // <-------- setup the GL context
//for having 100% full screen you must change the previous
//declaration for this one:
//ofSetupOpenGL(&window, 1024 ,768, OF_GAME_MODE);
ofRunApp( new testApp());
}
<commit_msg>Fullscreen on XML<commit_after>#include "ofMain.h"
#include "testApp.h"
#include "ofAppGlutWindow.h"
#include "GlobalConfig.hpp"
int main( ){
ofAppGlutWindow window;
if(GlobalConfig::getRef("PROGRAM:FULLSCREEN",0))
ofSetupOpenGL(&window, 1024 ,768, OF_GAME_MODE);
else
ofSetupOpenGL(&window, 1024 ,768, OF_WINDOW);
ofRunApp( new testApp());
}
<|endoftext|>
|
<commit_before>#include <iostream.h>
#include <string.h>
#include "dhash_common.h"
#include "dhash.h"
#include "dhashclient.h"
#include "mud.h"
ptr<dhashclient> dhash;
game_engine *mud;
void done_insert (ptr<avatar> a, int, mud_stat stat);
void really_done (ref<avatar> a, int, mud_stat);
void play (ref<avatar> a);
void done_look (mud_stat, ptr<room>);
void
new_player (str name, int i)
{
str pw ("");
ref<avatar> a = New refcounted<avatar> (name, pw, dhash);
mud->insert (a, wrap (&done_insert, a, i), true);
}
void
done_insert (ptr<avatar> a, int i, mud_stat stat)
{
if (stat == MUD_OK) {
cout << "\nAvatar " << a->get_name () << " creation successful!\n";
mud->enter_player (a, i, wrap (&really_done, a, i));
} else
cout << "Avatar creation error: stat = " << stat << "\n";
}
void
really_done (ref<avatar> a, int i, mud_stat stat)
{
if (stat == MUD_OK) {
cout << "Insert success!!\\n";
char rname[50];
sprintf (rname, "%s%d", "r", i);
ref<room> l = New refcounted<room> (str (rname), dhash);
a->enter (l);
play (a);
}
}
void
play (ref<avatar> a)
{
//pick from move (dest), look, and touch (sth)
//look
mud->lookup (a->loc (), wrap (&done_look));
//touch
}
void
done_look (mud_stat stat, ptr<room> r)
{
if (stat == MUD_OK)
cout << "done_look at current room Received " << r->size () << " bytes\n";
else
cout << "done_look err mud_stat: " << stat << "\n";
}
static void
usage ()
{
warnx << "usage: " << progname << " sock\n";
exit (1);
}
int
main (int argc, char **argv)
{
setprogname (argv[0]);
if (argc < 2)
usage ();
str control_socket = argv[1];
dhash = New refcounted<dhashclient> (control_socket);
mud = New game_engine (dhash);
str name ("a0");
new_player (name, 0);
amain ();
}
<commit_msg>Make synthetic player change an object (re-insert).<commit_after>#include <iostream.h>
#include <string.h>
#include "dhash_common.h"
#include "dhash.h"
#include "dhashclient.h"
#include "mud.h"
ptr<dhashclient> dhash;
game_engine *mud;
ptr<avatar> a;
void done_insert (int, mud_stat);
void really_done (int, mud_stat);
void play (mud_stat);
void done_look (mud_stat, ptr<room>);
void done_touch (ref<thing>, mud_stat);
void
done_insert (int i, mud_stat stat)
{
if (stat == MUD_OK) {
cout << "\nAvatar " << a->get_name () << " creation successful!\n";
mud->enter_player (a, i, wrap (&really_done, i));
} else
cout << "Avatar creation error: stat = " << stat << "\n";
}
void
really_done (int i, mud_stat stat)
{
if (stat == MUD_OK) {
cout << "Insert success!!\n";
char rname[50];
sprintf (rname, "%s%d", "r", i);
ref<room> l = New refcounted<room> (str (rname), dhash);
a->enter (l);
mud->insert (ref<avatar> (a), wrap (&play));
}
}
void
play (mud_stat stat)
{
assert (stat == 0);
//pick from move (dest), look, and touch (sth)
bool look=0, touch=1, move=0;
if (look)
mud->lookup (a->loc (), wrap (&done_look));
if (touch) {
uint n = a->loc ()->things ().size ();
if (n > 0) {
while (1) {
long rn = random ();
float rat = (rn / RAND_MAX);
int i = int (rat * n);
cout << "item to touch " << i << "\n";
ref<thing> t = New refcounted<thing> (a->loc ()->things ()[i]->get_name (),
chordID (a->ID ()));
mud->insert (t, wrap (&done_touch, t));
}
} else
cout << "Nothing to touch.\n";
}
if (move)
;
}
void
done_look (mud_stat stat, ptr<room> r)
{
if (stat == MUD_OK) {
a->enter (r);
cout << "done_look at current room Received " << r->size () << " bytes\n";
} else
cout << "done_look err mud_stat: " << stat << "\n";
}
void
done_touch (ref<thing> t, mud_stat stat)
{
if (stat == MUD_OK) {
cout << "done_touch object "<< t->get_name ()
<< "Inserted " << t->size () << " bytes\n";
} else
cout << "done_touch err mud_stat: " << stat << "\n";
}
void
done_alook (mud_stat stat, ptr<avatar> av)
{
if (stat == MUD_OK) {
a = av;
play (mud_stat (0));
} else
cout << "done_alook err mud_stat: " << stat << "\n";
}
static void
usage ()
{
warnx << "usage: " << progname << " sock init[=0]\n";
exit (1);
}
int
main (int argc, char **argv)
{
setprogname (argv[0]);
if (argc < 2)
usage ();
str control_socket = argv[1];
dhash = New refcounted<dhashclient> (control_socket);
bool init = 0;
if (argc > 2)
init = atoi(argv[2]);
mud = New game_engine (dhash);
int i = 0;
str name ("a0"), pw ("");
if (init) {
a = New refcounted<avatar> (name, pw, dhash);
mud->insert (ref<avatar> (a), wrap (&done_insert, i), true);
} else
mud->lookup (name, wrap (&done_alook));
amain ();
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#include <limits>
#include <dune/grid/io/file/dgfparser.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/grid/provider/default.hh>
#include <dune/stuff/functions/interfaces.hh>
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
/**
* The purpose of this class is to behave like a Stuff::Grid::ConstProviderInterface and at the same time to provide a
* means to obtain the real grid level corresponding to a refinement level.
*/
template< class GridType >
class Base
: public Stuff::Grid::Providers::Default< GridType >
{
typedef Stuff::Grid::Providers::Default< GridType > BaseType;
public:
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
Base(std::shared_ptr< GridType > grd, size_t num_refinements)
: BaseType(grd)
{
levels_.push_back(this->grid()->maxLevel());
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr < num_refinements; ++rr) {
this->grid()->globalRefine(refine_steps_for_half);
levels_.push_back(this->grid()->maxLevel());
}
this->grid()->globalRefine(refine_steps_for_half);
reference_level_ = this->grid()->maxLevel();
} // Base(...)
size_t num_refinements() const
{
assert(levels_.size() > 0);
return levels_.size() - 1;
}
int level_of(const size_t refinement) const
{
assert(refinement < num_refinements());
return levels_[refinement];
}
int reference_level() const
{
return reference_level_;
}
std::shared_ptr< const typename BaseType::LevelGridViewType > reference_grid_view() const
{
return this->level_view(reference_level_);
}
private:
std::vector< int > levels_;
int reference_level_;
}; // class Base
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
<commit_msg>[linearelliptic.testcases.base] fixed assertion<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
#include <limits>
#include <dune/grid/io/file/dgfparser.hh>
#include <dune/stuff/grid/layers.hh>
#include <dune/stuff/grid/provider/default.hh>
#include <dune/stuff/functions/interfaces.hh>
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace TestCases {
/**
* The purpose of this class is to behave like a Stuff::Grid::ConstProviderInterface and at the same time to provide a
* means to obtain the real grid level corresponding to a refinement level.
*/
template< class GridType >
class Base
: public Stuff::Grid::Providers::Default< GridType >
{
typedef Stuff::Grid::Providers::Default< GridType > BaseType;
public:
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
Base(std::shared_ptr< GridType > grd, size_t num_refinements)
: BaseType(grd)
{
levels_.push_back(this->grid()->maxLevel());
static const int refine_steps_for_half = DGFGridInfo< GridType >::refineStepsForHalf();
for (size_t rr = 0; rr < num_refinements; ++rr) {
this->grid()->globalRefine(refine_steps_for_half);
levels_.push_back(this->grid()->maxLevel());
}
this->grid()->globalRefine(refine_steps_for_half);
reference_level_ = this->grid()->maxLevel();
} // Base(...)
size_t num_refinements() const
{
assert(levels_.size() > 0);
return levels_.size() - 1;
}
int level_of(const size_t refinement) const
{
assert(refinement <= num_refinements());
return levels_[refinement];
}
int reference_level() const
{
return reference_level_;
}
std::shared_ptr< const typename BaseType::LevelGridViewType > reference_grid_view() const
{
return this->level_view(reference_level_);
}
private:
std::vector< int > levels_;
int reference_level_;
}; // class Base
} // namespace TestCases
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_HH
<|endoftext|>
|
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "slam-precomp.h" // Precompiled headerss
#include <mrpt/slam/CMonteCarloLocalization2D.h>
#include <mrpt/system/CTicTac.h>
#include <mrpt/maps/COccupancyGridMap2D.h>
#include <mrpt/obs/CActionCollection.h>
#include <mrpt/obs/CSensoryFrame.h>
#include <mrpt/random.h>
#include <mrpt/slam/PF_aux_structs.h>
using namespace mrpt;
using namespace mrpt::bayes;
using namespace mrpt::poses;
using namespace mrpt::math;
using namespace mrpt::maps;
using namespace mrpt::obs;
using namespace mrpt::slam;
using namespace mrpt::random;
using namespace std;
#include <mrpt/slam/PF_implementations_data.h>
namespace mrpt
{
namespace slam
{
/** Fills out a "TPoseBin2D" variable, given a path hypotesis and (if not set to
* nullptr) a new pose appended at the end, using the KLD params in "options".
*/
template <>
void KLF_loadBinFromParticle(
mrpt::slam::detail::TPoseBin2D& outBin, const TKLDParams& opts,
const CMonteCarloLocalization2D::CParticleDataContent* currentParticleValue,
const TPose3D* newPoseToBeInserted)
{
// 2D pose approx: Use the latest pose only:
if (newPoseToBeInserted)
{
outBin.x = round(newPoseToBeInserted->x / opts.KLD_binSize_XY);
outBin.y = round(newPoseToBeInserted->y / opts.KLD_binSize_XY);
outBin.phi = round(newPoseToBeInserted->yaw / opts.KLD_binSize_PHI);
}
else
{
ASSERT_(currentParticleValue);
outBin.x = round(currentParticleValue->x / opts.KLD_binSize_XY);
outBin.y = round(currentParticleValue->y / opts.KLD_binSize_XY);
outBin.phi = round(currentParticleValue->phi / opts.KLD_binSize_PHI);
}
}
}
}
#include <mrpt/slam/PF_implementations.h>
/*---------------------------------------------------------------
ctor
---------------------------------------------------------------*/
// Passing a "this" pointer at this moment is not a problem since it will be NOT
// access until the object is fully initialized
CMonteCarloLocalization2D::CMonteCarloLocalization2D(size_t M)
: CPosePDFParticles(M)
{
this->setLoggerName("CMonteCarloLocalization2D");
}
CMonteCarloLocalization2D::~CMonteCarloLocalization2D() {}
TPose3D CMonteCarloLocalization2D::getLastPose(
const size_t i, bool& is_valid_pose) const
{
if (i >= m_particles.size())
THROW_EXCEPTION("Particle index out of bounds!");
is_valid_pose = true;
ASSERTDEB_(m_particles[i].d);
return TPose3D(m_particles[i].d);
}
/*---------------------------------------------------------------
prediction_and_update_pfStandardProposal
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfStandardProposal(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfStandardProposal<mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
prediction_and_update_pfAuxiliaryPFStandard
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfAuxiliaryPFStandard(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfAuxiliaryPFStandard<
mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
prediction_and_update_pfAuxiliaryPFOptimal
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfAuxiliaryPFOptimal(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfAuxiliaryPFOptimal<mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
PF_SLAM_computeObservationLikelihoodForParticle
---------------------------------------------------------------*/
double
CMonteCarloLocalization2D::PF_SLAM_computeObservationLikelihoodForParticle(
const CParticleFilter::TParticleFilterOptions& PF_options,
const size_t particleIndexForMap, const CSensoryFrame& observation,
const CPose3D& x) const
{
MRPT_UNUSED_PARAM(PF_options);
ASSERT_(
options.metricMap || particleIndexForMap < options.metricMaps.size());
CMetricMap* map =
(options.metricMap) ? options.metricMap : // All particles, one map
options.metricMaps[particleIndexForMap]; // One map per particle
// For each observation:
double ret = 1;
for (CSensoryFrame::const_iterator it = observation.begin();
it != observation.end(); ++it)
ret += map->computeObservationLikelihood(
it->get(), x); // Compute the likelihood:
// Done!
return ret;
}
// Specialization for my kind of particles:
void CMonteCarloLocalization2D::
PF_SLAM_implementation_custom_update_particle_with_new_pose(
TPose2D* particleData, const TPose3D& newPose) const
{
*particleData = TPose2D(newPose);
}
void CMonteCarloLocalization2D::PF_SLAM_implementation_replaceByNewParticleSet(
CParticleList& old_particles, const vector<TPose3D>& newParticles,
const vector<double>& newParticlesWeight,
const vector<size_t>& newParticlesDerivedFromIdx) const
{
MRPT_UNUSED_PARAM(newParticlesDerivedFromIdx);
ASSERT_EQUAL_(
size_t(newParticlesWeight.size()), size_t(newParticles.size()));
// ---------------------------------------------------------------------------------
// Substitute old by new particle set:
// Old are in "m_particles"
// New are in "newParticles",
// "newParticlesWeight","newParticlesDerivedFromIdx"
// ---------------------------------------------------------------------------------
// Free old m_particles: not needed since "d" is now a smart ptr
// Copy into "m_particles"
const size_t N = newParticles.size();
old_particles.resize(N);
for (size_t i = 0; i < N; i++)
{
old_particles[i].log_w = newParticlesWeight[i];
old_particles[i].d = TPose2D(newParticles[i]);
}
}
void CMonteCarloLocalization2D::resetUniformFreeSpace(
COccupancyGridMap2D* theMap, const double freeCellsThreshold,
const int particlesCount, const double x_min, const double x_max,
const double y_min, const double y_max, const double phi_min,
const double phi_max)
{
MRPT_START
ASSERT_(theMap != nullptr);
int sizeX = theMap->getSizeX();
int sizeY = theMap->getSizeY();
double gridRes = theMap->getResolution();
std::vector<double> freeCells_x, freeCells_y;
size_t nFreeCells;
unsigned int xIdx1, xIdx2;
unsigned int yIdx1, yIdx2;
freeCells_x.reserve(sizeX * sizeY);
freeCells_y.reserve(sizeX * sizeY);
if (x_min > theMap->getXMin())
xIdx1 = max(0, theMap->x2idx(x_min));
else
xIdx1 = 0;
if (x_max < theMap->getXMax())
xIdx2 = min(sizeX - 1, theMap->x2idx(x_max));
else
xIdx2 = sizeX - 1;
if (y_min > theMap->getYMin())
yIdx1 = max(0, theMap->y2idx(y_min));
else
yIdx1 = 0;
if (y_max < theMap->getYMax())
yIdx2 = min(sizeY - 1, theMap->y2idx(y_max));
else
yIdx2 = sizeY - 1;
for (unsigned int x = xIdx1; x <= xIdx2; x++)
for (unsigned int y = yIdx1; y <= yIdx2; y++)
if (theMap->getCell(x, y) >= freeCellsThreshold)
{
freeCells_x.push_back(theMap->idx2x(x));
freeCells_y.push_back(theMap->idx2y(y));
}
nFreeCells = freeCells_x.size();
// Assure that map is not fully occupied!
ASSERT_(nFreeCells);
if (particlesCount > 0)
m_particles.resize(particlesCount);
const size_t M = m_particles.size();
// Generate pose m_particles:
for (size_t i = 0; i < M; i++)
{
int idx =
round(getRandomGenerator().drawUniform(0.0, nFreeCells - 1.001));
m_particles[i].d.x=
freeCells_x[idx] +
getRandomGenerator().drawUniform(-gridRes, gridRes);
m_particles[i].d.y=
freeCells_y[idx] +
getRandomGenerator().drawUniform(-gridRes, gridRes);
m_particles[i].d.phi =
getRandomGenerator().drawUniform(phi_min, phi_max);
m_particles[i].log_w = 0;
}
MRPT_END
}
<commit_msg>Get rid of broken ASSERTDEB_ <commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "slam-precomp.h" // Precompiled headerss
#include <mrpt/slam/CMonteCarloLocalization2D.h>
#include <mrpt/system/CTicTac.h>
#include <mrpt/maps/COccupancyGridMap2D.h>
#include <mrpt/obs/CActionCollection.h>
#include <mrpt/obs/CSensoryFrame.h>
#include <mrpt/random.h>
#include <mrpt/slam/PF_aux_structs.h>
using namespace mrpt;
using namespace mrpt::bayes;
using namespace mrpt::poses;
using namespace mrpt::math;
using namespace mrpt::maps;
using namespace mrpt::obs;
using namespace mrpt::slam;
using namespace mrpt::random;
using namespace std;
#include <mrpt/slam/PF_implementations_data.h>
namespace mrpt
{
namespace slam
{
/** Fills out a "TPoseBin2D" variable, given a path hypotesis and (if not set to
* nullptr) a new pose appended at the end, using the KLD params in "options".
*/
template <>
void KLF_loadBinFromParticle(
mrpt::slam::detail::TPoseBin2D& outBin, const TKLDParams& opts,
const CMonteCarloLocalization2D::CParticleDataContent* currentParticleValue,
const TPose3D* newPoseToBeInserted)
{
// 2D pose approx: Use the latest pose only:
if (newPoseToBeInserted)
{
outBin.x = round(newPoseToBeInserted->x / opts.KLD_binSize_XY);
outBin.y = round(newPoseToBeInserted->y / opts.KLD_binSize_XY);
outBin.phi = round(newPoseToBeInserted->yaw / opts.KLD_binSize_PHI);
}
else
{
ASSERT_(currentParticleValue);
outBin.x = round(currentParticleValue->x / opts.KLD_binSize_XY);
outBin.y = round(currentParticleValue->y / opts.KLD_binSize_XY);
outBin.phi = round(currentParticleValue->phi / opts.KLD_binSize_PHI);
}
}
}
}
#include <mrpt/slam/PF_implementations.h>
/*---------------------------------------------------------------
ctor
---------------------------------------------------------------*/
// Passing a "this" pointer at this moment is not a problem since it will be NOT
// access until the object is fully initialized
CMonteCarloLocalization2D::CMonteCarloLocalization2D(size_t M)
: CPosePDFParticles(M)
{
this->setLoggerName("CMonteCarloLocalization2D");
}
CMonteCarloLocalization2D::~CMonteCarloLocalization2D() {}
TPose3D CMonteCarloLocalization2D::getLastPose(
const size_t i, bool& is_valid_pose) const
{
if (i >= m_particles.size())
THROW_EXCEPTION("Particle index out of bounds!");
is_valid_pose = true;
return TPose3D(m_particles[i].d);
}
/*---------------------------------------------------------------
prediction_and_update_pfStandardProposal
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfStandardProposal(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfStandardProposal<mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
prediction_and_update_pfAuxiliaryPFStandard
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfAuxiliaryPFStandard(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfAuxiliaryPFStandard<
mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
prediction_and_update_pfAuxiliaryPFOptimal
---------------------------------------------------------------*/
void CMonteCarloLocalization2D::prediction_and_update_pfAuxiliaryPFOptimal(
const mrpt::obs::CActionCollection* actions,
const mrpt::obs::CSensoryFrame* sf,
const bayes::CParticleFilter::TParticleFilterOptions& PF_options)
{
MRPT_START
if (sf)
{ // A map MUST be supplied!
ASSERT_(options.metricMap || options.metricMaps.size() > 0);
if (!options.metricMap)
ASSERT_(options.metricMaps.size() == m_particles.size());
}
PF_SLAM_implementation_pfAuxiliaryPFOptimal<mrpt::slam::detail::TPoseBin2D>(
actions, sf, PF_options, options.KLD_params);
MRPT_END
}
/*---------------------------------------------------------------
PF_SLAM_computeObservationLikelihoodForParticle
---------------------------------------------------------------*/
double
CMonteCarloLocalization2D::PF_SLAM_computeObservationLikelihoodForParticle(
const CParticleFilter::TParticleFilterOptions& PF_options,
const size_t particleIndexForMap, const CSensoryFrame& observation,
const CPose3D& x) const
{
MRPT_UNUSED_PARAM(PF_options);
ASSERT_(
options.metricMap || particleIndexForMap < options.metricMaps.size());
CMetricMap* map =
(options.metricMap) ? options.metricMap : // All particles, one map
options.metricMaps[particleIndexForMap]; // One map per particle
// For each observation:
double ret = 1;
for (CSensoryFrame::const_iterator it = observation.begin();
it != observation.end(); ++it)
ret += map->computeObservationLikelihood(
it->get(), x); // Compute the likelihood:
// Done!
return ret;
}
// Specialization for my kind of particles:
void CMonteCarloLocalization2D::
PF_SLAM_implementation_custom_update_particle_with_new_pose(
TPose2D* particleData, const TPose3D& newPose) const
{
*particleData = TPose2D(newPose);
}
void CMonteCarloLocalization2D::PF_SLAM_implementation_replaceByNewParticleSet(
CParticleList& old_particles, const vector<TPose3D>& newParticles,
const vector<double>& newParticlesWeight,
const vector<size_t>& newParticlesDerivedFromIdx) const
{
MRPT_UNUSED_PARAM(newParticlesDerivedFromIdx);
ASSERT_EQUAL_(
size_t(newParticlesWeight.size()), size_t(newParticles.size()));
// ---------------------------------------------------------------------------------
// Substitute old by new particle set:
// Old are in "m_particles"
// New are in "newParticles",
// "newParticlesWeight","newParticlesDerivedFromIdx"
// ---------------------------------------------------------------------------------
// Free old m_particles: not needed since "d" is now a smart ptr
// Copy into "m_particles"
const size_t N = newParticles.size();
old_particles.resize(N);
for (size_t i = 0; i < N; i++)
{
old_particles[i].log_w = newParticlesWeight[i];
old_particles[i].d = TPose2D(newParticles[i]);
}
}
void CMonteCarloLocalization2D::resetUniformFreeSpace(
COccupancyGridMap2D* theMap, const double freeCellsThreshold,
const int particlesCount, const double x_min, const double x_max,
const double y_min, const double y_max, const double phi_min,
const double phi_max)
{
MRPT_START
ASSERT_(theMap != nullptr);
int sizeX = theMap->getSizeX();
int sizeY = theMap->getSizeY();
double gridRes = theMap->getResolution();
std::vector<double> freeCells_x, freeCells_y;
size_t nFreeCells;
unsigned int xIdx1, xIdx2;
unsigned int yIdx1, yIdx2;
freeCells_x.reserve(sizeX * sizeY);
freeCells_y.reserve(sizeX * sizeY);
if (x_min > theMap->getXMin())
xIdx1 = max(0, theMap->x2idx(x_min));
else
xIdx1 = 0;
if (x_max < theMap->getXMax())
xIdx2 = min(sizeX - 1, theMap->x2idx(x_max));
else
xIdx2 = sizeX - 1;
if (y_min > theMap->getYMin())
yIdx1 = max(0, theMap->y2idx(y_min));
else
yIdx1 = 0;
if (y_max < theMap->getYMax())
yIdx2 = min(sizeY - 1, theMap->y2idx(y_max));
else
yIdx2 = sizeY - 1;
for (unsigned int x = xIdx1; x <= xIdx2; x++)
for (unsigned int y = yIdx1; y <= yIdx2; y++)
if (theMap->getCell(x, y) >= freeCellsThreshold)
{
freeCells_x.push_back(theMap->idx2x(x));
freeCells_y.push_back(theMap->idx2y(y));
}
nFreeCells = freeCells_x.size();
// Assure that map is not fully occupied!
ASSERT_(nFreeCells);
if (particlesCount > 0)
m_particles.resize(particlesCount);
const size_t M = m_particles.size();
// Generate pose m_particles:
for (size_t i = 0; i < M; i++)
{
int idx =
round(getRandomGenerator().drawUniform(0.0, nFreeCells - 1.001));
m_particles[i].d.x=
freeCells_x[idx] +
getRandomGenerator().drawUniform(-gridRes, gridRes);
m_particles[i].d.y=
freeCells_y[idx] +
getRandomGenerator().drawUniform(-gridRes, gridRes);
m_particles[i].d.phi =
getRandomGenerator().drawUniform(phi_min, phi_max);
m_particles[i].log_w = 0;
}
MRPT_END
}
<|endoftext|>
|
<commit_before>#include "thrusttest/testframework.h"
#include "thrusttest/exceptions.h"
#include <cuda_runtime.h>
#include <iostream>
#include <cstdlib>
#include <algorithm>
void UnitTestDriver::register_test(UnitTest *test)
{
UnitTestDriver::s_driver()._test_list.push_back(test);
}
UnitTest::UnitTest(const char * _name) : name(_name)
{
UnitTestDriver::s_driver().register_test(this);
}
bool UnitTestDriver::run_tests(const std::vector<UnitTest *> &tests_to_run, const bool verbose)
{
bool any_failed = false;
std::cout << "Running " << tests_to_run.size() << " unit tests." << std::endl;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestFailure> > test_failures;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestKnownFailure> > test_known_failures;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestError> > test_errors;
std::vector< UnitTest * > test_exceptions;
cudaError_t error = cudaGetLastError();
if(error){
std::cerr << "[ERROR] CUDA Error detected before running tests: [";
std::cerr << std::string(cudaGetErrorString(error));
std::cerr << "]" << std::endl;
exit(EXIT_FAILURE);
}
for(size_t i = 0; i < tests_to_run.size(); i++){
UnitTest * test = tests_to_run[i];
if (verbose)
std::cout << "Running " << test->name << "\r" << std::flush;
try {
test->run();
if (verbose)
std::cout << "[PASS] ";
else
std::cout << ".";
}
catch (thrusttest::UnitTestFailure& f){
any_failed = true;
if (verbose)
std::cout << "[FAILURE] ";
else
std::cout << "F";
test_failures.push_back(std::make_pair(test,f));
}
catch (thrusttest::UnitTestKnownFailure& f){
if (verbose)
std::cout << "[KNOWN FAILURE] ";
else
std::cout << "K";
test_known_failures.push_back(std::make_pair(test,f));
}
catch (thrusttest::UnitTestError& e){
any_failed = true;
if (verbose)
std::cout << "[ERROR] ";
else
std::cout << "E";
test_errors.push_back(std::make_pair(test,e));
}
catch (...){
any_failed = true;
if (verbose)
std::cout << "[UNKNOWN EXCEPTION] " << std::endl;
else
std::cout << "U";
test_exceptions.push_back(test);
}
if (verbose)
std::cout << " " << test->name << std::endl;
error = cudaGetLastError();
if(error){
std::cerr << "\t[ERROR] CUDA Error detected after running " << test->name << ": [";
std::cerr << std::string(cudaGetErrorString(error));
std::cerr << "]" << std::endl;
exit(EXIT_FAILURE);
}
std::cout.flush();
}
std::cout << std::endl;
std::string hline = "================================================================";
for(size_t i = 0; i < test_failures.size(); i++){
std::cout << hline << std::endl;
std::cout << "FAILURE: " << test_failures[i].first->name << std::endl;
std::cout << test_failures[i].second << std::endl;
}
for(size_t i = 0; i < test_known_failures.size(); i++){
std::cout << hline << std::endl;
std::cout << "KNOWN FAILURE: " << test_known_failures[i].first->name << std::endl;
std::cout << test_known_failures[i].second << std::endl;
}
for(size_t i = 0; i < test_errors.size(); i++){
std::cout << hline << std::endl;
std::cout << "ERROR: " << test_errors[i].first->name << std::endl;
std::cout << test_errors[i].second << std::endl;
}
for(size_t i = 0; i < test_exceptions.size(); i++){
std::cout << hline << std::endl;
std::cout << "UNKNOWN EXCEPTION: " << test_exceptions[i]->name << std::endl;
}
std::cout << hline << std::endl;
std::cout << "Totals: ";
std::cout << test_failures.size() << " failures, ";
std::cout << test_known_failures.size() << " known failures, ";
std::cout << test_errors.size() << " errors and ";
std::cout << test_exceptions.size() << " unknown exceptions." << std::endl;
return any_failed;
}
// for sorting UnitTests by name
struct UnitTest_name_cmp
{
bool operator()(const UnitTest * a, const UnitTest * b) const {
return a->name < b->name;
}
};
bool UnitTestDriver::run_all_tests(const bool verbose)
{
std::vector<UnitTest *> tests_to_run(_test_list);
// sort tests by name for deterministic results
std::sort(tests_to_run.begin(), tests_to_run.end(), UnitTest_name_cmp());
return run_tests(tests_to_run, verbose);
}
bool
UnitTestDriver::run_tests(const std::vector<std::string> &tests, const bool verbose)
{
int i, j;
std::vector<UnitTest *> tests_to_run;
for (j=0; j < tests.size(); j++) {
bool found = false;
for (i = 0; !found && i < _test_list.size(); i++)
if (tests[j] == _test_list[i]->name) {
tests_to_run.push_back(_test_list[i]);
found = true;
}
if (!found) {
printf("[WARNING] UnitTestDriver::run_tests - test %s not found\n", tests[j].c_str());
}
}
return run_tests(tests_to_run, verbose);
}
UnitTestDriver &
UnitTestDriver::s_driver()
{
static UnitTestDriver s_instance;
return s_instance;
}
<commit_msg>Correctly return the status of unit tests in testframework.cpp.<commit_after>#include "thrusttest/testframework.h"
#include "thrusttest/exceptions.h"
#include <cuda_runtime.h>
#include <iostream>
#include <cstdlib>
#include <algorithm>
void UnitTestDriver::register_test(UnitTest *test)
{
UnitTestDriver::s_driver()._test_list.push_back(test);
}
UnitTest::UnitTest(const char * _name) : name(_name)
{
UnitTestDriver::s_driver().register_test(this);
}
bool UnitTestDriver::run_tests(const std::vector<UnitTest *> &tests_to_run, const bool verbose)
{
bool all_passed = true;
std::cout << "Running " << tests_to_run.size() << " unit tests." << std::endl;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestFailure> > test_failures;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestKnownFailure> > test_known_failures;
std::vector< std::pair<UnitTest *,thrusttest::UnitTestError> > test_errors;
std::vector< UnitTest * > test_exceptions;
cudaError_t error = cudaGetLastError();
if(error){
std::cerr << "[ERROR] CUDA Error detected before running tests: [";
std::cerr << std::string(cudaGetErrorString(error));
std::cerr << "]" << std::endl;
exit(EXIT_FAILURE);
}
for(size_t i = 0; i < tests_to_run.size(); i++){
UnitTest * test = tests_to_run[i];
if (verbose)
std::cout << "Running " << test->name << "\r" << std::flush;
try {
test->run();
if (verbose)
std::cout << "[PASS] ";
else
std::cout << ".";
}
catch (thrusttest::UnitTestFailure& f){
all_passed = false;
if (verbose)
std::cout << "[FAILURE] ";
else
std::cout << "F";
test_failures.push_back(std::make_pair(test,f));
}
catch (thrusttest::UnitTestKnownFailure& f){
if (verbose)
std::cout << "[KNOWN FAILURE] ";
else
std::cout << "K";
test_known_failures.push_back(std::make_pair(test,f));
}
catch (thrusttest::UnitTestError& e){
all_passed = false;
if (verbose)
std::cout << "[ERROR] ";
else
std::cout << "E";
test_errors.push_back(std::make_pair(test,e));
}
catch (...){
all_passed = false;
if (verbose)
std::cout << "[UNKNOWN EXCEPTION] " << std::endl;
else
std::cout << "U";
test_exceptions.push_back(test);
}
if (verbose)
std::cout << " " << test->name << std::endl;
error = cudaGetLastError();
if(error){
std::cerr << "\t[ERROR] CUDA Error detected after running " << test->name << ": [";
std::cerr << std::string(cudaGetErrorString(error));
std::cerr << "]" << std::endl;
exit(EXIT_FAILURE);
}
std::cout.flush();
}
std::cout << std::endl;
std::string hline = "================================================================";
for(size_t i = 0; i < test_failures.size(); i++){
std::cout << hline << std::endl;
std::cout << "FAILURE: " << test_failures[i].first->name << std::endl;
std::cout << test_failures[i].second << std::endl;
}
for(size_t i = 0; i < test_known_failures.size(); i++){
std::cout << hline << std::endl;
std::cout << "KNOWN FAILURE: " << test_known_failures[i].first->name << std::endl;
std::cout << test_known_failures[i].second << std::endl;
}
for(size_t i = 0; i < test_errors.size(); i++){
std::cout << hline << std::endl;
std::cout << "ERROR: " << test_errors[i].first->name << std::endl;
std::cout << test_errors[i].second << std::endl;
}
for(size_t i = 0; i < test_exceptions.size(); i++){
std::cout << hline << std::endl;
std::cout << "UNKNOWN EXCEPTION: " << test_exceptions[i]->name << std::endl;
}
std::cout << hline << std::endl;
std::cout << "Totals: ";
std::cout << test_failures.size() << " failures, ";
std::cout << test_known_failures.size() << " known failures, ";
std::cout << test_errors.size() << " errors and ";
std::cout << test_exceptions.size() << " unknown exceptions." << std::endl;
return all_passed;
}
// for sorting UnitTests by name
struct UnitTest_name_cmp
{
bool operator()(const UnitTest * a, const UnitTest * b) const {
return a->name < b->name;
}
};
bool UnitTestDriver::run_all_tests(const bool verbose)
{
std::vector<UnitTest *> tests_to_run(_test_list);
// sort tests by name for deterministic results
std::sort(tests_to_run.begin(), tests_to_run.end(), UnitTest_name_cmp());
return run_tests(tests_to_run, verbose);
}
bool
UnitTestDriver::run_tests(const std::vector<std::string> &tests, const bool verbose)
{
int i, j;
std::vector<UnitTest *> tests_to_run;
for (j=0; j < tests.size(); j++) {
bool found = false;
for (i = 0; !found && i < _test_list.size(); i++)
if (tests[j] == _test_list[i]->name) {
tests_to_run.push_back(_test_list[i]);
found = true;
}
if (!found) {
printf("[WARNING] UnitTestDriver::run_tests - test %s not found\n", tests[j].c_str());
}
}
return run_tests(tests_to_run, verbose);
}
UnitTestDriver &
UnitTestDriver::s_driver()
{
static UnitTestDriver s_instance;
return s_instance;
}
<|endoftext|>
|
<commit_before>#include "bodyParts.hpp"
#include "creature.hpp"
#include "world.hpp"
#include "pheromoneMap.hpp"
#include "ant.hpp"
AntLegs::AntLegs(World* w, Creature* owner) : BodyPart(w,owner)
{
targetPos_=owner->getPos();
}
void AntLegs::goToPos(const Point& p){
targetPos_=p;
}
void AntLegs::step(int deltatime){
while((deltatime--)>0){
Point curPos=owner_->getPos();
int x=curPos.posX();
int y=curPos.posY();
if(curPos.posX() != targetPos_.posX())
x+= (curPos.posX() < targetPos_.posX()) ? 1 : -1;
if(curPos.posY() != targetPos_.posY())
y+= (curPos.posY() < targetPos_.posY()) ? 1 : -1;
// check if this position is free (there is no other creature)
// (detect collision)
for(auto a : world_->getSimulationObjects<Creature>()){
if(a->getPos() == Point(x,y)){
// collision detected
return;
}
}
owner_->setPos(Point(x,y));
}
}
// AntSensor
Point AntSensor::Observation::getPos()const{
return ent_.lock()->getPos();
}
int AntSensor::Observation::getSmell()const{
return ent_.lock()->getSmell();
}
std::vector<AntSensor::Observation> AntSensor::getEntities(){
std::vector<Observation> ret;
for(auto& a : world_->getEntityPtrs()){
if(a.lock()->getPos().getDistance(owner_->getPos()) <= 4)
ret.push_back(Observation(a));
}
Point ownerPos=owner_->getPos();
std::sort(ret.begin(),ret.end(),
[ownerPos] (const Observation& a,const Observation& b) -> bool
{ return ownerPos.getDistance(a.getPos())
< ownerPos.getDistance(b.getPos()); });
return ret;
}
// AntMandibles
boost::weak_ptr<Entity> AntMandibles::getHoldingObject() const
{
return holdingObject_;
}
bool AntMandibles::grab(boost::weak_ptr<Entity> e){
if(owner_->getPos()!=e.lock()->getPos())
return 0;
if(isHolding()){
return 0;
}
holdingObject_=e;
return 1;
}
bool AntMandibles::grab(AntSensor::Observation o){
grab(o.ent_);
return 1;
}
void AntMandibles::step(int deltaTime){
if(isHolding()){
holdingObject_.lock()->setPos(owner_->getPos());
}
}
void AntMandibles::accept(Visitor &v) const
{
v.visit(*this);
}
// AntWorkerAbdomen
void AntWorkerAbdomen::dropToFoodPheromones(){
dropType=PheromoneMap::Type::ToFood;
}
void AntWorkerAbdomen::dropFromFoodPheromones(){
dropType=PheromoneMap::Type::FromFood;
}
void AntWorkerAbdomen::step(int deltaTime){
if(deltaTime<=0)
return;
if(dropType == PheromoneMap::Type::None)
return;
for(auto pm : world_->getSimulationObjects<PheromoneMap>()){
if(pm->getType()==dropType){
pm->createBlob(owner_->getPos(), 2, 100);
return;
}
}
dropType = PheromoneMap::Type::None;
}
<commit_msg>added collision detection and picking up stuff from adjecent blocks<commit_after>#include "bodyParts.hpp"
#include <set>
#include "creature.hpp"
#include "world.hpp"
#include "pheromoneMap.hpp"
#include "ant.hpp"
AntLegs::AntLegs(World* w, Creature* owner) : BodyPart(w,owner)
{
targetPos_=owner->getPos();
}
void AntLegs::goToPos(const Point& p){
targetPos_=p;
}
void AntLegs::step(int deltatime){
while((deltatime--)>0){
Point curPos=owner_->getPos();
int x=curPos.posX();
int y=curPos.posY();
if(curPos.posX() != targetPos_.posX())
x+= (curPos.posX() < targetPos_.posX()) ? 1 : -1;
if(curPos.posY() != targetPos_.posY())
y+= (curPos.posY() < targetPos_.posY()) ? 1 : -1;
// check if this position is free (there is no other creature)
// (detect collision)
for(auto a : world_->getEntityPtrs()){
if(a.lock()->getPos() == Point(x,y)){
// collision detected
return;
}
}
owner_->setPos(Point(x,y));
}
}
// AntSensor
Point AntSensor::Observation::getPos()const{
return ent_.lock()->getPos();
}
int AntSensor::Observation::getSmell()const{
return ent_.lock()->getSmell();
}
std::vector<AntSensor::Observation> AntSensor::getEntities(){
std::vector<Observation> ret;
for(auto& a : world_->getEntityPtrs()){
if(a.lock()->getPos().getDistance(owner_->getPos()) <= 4)
ret.push_back(Observation(a));
}
Point ownerPos=owner_->getPos();
std::sort(ret.begin(),ret.end(),
[ownerPos] (const Observation& a,const Observation& b) -> bool
{ return ownerPos.getDistance(a.getPos())
< ownerPos.getDistance(b.getPos()); });
return ret;
}
// AntMandibles
boost::weak_ptr<Entity> AntMandibles::getHoldingObject() const
{
return holdingObject_;
}
bool AntMandibles::grab(boost::weak_ptr<Entity> e){
if(isHolding())
return false;
// can grab from adjecent positions
std::set<Point> grab_from;
const auto& my_pos = owner_->getPos();
grab_from.insert(my_pos + Point(1, 0));
grab_from.insert(my_pos + Point(-1, 0));
grab_from.insert(my_pos + Point(0, 1));
grab_from.insert(my_pos + Point(0, -1));
for (const auto& pos : grab_from)
{
if (pos == e.lock()->getPos())
{
holdingObject_ = e;
break;
}
}
return true;
}
bool AntMandibles::grab(AntSensor::Observation o){
grab(o.ent_);
return 1;
}
void AntMandibles::step(int deltaTime){
if(isHolding()){
holdingObject_.lock()->setPos(owner_->getPos());
}
}
void AntMandibles::accept(Visitor &v) const
{
v.visit(*this);
}
// AntWorkerAbdomen
void AntWorkerAbdomen::dropToFoodPheromones(){
dropType=PheromoneMap::Type::ToFood;
}
void AntWorkerAbdomen::dropFromFoodPheromones(){
dropType=PheromoneMap::Type::FromFood;
}
void AntWorkerAbdomen::step(int deltaTime){
if(deltaTime<=0)
return;
if(dropType == PheromoneMap::Type::None)
return;
for(auto pm : world_->getSimulationObjects<PheromoneMap>()){
if(pm->getType()==dropType){
pm->createBlob(owner_->getPos(), 2, 100);
return;
}
}
dropType = PheromoneMap::Type::None;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/environment.h>
#include <fnordmetric/adminui.h>
#include <fnord/base/uri.h>
namespace fnordmetric {
std::unique_ptr<http::HTTPHandler> AdminUI::getHandler() {
return std::unique_ptr<http::HTTPHandler>(new AdminUI());
}
AdminUI::AdminUI() :
webui_bundle_("FnordMetric"),
webui_mount_(&webui_bundle_, "/admin") {
webui_bundle_.addComponent("fnord/3rdparty/codemirror.js");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css");
webui_bundle_.addComponent("fnord/3rdparty/reset.css");
webui_bundle_.addComponent("fnord/components/fn-table.css");
webui_bundle_.addComponent("fnord/components/fn-button.css");
webui_bundle_.addComponent("fnord/components/fn-modal.css");
webui_bundle_.addComponent("fnord/components/fn-tabbar.css");
webui_bundle_.addComponent("fnord/components/fn-message.css");
webui_bundle_.addComponent("fnord/themes/midnight-blue.css");
webui_bundle_.addComponent("fnord/fnord.js");
webui_bundle_.addComponent("fnord/components/fn-appbar.html");
webui_bundle_.addComponent("fnord/components/fn-button.html");
webui_bundle_.addComponent("fnord/components/fn-button-group.html");
webui_bundle_.addComponent("fnord/components/fn-icon.html");
webui_bundle_.addComponent("fnord/components/fn-input.html");
webui_bundle_.addComponent("fnord/components/fn-loader.html");
webui_bundle_.addComponent("fnord/components/fn-menu.html");
webui_bundle_.addComponent("fnord/components/fn-search.html");
webui_bundle_.addComponent("fnord/components/fn-table.html");
webui_bundle_.addComponent("fnord/components/fn-splitpane.html");
webui_bundle_.addComponent("fnord/components/fn-codeeditor.html");
webui_bundle_.addComponent("fnord/components/fn-dropdown.html");
webui_bundle_.addComponent("fnord/components/fn-datepicker.html");
webui_bundle_.addComponent("fnord/components/fn-timeinput.html");
webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html");
webui_bundle_.addComponent("fnord/components/fn-tabbar.html");
webui_bundle_.addComponent("fnord/components/fn-modal.html");
webui_bundle_.addComponent("fnord/components/fn-pager.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-list.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-search.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-preview.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-controls.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-time-controls.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js");
webui_bundle_.addComponent(
"fnordmetric/fnordmetric-embed-query-popup.html");
webui_bundle_.addComponent(
"fnordmetric-plugins/hosts/fnordmetric-plugin-hosts.html");
}
bool AdminUI::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
if (env()->verbose()) {
fnord::util::LogEntry log_entry;
log_entry.append("__severity__", "DEBUG");
log_entry.printf(
"__message__",
"HTTP request: %s %s",
request->getMethod().c_str(),
request->getUrl().c_str());
env()->logger()->log(log_entry);
}
if (webui_mount_.handleHTTPRequest(request, response)) {
return true;
}
fnord::URI uri(request->getUrl());
auto path = uri.path();
if (path == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addHeader("Location", "/admin");
return true;
}
return false;
}
}
<commit_msg>added tooltip for query editor buttons<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnordmetric/environment.h>
#include <fnordmetric/adminui.h>
#include <fnord/base/uri.h>
namespace fnordmetric {
std::unique_ptr<http::HTTPHandler> AdminUI::getHandler() {
return std::unique_ptr<http::HTTPHandler>(new AdminUI());
}
AdminUI::AdminUI() :
webui_bundle_("FnordMetric"),
webui_mount_(&webui_bundle_, "/admin") {
webui_bundle_.addComponent("fnord/3rdparty/codemirror.js");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.woff");
webui_bundle_.addComponent("fnord/3rdparty/fontawesome.css");
webui_bundle_.addComponent("fnord/3rdparty/reset.css");
webui_bundle_.addComponent("fnord/components/fn-table.css");
webui_bundle_.addComponent("fnord/components/fn-button.css");
webui_bundle_.addComponent("fnord/components/fn-modal.css");
webui_bundle_.addComponent("fnord/components/fn-tabbar.css");
webui_bundle_.addComponent("fnord/components/fn-message.css");
webui_bundle_.addComponent("fnord/components/fn-tooltip.css");
webui_bundle_.addComponent("fnord/themes/midnight-blue.css");
webui_bundle_.addComponent("fnord/fnord.js");
webui_bundle_.addComponent("fnord/components/fn-appbar.html");
webui_bundle_.addComponent("fnord/components/fn-button.html");
webui_bundle_.addComponent("fnord/components/fn-button-group.html");
webui_bundle_.addComponent("fnord/components/fn-icon.html");
webui_bundle_.addComponent("fnord/components/fn-input.html");
webui_bundle_.addComponent("fnord/components/fn-loader.html");
webui_bundle_.addComponent("fnord/components/fn-menu.html");
webui_bundle_.addComponent("fnord/components/fn-search.html");
webui_bundle_.addComponent("fnord/components/fn-table.html");
webui_bundle_.addComponent("fnord/components/fn-splitpane.html");
webui_bundle_.addComponent("fnord/components/fn-codeeditor.html");
webui_bundle_.addComponent("fnord/components/fn-dropdown.html");
webui_bundle_.addComponent("fnord/components/fn-datepicker.html");
webui_bundle_.addComponent("fnord/components/fn-timeinput.html");
webui_bundle_.addComponent("fnord/components/fn-daterangepicker.html");
webui_bundle_.addComponent("fnord/components/fn-tabbar.html");
webui_bundle_.addComponent("fnord/components/fn-modal.html");
webui_bundle_.addComponent("fnord/components/fn-pager.html");
webui_bundle_.addComponent("fnord/components/fn-tooltip.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-app.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-console.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-list.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-search.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-query-editor.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-metric-preview.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-controls.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-time-controls.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.html");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui.css");
webui_bundle_.addComponent("fnordmetric/fnordmetric-webui-util.js");
webui_bundle_.addComponent(
"fnordmetric/fnordmetric-embed-query-popup.html");
webui_bundle_.addComponent(
"fnordmetric-plugins/hosts/fnordmetric-plugin-hosts.html");
}
bool AdminUI::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
if (env()->verbose()) {
fnord::util::LogEntry log_entry;
log_entry.append("__severity__", "DEBUG");
log_entry.printf(
"__message__",
"HTTP request: %s %s",
request->getMethod().c_str(),
request->getUrl().c_str());
env()->logger()->log(log_entry);
}
if (webui_mount_.handleHTTPRequest(request, response)) {
return true;
}
fnord::URI uri(request->getUrl());
auto path = uri.path();
if (path == "/") {
response->setStatus(http::kStatusFound);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addHeader("Location", "/admin");
return true;
}
return false;
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.