<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPostgreSQLQuery.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 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkPostgreSQLQuery.h"

#include "vtkObjectFactory.h"
#include "vtkPostgreSQLDatabase.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkPostgreSQLDatabasePrivate.h"

#include <assert.h>

#include <vtksys/ios/sstream>

#define BEGIN_TRANSACTION "BEGIN TRANSACTION"
#define COMMIT_TRANSACTION "COMMIT"
#define ROLLBACK_TRANSACTION "ROLLBACK"

vtkCxxRevisionMacro(vtkPostgreSQLQuery, "1.8");
vtkStandardNewMacro(vtkPostgreSQLQuery);

class vtkPostgreSQLQueryPrivate : public vtkObject
{
public:
  static vtkPostgreSQLQueryPrivate* New();
  static vtkPostgreSQLQueryPrivate* NewForDatabase( vtkPostgreSQLDatabase* db )
    {
    vtkPostgreSQLQueryPrivate* p = vtkPostgreSQLQueryPrivate::New();
    p->SetDatabase( db );
    return p;
    }
  vtkTypeRevisionMacro(vtkPostgreSQLQueryPrivate,vtkObject);
  vtkPostgreSQLQueryPrivate()
    { // For StandardNewMacro. Do not use the default constructor!
    this->Database = 0;
    this->LastErrorText = 0;
    }
  vtkPostgreSQLQueryPrivate( vtkPostgreSQLDatabase* db )
    {
    this->Database = 0;
    this->LastErrorText = 0;

    assert( db );
    this->SetDatabase( db );
    }
  ~vtkPostgreSQLQueryPrivate()
    {
    this->SetDatabase( 0 );
    this->SetLastErrorText( 0 );
    }
  bool Execute( bool& active, const char* query )
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      bool err = true;
      if ( this->Database )
        { // Perhaps the connection parameters were modified since the last open?
        err = this->Database->Open() ? false : true;
        }
      if ( err )
        {
        vtkErrorMacro( "Need a valid database connection to execute query \"" << query << "\"" );
        return false;
        }
      }

    pqxx::transaction<>* work = this->Database->Connection->Work;
    bool localWork = false; // automatically commit when done?
    try
      {
      if ( ! work )
        {
        work = new pqxx::transaction<>( this->Database->Connection->Connection, "LocalWork" );
        localWork = true;
        }
      this->Result = work->exec( query );
      this->NextIterator = this->Result.begin();
      this->Iterator = NextIterator;
      if ( localWork )
        {
        work->commit();
        delete work;
        }
      active = 1;
      }
    catch ( vtkstd::exception& e )
      {
      active = 0;
      this->SetLastErrorText( e.what() );
      return false;
      }
    this->SetLastErrorText( 0 );
    return true;
    }

  bool BeginTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to open a transaction" );
      return false;
      }
    return this->Database->Connection->BeginTransaction();
    }

  bool CommitTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to commit a transaction" );
      return false;
      }
    return this->Database->Connection->CommitTransaction();
    }

  bool RollbackTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to rollback a transaction" );
      return false;
      }
    return this->Database->Connection->RollbackTransaction();
    }

  int GetNumberOfFields()
    {
    return this->Result.columns();
    }

  const char* GetFieldName( int column )
    {
    return this->Result.column_name( column );
    }

  int GetFieldType( int column )
    {
    pqxx::oid ctyp = this->Result.column_type( column );
    return this->Database->Connection->GetVTKTypeFromOID( ctyp );
    }

  bool NextRow()
    {
    this->Iterator = this->NextIterator;
    ++ this->NextIterator;
    return this->Iterator != this->Result.end();
    }

  vtkVariant DataValue( int column )
    {
    int colType = this->GetFieldType( column );
    switch ( colType )
      {
    case VTK_VOID:
      return vtkVariant();
    case VTK_BIT:
        {
        bool val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_CHAR:
    case VTK_SIGNED_CHAR:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( (char)val );
        }
    case VTK_UNSIGNED_CHAR:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( (unsigned char)val );
        }
    case VTK_SHORT:
        {
        short val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_SHORT:
        {
        unsigned short val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_INT:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_INT:
        {
        unsigned int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_LONG:
        {
        long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_LONG:
        {
        unsigned long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
#ifdef VTK_TYPE_USE_LONG_LONG
    case VTK_LONG_LONG:
        {
        long long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_LONG_LONG:
        {
        unsigned long long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
#endif // VTK_TYPE_USE_LONG_LONG
    case VTK_FLOAT:
        {
        float val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_DOUBLE:
        {
        double val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_ID_TYPE:
        {
        vtkIdType val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_STRING:
        {
        vtkstd::string val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
      }
    return vtkVariant();
    }

  vtkSetObjectMacro(Database,vtkPostgreSQLDatabase);
  vtkSetStringMacro(LastErrorText);

  vtkPostgreSQLDatabase* Database;
  pqxx::result Result;
  pqxx::result::const_iterator Iterator;
  pqxx::result::const_iterator NextIterator;
  char* LastErrorText;
};

vtkStandardNewMacro(vtkPostgreSQLQueryPrivate);
vtkCxxRevisionMacro(vtkPostgreSQLQueryPrivate, "1.8");

// ----------------------------------------------------------------------
vtkPostgreSQLQuery::vtkPostgreSQLQuery()
{
  this->Transactor = 0;
}

// ----------------------------------------------------------------------
vtkPostgreSQLQuery::~vtkPostgreSQLQuery()
{
  if ( this->Transactor )
    {
    this->Transactor->Delete();
    }
}

// ----------------------------------------------------------------------
void vtkPostgreSQLQuery::PrintSelf( ostream& os, vtkIndent indent )
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Transactor: ";
  if ( this->Transactor )
    {
    os << this->Transactor << "\n";
    }
  else
    {
    os << "(null)\n";
    }
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::Execute()
{
  if ( this->Query == 0 )
    {
    vtkErrorMacro( "Cannot execute before a query has been set." );
    return false;
    }

  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );
  assert( db );

  if ( this->Transactor && this->Transactor->Database != db )
    {
    this->Active = 0;
    // Delete any transactor not attached to the current database.
    this->Transactor->Delete();
    this->Transactor = 0;
    }

  if ( ! this->Transactor )
    {
    if ( ! db )
      {
      vtkErrorMacro( "No database on which to execute the query." );
      return false;
      }
    this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );
    }

  return this->Transactor->Execute( this->Active, this->Query );
}

// ----------------------------------------------------------------------
int vtkPostgreSQLQuery::GetNumberOfFields()
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return 0;
    }

  return this->Transactor->GetNumberOfFields();
}

// ----------------------------------------------------------------------
const char* vtkPostgreSQLQuery::GetFieldName( int column )
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return 0;
    }
  else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )
    {
    vtkErrorMacro( "Illegal field index " << column );
    return 0;
    }
  return this->Transactor->GetFieldName( column );
}

// ----------------------------------------------------------------------
int vtkPostgreSQLQuery::GetFieldType( int column )
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return -1;
    }
  else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )
    {
    vtkErrorMacro( "Illegal field index " << column );
    return -1;
    }
  return this->Transactor->GetFieldType( column );
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::NextRow()
{
  if ( ! this->IsActive() || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return false;
    }

  return this->Transactor->NextRow();
}

// ----------------------------------------------------------------------
vtkVariant vtkPostgreSQLQuery::DataValue( vtkIdType column )
{
  if ( this->IsActive() == false )
    {
    vtkWarningMacro( "DataValue() called on inactive query" );
    return vtkVariant();
    }
  else if ( column < 0 || column >= this->GetNumberOfFields() )
    {
    vtkWarningMacro( "DataValue() called with out-of-range column index " << column );
    return vtkVariant();
    }

  return this->Transactor->DataValue( column );
}

// ----------------------------------------------------------------------
const char * vtkPostgreSQLQuery::GetLastErrorText()
{
  if ( ! this->Database )
    {
    return "No database";
    }
  if ( ! this->Transactor )
    {
    return "No active query";
    }
  return this->Transactor->LastErrorText;
}

vtkStdString vtkPostgreSQLQuery::EscapeString( vtkStdString s, bool addSurroundingQuotes )
{
  vtkStdString retval;
  if ( addSurroundingQuotes )
    {
    retval = "'";
    }

  vtkPostgreSQLDatabase* db = static_cast<vtkPostgreSQLDatabase*>( this->Database );
  if ( db->Connection )
    {
    if ( db->Connection->Work )
      {
      retval.append( db->Connection->Work->esc( s ) );
      }
    else
      {
      pqxx::transaction<> ework( db->Connection->Connection, "EscapeWork" );
      retval.append( ework.esc( s ) );
      }
    }
  else
    {
    this->Superclass::EscapeString( s, false );
    }

  if ( addSurroundingQuotes )
    {
    retval.append( "'" );
    }
  return retval;
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::HasError()
{
  if ( ! this->Database )
    {
    return false;
    }
  if ( ! this->Transactor )
    {
    return false;
    }
  return ( this->Transactor->LastErrorText != 0 );
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::BeginTransaction()
{
  if ( this->Transactor )
    {
    vtkErrorMacro(<<"Cannot start a transaction.  One is already in progress.");
    return false;
    }

  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );
  assert( db );

  this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );
  if ( ! this->Transactor )
    {
    vtkErrorMacro(<<"Cannot create a new transaction.");
    return false;
    }

  return this->Transactor->BeginTransaction();
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::CommitTransaction()
{
  if ( this->Transactor )
    {
    if ( this->Transactor->CommitTransaction() )
      {
      this->Transactor->Delete();
      this->Transactor = 0;
      this->Active = false;
      return true;
      }
    // don't delete the transactor on failure... we want the error message!
    return false;
    }
  vtkErrorMacro( "Cannot commit.  There is no transaction in progress.");
  return false;
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::RollbackTransaction()
{
  if ( ! this->Transactor )
    {
    vtkErrorMacro("Cannot rollback.  There is no transaction in progress.");
    return false;
    }

  return this->Transactor->RollbackTransaction();
}

// ----------------------------------------------------------------------
void vtkPostgreSQLQuery::SetLastErrorText( const char* msg )
{
  if ( this->Transactor )
    {
    this->Transactor->SetLastErrorText( msg );
    }
}

<commit_msg>BUG: in EscapeString(), append to the return value (and not only calculate)      the string that is calculated by the method of the superclass.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPostgreSQLQuery.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 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkPostgreSQLQuery.h"

#include "vtkObjectFactory.h"
#include "vtkPostgreSQLDatabase.h"
#include "vtkStringArray.h"
#include "vtkVariant.h"
#include "vtkVariantArray.h"
#include "vtkPostgreSQLDatabasePrivate.h"

#include <assert.h>

#include <vtksys/ios/sstream>

#define BEGIN_TRANSACTION "BEGIN TRANSACTION"
#define COMMIT_TRANSACTION "COMMIT"
#define ROLLBACK_TRANSACTION "ROLLBACK"

vtkCxxRevisionMacro(vtkPostgreSQLQuery, "1.9");
vtkStandardNewMacro(vtkPostgreSQLQuery);

class vtkPostgreSQLQueryPrivate : public vtkObject
{
public:
  static vtkPostgreSQLQueryPrivate* New();
  static vtkPostgreSQLQueryPrivate* NewForDatabase( vtkPostgreSQLDatabase* db )
    {
    vtkPostgreSQLQueryPrivate* p = vtkPostgreSQLQueryPrivate::New();
    p->SetDatabase( db );
    return p;
    }
  vtkTypeRevisionMacro(vtkPostgreSQLQueryPrivate,vtkObject);
  vtkPostgreSQLQueryPrivate()
    { // For StandardNewMacro. Do not use the default constructor!
    this->Database = 0;
    this->LastErrorText = 0;
    }
  vtkPostgreSQLQueryPrivate( vtkPostgreSQLDatabase* db )
    {
    this->Database = 0;
    this->LastErrorText = 0;

    assert( db );
    this->SetDatabase( db );
    }
  ~vtkPostgreSQLQueryPrivate()
    {
    this->SetDatabase( 0 );
    this->SetLastErrorText( 0 );
    }
  bool Execute( bool& active, const char* query )
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      bool err = true;
      if ( this->Database )
        { // Perhaps the connection parameters were modified since the last open?
        err = this->Database->Open() ? false : true;
        }
      if ( err )
        {
        vtkErrorMacro( "Need a valid database connection to execute query \"" << query << "\"" );
        return false;
        }
      }

    pqxx::transaction<>* work = this->Database->Connection->Work;
    bool localWork = false; // automatically commit when done?
    try
      {
      if ( ! work )
        {
        work = new pqxx::transaction<>( this->Database->Connection->Connection, "LocalWork" );
        localWork = true;
        }
      this->Result = work->exec( query );
      this->NextIterator = this->Result.begin();
      this->Iterator = NextIterator;
      if ( localWork )
        {
        work->commit();
        delete work;
        }
      active = 1;
      }
    catch ( vtkstd::exception& e )
      {
      active = 0;
      this->SetLastErrorText( e.what() );
      return false;
      }
    this->SetLastErrorText( 0 );
    return true;
    }

  bool BeginTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to open a transaction" );
      return false;
      }
    return this->Database->Connection->BeginTransaction();
    }

  bool CommitTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to commit a transaction" );
      return false;
      }
    return this->Database->Connection->CommitTransaction();
    }

  bool RollbackTransaction()
    {
    if ( ! this->Database || ! this->Database->IsOpen() )
      {
      vtkErrorMacro( "Need a valid database connection to rollback a transaction" );
      return false;
      }
    return this->Database->Connection->RollbackTransaction();
    }

  int GetNumberOfFields()
    {
    return this->Result.columns();
    }

  const char* GetFieldName( int column )
    {
    return this->Result.column_name( column );
    }

  int GetFieldType( int column )
    {
    pqxx::oid ctyp = this->Result.column_type( column );
    return this->Database->Connection->GetVTKTypeFromOID( ctyp );
    }

  bool NextRow()
    {
    this->Iterator = this->NextIterator;
    ++ this->NextIterator;
    return this->Iterator != this->Result.end();
    }

  vtkVariant DataValue( int column )
    {
    int colType = this->GetFieldType( column );
    switch ( colType )
      {
    case VTK_VOID:
      return vtkVariant();
    case VTK_BIT:
        {
        bool val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_CHAR:
    case VTK_SIGNED_CHAR:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( (char)val );
        }
    case VTK_UNSIGNED_CHAR:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( (unsigned char)val );
        }
    case VTK_SHORT:
        {
        short val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_SHORT:
        {
        unsigned short val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_INT:
        {
        int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_INT:
        {
        unsigned int val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_LONG:
        {
        long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_LONG:
        {
        unsigned long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
#ifdef VTK_TYPE_USE_LONG_LONG
    case VTK_LONG_LONG:
        {
        long long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_UNSIGNED_LONG_LONG:
        {
        unsigned long long val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
#endif // VTK_TYPE_USE_LONG_LONG
    case VTK_FLOAT:
        {
        float val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_DOUBLE:
        {
        double val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_ID_TYPE:
        {
        vtkIdType val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
    case VTK_STRING:
        {
        vtkstd::string val;
        if ( ! this->Iterator[column].to( val ) )
          {
          return vtkVariant();
          }
        return vtkVariant( val );
        }
      }
    return vtkVariant();
    }

  vtkSetObjectMacro(Database,vtkPostgreSQLDatabase);
  vtkSetStringMacro(LastErrorText);

  vtkPostgreSQLDatabase* Database;
  pqxx::result Result;
  pqxx::result::const_iterator Iterator;
  pqxx::result::const_iterator NextIterator;
  char* LastErrorText;
};

vtkStandardNewMacro(vtkPostgreSQLQueryPrivate);
vtkCxxRevisionMacro(vtkPostgreSQLQueryPrivate, "1.9");

// ----------------------------------------------------------------------
vtkPostgreSQLQuery::vtkPostgreSQLQuery()
{
  this->Transactor = 0;
}

// ----------------------------------------------------------------------
vtkPostgreSQLQuery::~vtkPostgreSQLQuery()
{
  if ( this->Transactor )
    {
    this->Transactor->Delete();
    }
}

// ----------------------------------------------------------------------
void vtkPostgreSQLQuery::PrintSelf( ostream& os, vtkIndent indent )
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Transactor: ";
  if ( this->Transactor )
    {
    os << this->Transactor << "\n";
    }
  else
    {
    os << "(null)\n";
    }
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::Execute()
{
  if ( this->Query == 0 )
    {
    vtkErrorMacro( "Cannot execute before a query has been set." );
    return false;
    }

  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );
  assert( db );

  if ( this->Transactor && this->Transactor->Database != db )
    {
    this->Active = 0;
    // Delete any transactor not attached to the current database.
    this->Transactor->Delete();
    this->Transactor = 0;
    }

  if ( ! this->Transactor )
    {
    if ( ! db )
      {
      vtkErrorMacro( "No database on which to execute the query." );
      return false;
      }
    this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );
    }

  return this->Transactor->Execute( this->Active, this->Query );
}

// ----------------------------------------------------------------------
int vtkPostgreSQLQuery::GetNumberOfFields()
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return 0;
    }

  return this->Transactor->GetNumberOfFields();
}

// ----------------------------------------------------------------------
const char* vtkPostgreSQLQuery::GetFieldName( int column )
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return 0;
    }
  else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )
    {
    vtkErrorMacro( "Illegal field index " << column );
    return 0;
    }
  return this->Transactor->GetFieldName( column );
}

// ----------------------------------------------------------------------
int vtkPostgreSQLQuery::GetFieldType( int column )
{
  if ( ! this->Active || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return -1;
    }
  else if ( column < 0 || column >= this->Transactor->GetNumberOfFields() )
    {
    vtkErrorMacro( "Illegal field index " << column );
    return -1;
    }
  return this->Transactor->GetFieldType( column );
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::NextRow()
{
  if ( ! this->IsActive() || ! this->Transactor )
    {
    vtkErrorMacro( "Query is not active!" );
    return false;
    }

  return this->Transactor->NextRow();
}

// ----------------------------------------------------------------------
vtkVariant vtkPostgreSQLQuery::DataValue( vtkIdType column )
{
  if ( this->IsActive() == false )
    {
    vtkWarningMacro( "DataValue() called on inactive query" );
    return vtkVariant();
    }
  else if ( column < 0 || column >= this->GetNumberOfFields() )
    {
    vtkWarningMacro( "DataValue() called with out-of-range column index " << column );
    return vtkVariant();
    }

  return this->Transactor->DataValue( column );
}

// ----------------------------------------------------------------------
const char * vtkPostgreSQLQuery::GetLastErrorText()
{
  if ( ! this->Database )
    {
    return "No database";
    }
  if ( ! this->Transactor )
    {
    return "No active query";
    }
  return this->Transactor->LastErrorText;
}

vtkStdString vtkPostgreSQLQuery::EscapeString( vtkStdString s, bool addSurroundingQuotes )
{
  vtkStdString retval;
  if ( addSurroundingQuotes )
    {
    retval = "'";
    }

  vtkPostgreSQLDatabase* db = static_cast<vtkPostgreSQLDatabase*>( this->Database );
  if ( db->Connection )
    {
    if ( db->Connection->Work )
      {
      retval.append( db->Connection->Work->esc( s ) );
      }
    else
      {
      pqxx::transaction<> ework( db->Connection->Connection, "EscapeWork" );
      retval.append( ework.esc( s ) );
      }
    }
  else
    {
    retval.append( this->Superclass::EscapeString( s, false ) );
    }

  if ( addSurroundingQuotes )
    {
    retval.append( "'" );
    }

  return retval;
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::HasError()
{
  if ( ! this->Database )
    {
    return false;
    }
  if ( ! this->Transactor )
    {
    return false;
    }
  return ( this->Transactor->LastErrorText != 0 );
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::BeginTransaction()
{
  if ( this->Transactor )
    {
    vtkErrorMacro(<<"Cannot start a transaction.  One is already in progress.");
    return false;
    }

  vtkPostgreSQLDatabase* db = vtkPostgreSQLDatabase::SafeDownCast( this->Database );
  assert( db );

  this->Transactor = vtkPostgreSQLQueryPrivate::NewForDatabase( db );
  if ( ! this->Transactor )
    {
    vtkErrorMacro(<<"Cannot create a new transaction.");
    return false;
    }

  return this->Transactor->BeginTransaction();
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::CommitTransaction()
{
  if ( this->Transactor )
    {
    if ( this->Transactor->CommitTransaction() )
      {
      this->Transactor->Delete();
      this->Transactor = 0;
      this->Active = false;
      return true;
      }
    // don't delete the transactor on failure... we want the error message!
    return false;
    }
  vtkErrorMacro( "Cannot commit.  There is no transaction in progress.");
  return false;
}

// ----------------------------------------------------------------------
bool vtkPostgreSQLQuery::RollbackTransaction()
{
  if ( ! this->Transactor )
    {
    vtkErrorMacro("Cannot rollback.  There is no transaction in progress.");
    return false;
    }

  return this->Transactor->RollbackTransaction();
}

// ----------------------------------------------------------------------
void vtkPostgreSQLQuery::SetLastErrorText( const char* msg )
{
  if ( this->Transactor )
    {
    this->Transactor->SetLastErrorText( msg );
    }
}

<|endoftext|>


<commit_before>/*
###############################################################################
#
#  EGSnrc gui compile page
#  Copyright (C) 2015 National Research Council Canada
#
#  This file is part of EGSnrc.
#
#  EGSnrc 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, either version 3 of the License, or (at your
#  option) any later version.
#
#  EGSnrc 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 Affero General Public License for
#  more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with EGSnrc. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#
#  Author:          Iwan Kawrakow, 2003
#
#  Contributors:    Ernesto Mainegra-Hing
#
###############################################################################
*/

#include "egs_compile_page.h"

#include <qlayout.h>
#include <qcombobox.h>
#include <qgroupbox.h>
#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qfile.h>
#include <qdir.h>
#include <qstringlist.h>
#include <qtextedit.h>
#include <qmessagebox.h>
//#include <qcstring.h>

#include <cstdlib>

const QSizePolicy ignored(QSizePolicy::Ignored,QSizePolicy::Ignored);
const QSizePolicy preferred(QSizePolicy::Preferred,QSizePolicy::Preferred);

using namespace Qt;

EGS_CompilePage::EGS_CompilePage(QWidget *parent, const char *name,
    WFlags f) : EGS_GUI_Widget(parent,name,f) { make(); }

EGS_CompilePage::EGS_CompilePage(EGS_ConfigReader *cr, QWidget *parent,
    const char *name, WFlags f) : EGS_GUI_Widget(cr,parent,name,f) { make(); }

void EGS_CompilePage::make() {

   // The layout of the compile widget
   QVBoxLayout *topl = new QVBoxLayout(this);
   topl->setSpacing(6); topl->setMargin(11);

   bg_coption = new QButtonGroup(this);
   c_option = new QGroupBox("coption box",this);
   QVBoxLayout *bgl = new QVBoxLayout(c_option);bgl->setSpacing(6); bgl->setMargin(11);
   c_option->setTitle( tr("Target") );

   QRadioButton *rb = new QRadioButton("opt",c_option);
   rb->setChecked(true); bgl->addWidget(rb); the_target = 0;    bg_coption->addButton(rb);
   rb = new QRadioButton("noopt",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   rb = new QRadioButton("debug",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   rb = new QRadioButton("clean",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   //connect(bg_coption,SIGNAL(clicked(int)),this,SLOT(changeTarget(int)));

   QHBoxLayout *hl1 = new QHBoxLayout;
   hl1->addWidget(c_option);

   QVBoxLayout *vl1 = new QVBoxLayout;

   // Fortran options
   QVBoxLayout *gbl = new QVBoxLayout();gbl->setSpacing(6); gbl->setMargin(11);
   QGroupBox *gb = new QGroupBox(this); gb->setTitle( tr("Extra Fortran options") );
   QHBoxLayout *hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );
   extra_f_options = new QLineEdit(gb);
   hbl->addWidget(extra_f_options);
   vl1->addWidget(gb);
   // C Options
   gb = new QGroupBox("Extra C options",this); gb->setTitle( tr("Extra C options") );
   hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );
   extra_c_options = new QLineEdit(gb);
   hbl->addWidget(extra_c_options);

   vl1->addWidget(gb);

   hl1->addLayout(vl1);
   topl->addLayout(hl1,1);

   hl1 = new QHBoxLayout;
   QPushButton *b = new QPushButton("&Go",this);
   connect(b,SIGNAL(clicked()),this,SLOT(startCompilation()));
   hl1->addWidget(b); is_running = false; start_c = b;

   QSpacerItem *spacer = new QSpacerItem(20,20,QSizePolicy::Expanding,
                                          QSizePolicy::Minimum);
   hl1->addItem(spacer);
   //b = new QPushButton("&Cancel",this,"cancel button");
   b = new QPushButton("&Cancel",this);
   connect(b,SIGNAL(clicked()),this,SLOT(stopCompilation()));
   b->setEnabled(false); hl1->addWidget(b); stop_c = b;

   topl->addLayout(hl1,1);

   //c_text = new QTextEdit(this,"compilation output");
   c_text = new QTextEdit(this);
   QFont ctext_font(  c_text->font() );
   ctext_font.setFamily( "Courier [Adobe]" );
   ctext_font.setPointSize( 9 );
   c_text->setFont( ctext_font );

   c_text->setReadOnly(true);
   //c_text->hide(); d_hidden = true;
   topl->addWidget(c_text,100);

   c_process = new QProcess;
   connect(c_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readProcessOut()));
   connect(c_process,SIGNAL(readyReadStandardError()),this,SLOT(readProcessErr()));
   connect(c_process,SIGNAL(finished(int, QProcess::ExitStatus)),
           this,     SLOT(compilationFinished(int, QProcess::ExitStatus)));
}

bool EGS_CompilePage::checkExeDir() {
  QString exe_dir = egsHome() + "bin" + QDir::separator();
  QDir dexe(exe_dir);
  if( !dexe.exists() ) {
#ifdef IK_DEBUG
    qDebug("Creating directory %s",exe_dir.latin1());
#endif
    if( !dexe.mkdir(exe_dir) ) return false;
  }
  exe_dir += myMachine();
  dexe.setPath(exe_dir);
  if( !dexe.exists() ) {
#ifdef IK_DEBUG
    qDebug("Creating directory %s",exe_dir.latin1());
#endif
    if( !dexe.mkdir(exe_dir) ) return false;
  }
  return true;
}

void EGS_CompilePage::startCompilation() {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::startCompilation()\n");
#endif
  if ( !checkVars() ) return;
  start_c->setEnabled(false); stop_c->setEnabled(true);
  c_option->setEnabled(false);

  if( !checkExeDir() )
    qFatal("Failed to create executable directory for %s",myMachine().toLatin1().data());

  QStringList args;
  //c_process->clearArguments();
  //c_process->addArgument(makeProgram());
#ifdef IK_DEBUG
  qDebug("user code: %s",the_user_code.toLatin1().data());
#endif
  QString ucode = the_user_code;
  QString udir = egsHome() + ucode;
  QDir::setCurrent(udir);
#ifdef IK_DEBUG
  qDebug("udir: %s",udir.toLatin1().data());
#endif
  //QButton *b = c_option->selected();
  QAbstractButton *b = bg_coption->checkedButton();//c_option->selected();
  QString bname = b->text();//b->name();
#ifdef IK_DEBUG
  qDebug("selected button: %s",bname.toLatin1().data());
#endif
  if( bname != "opt" ) args << bname;//c_process->addArgument(bname);
  QString conf = "EGS_CONFIG="; conf += egsConfiguration();
  args <<conf; //c_process->addArgument(conf);
  QString ehome = "EGS_HOME="; ehome += egsHome();
  args << ehome; //c_process->addArgument(ehome);
  if( bname != "clean" ) {
    QString fopt = extra_f_options->text();
    if( !fopt.isEmpty() ) {
      //QString aux="FCFLAGS=\"";
      //aux += fFlags() + " " + fopt + "\"";
      QString aux="FCFLAGS=";
      aux += fFlags() + " " + fopt;
      args << aux; //c_process->addArgument(aux);
    }
    QString copt = extra_c_options->text();
    if( !copt.isEmpty() ) {
      QString aux="C_FLAGS=\"";
      aux += cFlags() + " " + copt + "\"";
      args << aux; //c_process->addArgument(aux);
    }
  }
#ifdef IK_DEBUG
  qDebug("Current directory: %s",QDir::currentDirPath().toLatin1().data());
#endif
  //qWarning("Executing: <%s>",args.join(" ").toLatin1().data());
  c_text->setText("");

  //c_process->start();
  c_process->start(makeProgram(),args);
  if(c_process->error()==QProcess::FailedToStart) {
    c_text->insertPlainText(tr("Failed to execute: ")+ makeProgram() + args.join(" ") + tr("!!!"));
  }
  else{
   is_running = true; killed = false;
  }
}

void EGS_CompilePage::stopCompilation() {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::stopCompilation()\n");
#endif
  //c_process->tryTerminate();
  c_process->kill(); killed = true;
}

void EGS_CompilePage::readProcessOut() {
  //QByteArray a = c_process->readStdout();
  QByteArray a = c_process->readAllStandardOutput();
  c_text->insertPlainText(a);//c_text->insert(a); //c_text->append(a);
}

void EGS_CompilePage::readProcessErr() {
  //QByteArray a = c_process->readStderr();
  QByteArray a = c_process->readAllStandardError();
  c_text->insertPlainText(a);//c_text->insert(a); //c_text->append(a);
}

void EGS_CompilePage::setUserCode(const QString &new_user_code) {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::setUserCode: %s",new_user_code.latin1());
#endif
  the_user_code = new_user_code;
}

void EGS_CompilePage::sendSignals() {
  //QButton *b = c_option->selected();
  //QString bname = b->name();
  QAbstractButton *b = bg_coption->checkedButton();
  QString bname = b->text();
  emit targetChanged(bname);
}

void EGS_CompilePage::changeTarget(int id) {
  if( id == the_target ) return;
  the_target = id;
  //QButton *b = c_option->selected(); QString bname = b->name();
  QAbstractButton *b = bg_coption->checkedButton();
  QString bname = b->text();
  emit targetChanged(bname);
}

void EGS_CompilePage::compilationFinished(int exitCode, QProcess::ExitStatus exitStatus) {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::compilationFinished()\n");
#endif
  start_c->setEnabled(true); stop_c->setEnabled(false);
  c_option->setEnabled(true);
  is_running = false;

  QString bname = bg_coption->checkedButton()->text();
  QString exit_code = tr("ExitCode = ")  + QString::number(exitCode);
  c_text->append(exit_code);
  if( bname != QString("clean") ) {
   if (killed)
       c_text->append(
       "\n\n************************* killed *****************************\n\n");
   else{
       if( exitStatus != QProcess::NormalExit)
         c_text->append(
         "\n\n************************* failed *****************************\n\n");
       else
         c_text->append(
         "\n\n************************* finished *****************************\n\n");
   }
  }
}
<commit_msg>Set egs_gui compilation flags properly (#340)<commit_after>/*
###############################################################################
#
#  EGSnrc gui compile page
#  Copyright (C) 2015 National Research Council Canada
#
#  This file is part of EGSnrc.
#
#  EGSnrc 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, either version 3 of the License, or (at your
#  option) any later version.
#
#  EGSnrc 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 Affero General Public License for
#  more details.
#
#  You should have received a copy of the GNU Affero General Public License
#  along with EGSnrc. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#
#  Author:          Iwan Kawrakow, 2003
#
#  Contributors:    Ernesto Mainegra-Hing
#
###############################################################################
*/

#include "egs_compile_page.h"

#include <qlayout.h>
#include <qcombobox.h>
#include <qgroupbox.h>
#include <qbuttongroup.h>
#include <qradiobutton.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qfile.h>
#include <qdir.h>
#include <qstringlist.h>
#include <qtextedit.h>
#include <qmessagebox.h>
//#include <qcstring.h>

#include <cstdlib>

const QSizePolicy ignored(QSizePolicy::Ignored,QSizePolicy::Ignored);
const QSizePolicy preferred(QSizePolicy::Preferred,QSizePolicy::Preferred);

using namespace Qt;

EGS_CompilePage::EGS_CompilePage(QWidget *parent, const char *name,
    WFlags f) : EGS_GUI_Widget(parent,name,f) { make(); }

EGS_CompilePage::EGS_CompilePage(EGS_ConfigReader *cr, QWidget *parent,
    const char *name, WFlags f) : EGS_GUI_Widget(cr,parent,name,f) { make(); }

void EGS_CompilePage::make() {

   // The layout of the compile widget
   QVBoxLayout *topl = new QVBoxLayout(this);
   topl->setSpacing(6); topl->setMargin(11);

   bg_coption = new QButtonGroup(this);
   c_option = new QGroupBox("coption box",this);
   QVBoxLayout *bgl = new QVBoxLayout(c_option);bgl->setSpacing(6); bgl->setMargin(11);
   c_option->setTitle( tr("Target") );

   QRadioButton *rb = new QRadioButton("opt",c_option);
   rb->setChecked(true); bgl->addWidget(rb); the_target = 0;    bg_coption->addButton(rb);
   rb = new QRadioButton("noopt",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   rb = new QRadioButton("debug",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   rb = new QRadioButton("clean",c_option); bgl->addWidget(rb); bg_coption->addButton(rb);
   //connect(bg_coption,SIGNAL(clicked(int)),this,SLOT(changeTarget(int)));

   QHBoxLayout *hl1 = new QHBoxLayout;
   hl1->addWidget(c_option);

   QVBoxLayout *vl1 = new QVBoxLayout;

   // Fortran options
   QVBoxLayout *gbl = new QVBoxLayout();gbl->setSpacing(6); gbl->setMargin(11);
   QGroupBox *gb = new QGroupBox(this); gb->setTitle( tr("Extra Fortran options") );
   QHBoxLayout *hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );
   extra_f_options = new QLineEdit(gb);
   hbl->addWidget(extra_f_options);
   vl1->addWidget(gb);
   // C Options
   gb = new QGroupBox("Extra C options",this); gb->setTitle( tr("Extra C options") );
   hbl = new QHBoxLayout(gb);hbl->setAlignment( Qt::AlignCenter );
   extra_c_options = new QLineEdit(gb);
   hbl->addWidget(extra_c_options);

   vl1->addWidget(gb);

   hl1->addLayout(vl1);
   topl->addLayout(hl1,1);

   hl1 = new QHBoxLayout;
   QPushButton *b = new QPushButton("&Go",this);
   connect(b,SIGNAL(clicked()),this,SLOT(startCompilation()));
   hl1->addWidget(b); is_running = false; start_c = b;

   QSpacerItem *spacer = new QSpacerItem(20,20,QSizePolicy::Expanding,
                                          QSizePolicy::Minimum);
   hl1->addItem(spacer);
   //b = new QPushButton("&Cancel",this,"cancel button");
   b = new QPushButton("&Cancel",this);
   connect(b,SIGNAL(clicked()),this,SLOT(stopCompilation()));
   b->setEnabled(false); hl1->addWidget(b); stop_c = b;

   topl->addLayout(hl1,1);

   //c_text = new QTextEdit(this,"compilation output");
   c_text = new QTextEdit(this);
   QFont ctext_font(  c_text->font() );
   ctext_font.setFamily( "Courier [Adobe]" );
   ctext_font.setPointSize( 9 );
   c_text->setFont( ctext_font );

   c_text->setReadOnly(true);
   //c_text->hide(); d_hidden = true;
   topl->addWidget(c_text,100);

   c_process = new QProcess;
   connect(c_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readProcessOut()));
   connect(c_process,SIGNAL(readyReadStandardError()),this,SLOT(readProcessErr()));
   connect(c_process,SIGNAL(finished(int, QProcess::ExitStatus)),
           this,     SLOT(compilationFinished(int, QProcess::ExitStatus)));
}

bool EGS_CompilePage::checkExeDir() {
  QString exe_dir = egsHome() + "bin" + QDir::separator();
  QDir dexe(exe_dir);
  if( !dexe.exists() ) {
#ifdef IK_DEBUG
    qDebug("Creating directory %s",exe_dir.latin1());
#endif
    if( !dexe.mkdir(exe_dir) ) return false;
  }
  exe_dir += myMachine();
  dexe.setPath(exe_dir);
  if( !dexe.exists() ) {
#ifdef IK_DEBUG
    qDebug("Creating directory %s",exe_dir.latin1());
#endif
    if( !dexe.mkdir(exe_dir) ) return false;
  }
  return true;
}

void EGS_CompilePage::startCompilation() {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::startCompilation()\n");
#endif
  if ( !checkVars() ) return;
  start_c->setEnabled(false); stop_c->setEnabled(true);
  c_option->setEnabled(false);

  if( !checkExeDir() )
    qFatal("Failed to create executable directory for %s",myMachine().toLatin1().data());

  QStringList args;
  //c_process->clearArguments();
  //c_process->addArgument(makeProgram());
#ifdef IK_DEBUG
  qDebug("user code: %s",the_user_code.toLatin1().data());
#endif
  QString ucode = the_user_code;
  QString udir = egsHome() + ucode;
  QDir::setCurrent(udir);
#ifdef IK_DEBUG
  qDebug("udir: %s",udir.toLatin1().data());
#endif
  //QButton *b = c_option->selected();
  QAbstractButton *b = bg_coption->checkedButton();//c_option->selected();
  QString bname = b->text();//b->name();
#ifdef IK_DEBUG
  qDebug("selected button: %s",bname.toLatin1().data());
#endif
  if( bname != "opt" ){
    if( bname == "noopt" )
        args << "FOPT= " << "opt= ";
    else if ( bname == "debug" )
        args << "FOPT=-g" << "opt=-g";
    else
      args << bname;
  }
  QString conf = "EGS_CONFIG="; conf += egsConfiguration();
  args <<conf; //c_process->addArgument(conf);
  QString ehome = "EGS_HOME="; ehome += egsHome();
  args << ehome; //c_process->addArgument(ehome);
  if( bname != "clean" ) {
    QString fopt = extra_f_options->text();
    if( !fopt.isEmpty() ) {
      //QString aux="FCFLAGS=\"";
      //aux += fFlags() + " " + fopt + "\"";
      QString aux="FCFLAGS=";
      aux += fFlags() + " " + fopt;
      args << aux; //c_process->addArgument(aux);
    }
    QString copt = extra_c_options->text();
    if( !copt.isEmpty() ) {
      QString aux="C_FLAGS=\"";
      aux += cFlags() + " " + copt + "\"";
      args << aux; //c_process->addArgument(aux);
    }
  }
#ifdef IK_DEBUG
  qDebug("Current directory: %s",QDir::currentDirPath().toLatin1().data());
#endif
  //qWarning("Executing: <%s>",args.join(" ").toLatin1().data());
  c_text->setText("");

  //c_process->start();
  c_process->start(makeProgram(),args);
  if(c_process->error()==QProcess::FailedToStart) {
    c_text->insertPlainText(tr("Failed to execute: ")+ makeProgram() + args.join(" ") + tr("!!!"));
  }
  else{
   is_running = true; killed = false;
  }
}

void EGS_CompilePage::stopCompilation() {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::stopCompilation()\n");
#endif
  //c_process->tryTerminate();
  c_process->kill(); killed = true;
}

void EGS_CompilePage::readProcessOut() {
  //QByteArray a = c_process->readStdout();
  QByteArray a = c_process->readAllStandardOutput();
  c_text->insertPlainText(a);//c_text->insert(a); //c_text->append(a);
}

void EGS_CompilePage::readProcessErr() {
  //QByteArray a = c_process->readStderr();
  QByteArray a = c_process->readAllStandardError();
  c_text->insertPlainText(a);//c_text->insert(a); //c_text->append(a);
}

void EGS_CompilePage::setUserCode(const QString &new_user_code) {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::setUserCode: %s",new_user_code.latin1());
#endif
  the_user_code = new_user_code;
}

void EGS_CompilePage::sendSignals() {
  //QButton *b = c_option->selected();
  //QString bname = b->name();
  QAbstractButton *b = bg_coption->checkedButton();
  QString bname = b->text();
  emit targetChanged(bname);
}

void EGS_CompilePage::changeTarget(int id) {
  if( id == the_target ) return;
  the_target = id;
  //QButton *b = c_option->selected(); QString bname = b->name();
  QAbstractButton *b = bg_coption->checkedButton();
  QString bname = b->text();
  emit targetChanged(bname);
}

void EGS_CompilePage::compilationFinished(int exitCode, QProcess::ExitStatus exitStatus) {
#ifdef IK_DEBUG
  qDebug("In EGS_CompilePage::compilationFinished()\n");
#endif
  start_c->setEnabled(true); stop_c->setEnabled(false);
  c_option->setEnabled(true);
  is_running = false;

  QString bname = bg_coption->checkedButton()->text();
  QString exit_code = tr("ExitCode = ")  + QString::number(exitCode);
  c_text->append(exit_code);
  if( bname != QString("clean") ) {
   if (killed)
       c_text->append(
       "\n\n************************* killed *****************************\n\n");
   else{
       if( exitStatus != QProcess::NormalExit)
         c_text->append(
         "\n\n************************* failed *****************************\n\n");
       else
         c_text->append(
         "\n\n************************* finished *****************************\n\n");
   }
  }
}
<|endoftext|>


<commit_before>#include <cstdint>
#include "immintrin.h"

#include "/home/christoph/intel/iaca/include/iacaMarks.h"

#if 0
__m512i _mm512_mulhi_epi32(__m512i a, __m512i b) {
  auto a_lo = _mm512_srli_epi64(a, 32);
  auto b_lo = _mm512_srli_epi64(b, 32);
  auto c_lo = _mm512_mul_epi32(a_lo, b_lo);
  auto c_hi = _mm512_mul_epi32(a   , b   );
  return _mm512_mask_blend_epi32(0x5555, c_lo, _mm512_srli_epi64(c_hi, 32));
}
#endif

// constants
constexpr std::size_t m512i_size = sizeof(__m512i);
constexpr std::size_t small_bits = 23;
constexpr std::size_t small_shft =  8;
constexpr std::size_t large_bits = 52;
constexpr std::size_t large_shft = 32;
constexpr std::size_t small_smin = 1 << (small_bits - small_shft);
constexpr std::size_t large_smin = 1 << (large_bits - large_shft);

template<class T>
inline T* _addr(T* base, std::size_t byte_step) {
  return reinterpret_cast<T*>(
    reinterpret_cast<std::uint8_t*>(base) + byte_step
  );
}

std::uint8_t* encode_ans(
  std::uint32_t* coder_iter,  // where the stream starts
  std::uint32_t* coder_last,  // where the stream ends
                              //   note that we encode from the end to the front!
  std::uint8_t*  stream_out   // target to write the stream out to
) {
  // small states, 3 for pipelining
  auto state_sml0 = _mm512_set1_epi32(small_smin);
  auto state_sml1 = _mm512_set1_epi32(small_smin);
  auto state_sml2 = _mm512_set1_epi32(small_smin);
  // large states, 3 for pipelining (might not be worth it)
  //auto state_lrg0 = _mm512_set1_epi64(large_smin);
  //auto state_lrg1 = _mm512_set1_epi64(large_smin);
  //auto state_lrg2 = _mm512_set1_epi64(large_smin);

  // we write from a high adress to a low so we need to
  __m128i stream_buf;
  __m128i shuffle_mk[] = {
    // shuffle masks that move each element left by 1 and clear the low bytes
    _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00),
    _mm_set_epi8(0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF),
    _mm_set_epi8(0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF),
    _mm_set_epi8(0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF)
  };

  while (coder_iter < coder_last) {
    IACA_START
    // load data
    coder_last = _addr(coder_last, -2 * m512i_size);
    auto digit = _mm512_loadu_si512(_addr(coder_last, 0 * m512i_size));
    auto base  = _mm512_loadu_si512(_addr(coder_last, 1 * m512i_size));

    // check if there are small codings
    auto small_mask = _mm512_cmpgt_epi32_mask(_mm512_set1_epi32(32), base);

    // check for overflow
    auto oflow_test = _mm512_mullo_epi32(state_sml0, base);
    auto oflow_mask = _mm512_mask_cmpgt_epi32_mask(small_mask, oflow_test, _mm512_set1_epi32((1 << small_bits) - 1));

    // shift out
    auto state_shft = _mm512_cvtepi32_epi8(_mm512_maskz_compress_epi32(oflow_mask, state_sml0));
    auto oflow_n    = _mm_popcnt_u64(oflow_mask);
    stream_buf      = _mm_shuffle_epi8(stream_buf, _mm_load_si128(shuffle_mk + oflow_n));
    stream_buf      = _mm_or_si128(stream_buf, state_shft);  // @todo if vpermi2b has a low latency then this might be improved
    stream_out     -= oflow_n;
    _mm_storeu_si128(reinterpret_cast<__m128i*>(stream_out), stream_buf);  // partially overrides

    // rescale
    state_sml0 = _mm512_mask_srli_epi32(state_sml0, oflow_mask, state_sml0, small_shft);

    // actual encoding
    state_sml0 = _mm512_mask_mullo_epi32(state_sml0, small_mask, state_sml0, base );
    state_sml0 = _mm512_mask_add_epi32  (state_sml0, small_mask, state_sml0, digit);

    // rotate the states to reduce dependency
    auto tmp   = state_sml0;
    state_sml0 = state_sml1;
    state_sml1 = state_sml2;
    state_sml2 = tmp;

    if (!_mm512_kortestc(small_mask, small_mask)) {
      // @todo Add fallback for large bases
      _mm512_storeu_si512(reinterpret_cast<__m512i*>(stream_out), tmp);  // just to keep the branch
    }
  }
  IACA_END

  // store small states
  _mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_sml0);
  _mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_sml1);
  _mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_sml2);
  stream_out = _addr(stream_out, 3 * m512i_size);

  // store large states
  //_mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_lrg0);
  //_mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_lrg1);
  //_mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_lrg2);
  //stream_out = _addr(stream_out, 3 * m512i_size);

  // return a pointer to the end
  return stream_out;
}

int main() {}
<commit_msg>Improved latency<commit_after>#include <cstdint>
#include "immintrin.h"

#include "/home/christoph/intel/iaca/include/iacaMarks.h"

#if 0
__m512i _mm512_mulhi_epi32(__m512i a, __m512i b) {
  auto a_lo = _mm512_srli_epi64(a, 32);
  auto b_lo = _mm512_srli_epi64(b, 32);
  auto c_lo = _mm512_mul_epi32(a_lo, b_lo);
  auto c_hi = _mm512_mul_epi32(a   , b   );
  return _mm512_mask_blend_epi32(0x5555, c_lo, _mm512_srli_epi64(c_hi, 32));
}
#endif

// constants
constexpr std::size_t m512i_size = sizeof(__m512i);
constexpr std::size_t small_bits = 23;
constexpr std::size_t small_shft =  8;
constexpr std::size_t large_bits = 52;
constexpr std::size_t large_shft = 32;
constexpr std::size_t small_smin = 1 << (small_bits - small_shft);
constexpr std::size_t large_smin = 1 << (large_bits - large_shft);

template<class T>
inline T* _addr(T* base, std::size_t byte_step) {
  return reinterpret_cast<T*>(
    reinterpret_cast<std::uint8_t*>(base) + byte_step
  );
}

std::uint8_t* encode_ans(
  std::uint32_t* coder_iter,  // where the stream starts
  std::uint32_t* coder_last,  // where the stream ends
                              //   note that we encode from the end to the front!
  std::uint8_t*  stream_out   // target to write the stream out to
) {
  // small states, 3 for pipelining
  auto state_sml0 = _mm512_set1_epi32(small_smin);
  auto state_sml1 = _mm512_set1_epi32(small_smin);
  auto state_sml2 = _mm512_set1_epi32(small_smin);
  // large states, 3 for pipelining (might not be worth it)
  //auto state_lrg0 = _mm512_set1_epi64(large_smin);
  //auto state_lrg1 = _mm512_set1_epi64(large_smin);
  //auto state_lrg2 = _mm512_set1_epi64(large_smin);

  // we write from a high adress to a low so we need to
  __m128i stream_buf;
#if 0
  __m128i shuffle_mk[] = {
    // shuffle masks that move each element left by 1 and clear the low bytes
    _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00),
    _mm_set_epi8(0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF),
    _mm_set_epi8(0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF),
    _mm_set_epi8(0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x06,0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x05,0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x04,0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x03,0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x02,0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x01,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF),
    _mm_set_epi8(0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF)
  };
#else
  __m128i shuffle_mk = _mm_set_epi8(0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00);
#endif

  while (coder_iter < coder_last) {
    IACA_START
    // load data
    coder_last = _addr(coder_last, -2 * m512i_size);
    auto digit = _mm512_loadu_si512(_addr(coder_last, 0 * m512i_size));
    auto base  = _mm512_loadu_si512(_addr(coder_last, 1 * m512i_size));

    // check if there are small codings
    auto small_mask = _mm512_cmpgt_epi32_mask(_mm512_set1_epi32(32), base);

    // check for overflow
    auto oflow_test = _mm512_mullo_epi32(state_sml0, base);
    auto oflow_mask = _mm512_mask_cmpgt_epi32_mask(small_mask, oflow_test, _mm512_set1_epi32((1 << small_bits) - 1));

    // shift out
    auto state_shft = _mm512_cvtepi32_epi8(_mm512_maskz_compress_epi32(oflow_mask, state_sml0));
#if 1
    auto oflow_n    = _mm_popcnt_u64(oflow_mask);
    auto oflow_bc   = _mm_broadcastb_epi8(_mm_cvtsi128_si64x(oflow_n));
    stream_buf      = _mm_shuffle_epi8(stream_buf, _mm_sub_si128(shuffle_mk, oflow_bc));
#else
    stream_buf      = _mm_shuffle_epi8(stream_buf, _mm_load_si128(shuffle_mk + oflow_n));
#endif
    stream_buf      = _mm_or_si128(stream_buf, state_shft);  // @todo if vpermi2b has a low latency then this might be improved
    stream_out     -= oflow_n;
    _mm_storeu_si128(reinterpret_cast<__m128i*>(stream_out), stream_buf);  // partially overrides

    // rescale
    state_sml0 = _mm512_mask_srli_epi32(state_sml0, oflow_mask, state_sml0, small_shft);

    // actual encoding
    state_sml0 = _mm512_mask_mullo_epi32(state_sml0, small_mask, state_sml0, base );
    state_sml0 = _mm512_mask_add_epi32  (state_sml0, small_mask, state_sml0, digit);

    // rotate the states to reduce dependency
    auto tmp   = state_sml0;
    state_sml0 = state_sml1;
    state_sml1 = state_sml2;
    state_sml2 = tmp;

    if (!_mm512_kortestc(small_mask, small_mask)) {
      // @todo Add fallback for large bases
      _mm512_storeu_si512(reinterpret_cast<__m512i*>(stream_out), tmp);  // just to keep the branch
    }
  }
  IACA_END

  // store small states
  _mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_sml0);
  _mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_sml1);
  _mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_sml2);
  stream_out = _addr(stream_out, 3 * m512i_size);

  // store large states
  //_mm512_storeu_si512(_addr(stream_out, 0 * m512i_size), state_lrg0);
  //_mm512_storeu_si512(_addr(stream_out, 1 * m512i_size), state_lrg1);
  //_mm512_storeu_si512(_addr(stream_out, 2 * m512i_size), state_lrg2);
  //stream_out = _addr(stream_out, 3 * m512i_size);

  // return a pointer to the end
  return stream_out;
}

int main() {}
<|endoftext|>


<commit_before>/*
* This file is part of `et engine`
* Copyright 2009-2012 by Sergey Reznik
* Please, do not modify contents without approval.
*
*/

#include <fstream>
#include <et/core/tools.h>
#include <et/core/containers.h>
#include <et/locale/locale.h>

using namespace et;

std::string Locale::time()
{
	return std::string();
}

std::string Locale::date()
{
	return std::string();
}

size_t Locale::currentLocale()
{
	std::string mbcs("en_US");
	lowercase(mbcs);

	size_t result = 0;

	if (mbcs.size() > 0)
		result |= mbcs[0];

	if (mbcs.size() > 1)
		result |= mbcs[1] << 8;

	if ((mbcs.size() >= 5) && ((mbcs[2] == '-') || (mbcs[2] == '_')))
		result |= (mbcs[3] << 16) | (mbcs[4] << 24);
	else
		result |= (result & 0xffff) << 16;

	return result;
}
<commit_msg>android locale<commit_after>/*
* This file is part of `et engine`
* Copyright 2009-2012 by Sergey Reznik
* Please, do not modify contents without approval.
*
*/

#include <fstream>
#include <et/core/tools.h>
#include <et/core/containers.h>
#include <et/locale/locale.h>

using namespace et;

std::string locale::time()
{
	return std::string();
}

std::string locale::date()
{
	return std::string();
}

size_t locale::currentLocale()
{
	std::string mbcs("en_US");
	lowercase(mbcs);

	size_t result = 0;

	if (mbcs.size() > 0)
		result |= mbcs[0];

	if (mbcs.size() > 1)
		result |= mbcs[1] << 8;

	if ((mbcs.size() >= 5) && ((mbcs[2] == '-') || (mbcs[2] == '_')))
		result |= (mbcs[3] << 16) | (mbcs[4] << 24);
	else
		result |= (result & 0xffff) << 16;

	return result;
}
<|endoftext|>


<commit_before>#include <StdAfx.h>
#include <Interpret/SmartView/ExtendedFlags.h>
#include <Interpret/Guids.h>
#include <Interpret/InterpretProp.h>
#include <Interpret/ExtraPropTags.h>

namespace smartview
{
	void ExtendedFlags::Parse()
	{
		// Run through the parser once to count the number of flag structs
		for (;;)
		{
			// Must have at least 2 bytes left to have another flag
			if (m_Parser.RemainingBytes() < 2) break;
			(void) m_Parser.Get<BYTE>();
			const auto cbData = m_Parser.Get<BYTE>();
			// Must have at least cbData bytes left to be a valid flag
			if (m_Parser.RemainingBytes() < cbData) break;

			m_Parser.advance(cbData);
			m_ulNumFlags++;
		}

		// Now we parse for real
		m_Parser.rewind();

		if (m_ulNumFlags && m_ulNumFlags < _MaxEntriesSmall)
		{
			auto bBadData = false;

			m_pefExtendedFlags.reserve(m_ulNumFlags);
			for (ULONG i = 0; i < m_ulNumFlags; i++)
			{
				ExtendedFlag extendedFlag;

				extendedFlag.Id = m_Parser.Get<BYTE>();
				extendedFlag.Cb = m_Parser.Get<BYTE>();

				// If the structure says there's more bytes than remaining buffer, we're done parsing.
				if (m_Parser.RemainingBytes() < extendedFlag.Cb)
				{
					m_ulNumFlags = i;
					break;
				}

				switch (extendedFlag.Id)
				{
				case EFPB_FLAGS:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.ExtendedFlags = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				case EFPB_CLSIDID:
					if (extendedFlag.Cb == sizeof(GUID))
						extendedFlag.Data.SearchFolderID = m_Parser.Get<GUID>();
					else
						bBadData = true;
					break;
				case EFPB_SFTAG:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.SearchFolderTag = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				case EFPB_TODO_VERSION:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.ToDoFolderVersion = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				default:
					extendedFlag.lpUnknownData = m_Parser.GetBYTES(extendedFlag.Cb, _MaxBytes);
					break;
				}

				// If we encountered a bad flag, stop parsing
				if (bBadData)
				{
					m_ulNumFlags = i;
					break;
				}

				m_pefExtendedFlags.push_back(extendedFlag);
			}
		}
	}

	void ExtendedFlags::ParseBlocks()
	{
		setRoot(L"Extended Flags:");
		addHeader(L"\r\nNumber of flags = %1!d!", m_ulNumFlags);

		if (m_pefExtendedFlags.size())
		{
			for (const auto& extendedFlag : m_pefExtendedFlags)
			{
				auto szFlags = interpretprop::InterpretFlags(flagExtendedFolderFlagType, extendedFlag.Id);
				addBlock(extendedFlag.Id, L"\r\nId = 0x%1!02X! = %2!ws!", extendedFlag.Id.getData(), szFlags.c_str());
				addBlock(extendedFlag.Cb, L"\r\nCb = 0x%1!02X! = %1!d!", extendedFlag.Cb.getData());

				switch (extendedFlag.Id)
				{
				case EFPB_FLAGS:
					addBlock(
						extendedFlag.Data.ExtendedFlags,
						L"\r\n\tExtended Flags = 0x%1!08X! = %2!ws!",
						extendedFlag.Data.ExtendedFlags.getData(),
						interpretprop::InterpretFlags(flagExtendedFolderFlag, extendedFlag.Data.ExtendedFlags).c_str());
					break;
				case EFPB_CLSIDID:
					addBlock(
						extendedFlag.Data.SearchFolderID,
						L"\r\n\tSearchFolderID = %1!ws!",
						guid::GUIDToString(extendedFlag.Data.SearchFolderID).c_str());
					break;
				case EFPB_SFTAG:
					addBlock(
						extendedFlag.Data.SearchFolderTag,
						L"\r\n\tSearchFolderTag = 0x%1!08X!",
						extendedFlag.Data.SearchFolderTag.getData());
					break;
				case EFPB_TODO_VERSION:
					addBlock(
						extendedFlag.Data.ToDoFolderVersion,
						L"\r\n\tToDoFolderVersion = 0x%1!08X!",
						extendedFlag.Data.ToDoFolderVersion.getData());
					break;
				}

				if (extendedFlag.lpUnknownData.size())
				{
					addBlankLine();
					addHeader(L"\tUnknown Data = ");
					addBlock(extendedFlag.lpUnknownData);
				}
			}
		}
	}
} // namespace smartview<commit_msg>Fix Extended Flags<commit_after>#include <StdAfx.h>
#include <Interpret/SmartView/ExtendedFlags.h>
#include <Interpret/Guids.h>
#include <Interpret/InterpretProp.h>
#include <Interpret/ExtraPropTags.h>

namespace smartview
{
	void ExtendedFlags::Parse()
	{
		// Run through the parser once to count the number of flag structs
		for (;;)
		{
			// Must have at least 2 bytes left to have another flag
			if (m_Parser.RemainingBytes() < 2) break;
			(void) m_Parser.Get<BYTE>();
			const auto cbData = m_Parser.Get<BYTE>();
			// Must have at least cbData bytes left to be a valid flag
			if (m_Parser.RemainingBytes() < cbData) break;

			m_Parser.advance(cbData);
			m_ulNumFlags++;
		}

		// Now we parse for real
		m_Parser.rewind();

		if (m_ulNumFlags && m_ulNumFlags < _MaxEntriesSmall)
		{
			auto bBadData = false;

			m_pefExtendedFlags.reserve(m_ulNumFlags);
			for (ULONG i = 0; i < m_ulNumFlags; i++)
			{
				ExtendedFlag extendedFlag;

				extendedFlag.Id = m_Parser.Get<BYTE>();
				extendedFlag.Cb = m_Parser.Get<BYTE>();

				// If the structure says there's more bytes than remaining buffer, we're done parsing.
				if (m_Parser.RemainingBytes() < extendedFlag.Cb)
				{
					m_pefExtendedFlags.push_back(extendedFlag);
					m_ulNumFlags = i;
					break;
				}

				switch (extendedFlag.Id)
				{
				case EFPB_FLAGS:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.ExtendedFlags = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				case EFPB_CLSIDID:
					if (extendedFlag.Cb == sizeof(GUID))
						extendedFlag.Data.SearchFolderID = m_Parser.Get<GUID>();
					else
						bBadData = true;
					break;
				case EFPB_SFTAG:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.SearchFolderTag = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				case EFPB_TODO_VERSION:
					if (extendedFlag.Cb == sizeof(DWORD))
						extendedFlag.Data.ToDoFolderVersion = m_Parser.Get<DWORD>();
					else
						bBadData = true;
					break;
				default:
					extendedFlag.lpUnknownData = m_Parser.GetBYTES(extendedFlag.Cb, _MaxBytes);
					break;
				}

				// If we encountered a bad flag, stop parsing
				if (bBadData)
				{
					m_pefExtendedFlags.push_back(extendedFlag);
					m_ulNumFlags = i;
					break;
				}

				m_pefExtendedFlags.push_back(extendedFlag);
			}
		}
	}

	void ExtendedFlags::ParseBlocks()
	{
		setRoot(L"Extended Flags:");
		addHeader(L"\r\nNumber of flags = %1!d!", m_ulNumFlags);

		if (m_pefExtendedFlags.size())
		{
			for (const auto& extendedFlag : m_pefExtendedFlags)
			{
				auto szFlags = interpretprop::InterpretFlags(flagExtendedFolderFlagType, extendedFlag.Id);
				addBlock(extendedFlag.Id, L"\r\nId = 0x%1!02X! = %2!ws!", extendedFlag.Id.getData(), szFlags.c_str());
				addBlock(extendedFlag.Cb, L"\r\nCb = 0x%1!02X! = %1!d!", extendedFlag.Cb.getData());

				switch (extendedFlag.Id)
				{
				case EFPB_FLAGS:
					addBlock(
						extendedFlag.Data.ExtendedFlags,
						L"\r\n\tExtended Flags = 0x%1!08X! = %2!ws!",
						extendedFlag.Data.ExtendedFlags.getData(),
						interpretprop::InterpretFlags(flagExtendedFolderFlag, extendedFlag.Data.ExtendedFlags).c_str());
					break;
				case EFPB_CLSIDID:
					addBlock(
						extendedFlag.Data.SearchFolderID,
						L"\r\n\tSearchFolderID = %1!ws!",
						guid::GUIDToString(extendedFlag.Data.SearchFolderID).c_str());
					break;
				case EFPB_SFTAG:
					addBlock(
						extendedFlag.Data.SearchFolderTag,
						L"\r\n\tSearchFolderTag = 0x%1!08X!",
						extendedFlag.Data.SearchFolderTag.getData());
					break;
				case EFPB_TODO_VERSION:
					addBlock(
						extendedFlag.Data.ToDoFolderVersion,
						L"\r\n\tToDoFolderVersion = 0x%1!08X!",
						extendedFlag.Data.ToDoFolderVersion.getData());
					break;
				}

				if (extendedFlag.lpUnknownData.size())
				{
					addBlankLine();
					addHeader(L"\tUnknown Data = ");
					addBlock(extendedFlag.lpUnknownData);
				}
			}
		}
	}
} // namespace smartview<|endoftext|>


<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2007
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: RepeatGuard.cpp,v 1.2 2007/03/02 13:45:29 nbarriga Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* nbarriga  2007-02-20  created
*/

#include "vltPort.h"

static char *rcsId="@(#) $Id: RepeatGuard.cpp,v 1.2 2007/03/02 13:45:29 nbarriga Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include "RepeatGuard.h"

RepeatGuard::RepeatGuard(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){
        method=or_or_and;
        if(interval==0)method=COUNTER;
        if(maxRepetitions==0)method=TIMER;

	this->maxRepetitions=maxRepetitions;
	this->interval=interval*10000000;
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}

RepeatGuard::~RepeatGuard(){

}

bool RepeatGuard::check(){
        switch(method){
                case AND:
                        if(lastTime+interval<=getTimeStamp()&&counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case OR:
                        if(lastTime+interval<=getTimeStamp()||counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case TIMER:
                        if(lastTime+interval<=getTimeStamp()){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case COUNTER:
                        if(counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
        }
}

bool RepeatGuard::checkAndIncrement(){

        counter++;
        return check();
}

void RepeatGuard::increment(){
	counter++;
}

unsigned int RepeatGuard::count(){
	return counterAtLastCheck;
}

void RepeatGuard::reset(){
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}

void RepeatGuard::reset(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){
        method=OR;
        if(interval==0)method=COUNTER;
        if(maxRepetitions==0)method=TIMER;

	this->maxRepetitions=maxRepetitions;
	this->interval=interval*10000000;
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}
/*___oOo___*/
<commit_msg>Removed a warning in check(). It returns false if no case in the switch is selected. In practice, this cannot happen anyway, but the compiler was complaining because it was detecting a method without value for the return.<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2007
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: RepeatGuard.cpp,v 1.3 2007/03/22 10:55:29 gchiozzi Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* nbarriga  2007-02-20  created
*/

#include "vltPort.h"

static char *rcsId="@(#) $Id: RepeatGuard.cpp,v 1.3 2007/03/22 10:55:29 gchiozzi Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include "RepeatGuard.h"

RepeatGuard::RepeatGuard(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){
        method=or_or_and;
        if(interval==0)method=COUNTER;
        if(maxRepetitions==0)method=TIMER;

	this->maxRepetitions=maxRepetitions;
	this->interval=interval*10000000;
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}

RepeatGuard::~RepeatGuard(){

}

bool RepeatGuard::check(){
        switch(method){
                case AND:
                        if(lastTime+interval<=getTimeStamp()&&counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case OR:
                        if(lastTime+interval<=getTimeStamp()||counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case TIMER:
                        if(lastTime+interval<=getTimeStamp()){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
                case COUNTER:
                        if(counter>=maxRepetitions){
                                counterAtLastCheck=counter;
                                counter=0;
                                lastTime=getTimeStamp();
                                return true;
                        }
                        return false;
                        break;
        }
	return false;
}

bool RepeatGuard::checkAndIncrement(){

        counter++;
        return check();
}

void RepeatGuard::increment(){
	counter++;
}

unsigned int RepeatGuard::count(){
	return counterAtLastCheck;
}

void RepeatGuard::reset(){
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}

void RepeatGuard::reset(unsigned int interval, unsigned int maxRepetitions, bool or_or_and){
        method=OR;
        if(interval==0)method=COUNTER;
        if(maxRepetitions==0)method=TIMER;

	this->maxRepetitions=maxRepetitions;
	this->interval=interval*10000000;
	counter=0;
	counterAtLastCheck=0;
	lastTime=0;
}
/*___oOo___*/
<|endoftext|>


<commit_before>#include <kprint>
#include <info>
#include <service>
#include <smp>
#include <boot/multiboot.h>
#include <kernel/os.hpp>

extern "C" {
#include <solo5.h>
}

extern void __platform_init();
extern void default_stdout_handlers();

char cmdline[256];
uintptr_t mem_size;

extern "C" {
  void __init_sanity_checks();
  void kernel_sanity_checks();
  uintptr_t _move_symbols(uintptr_t loc);
  void _init_bss();
  void _init_heap(uintptr_t);
  void _init_c_runtime();
  void _init_syscalls();
  void __libc_init_array();
  uintptr_t _end;
  void set_stack();
  void* get_cpu_ebp();

  // Set to NULL. There are no interrupts in ukvm
  void (*current_eoi_mechanism)();
  void (*current_intr_handler)();
  void (*cpu_sampling_irq_handler)();

  void kernel_start()
  {

    // generate checksums of read-only areas etc.
    __init_sanity_checks();

    // Determine where free memory starts
    uintptr_t free_mem_begin = reinterpret_cast<uintptr_t>(&_end);

    // Preserve symbols from the ELF binary
    free_mem_begin += _move_symbols(free_mem_begin);

    // Do not zero out all solo5 global variables!! == don't touch the BSS
    //_init_bss();

    // Initialize heap
    // XXX: this is dangerous as solo5 might be doing malloc()'s using it's own
    // idea of a heap. Luckily there is no malloc instance at solo5/kernel/[ukvm|virtio|muen],
    // so might be OK (for now).
    _init_heap(free_mem_begin);

    //Initialize stack-unwinder, call global constructors etc.
    _init_c_runtime();

    // Initialize system calls
    _init_syscalls();

    //Initialize stdout handlers
    default_stdout_handlers();

    // Call global ctors
    __libc_init_array();

    // interrupts.asm uses these symbols. This is just to make the compiler happy.
    // These won't ever be called.
    current_eoi_mechanism = NULL;
    current_intr_handler  = NULL;
    cpu_sampling_irq_handler = NULL;

    // Initialize OS including devices
    OS::start(cmdline, mem_size);

    // Starting event loop from here allows us to profile OS::start
    OS::event_loop();
  }

  int solo5_app_main(char *_cmdline)
  {
     // cmdline is stored at 0x6000 by ukvm which is used by includeos. Move it fast.
     strncpy(cmdline, _cmdline, 256);

     // solo5 sets the stack to be at the end of memory, so let's use that as
     // our memory size (before we change).
     mem_size = (uintptr_t)get_cpu_ebp();

     // set the stack location to its new includeos location, and call kernel_start
     set_stack();
  }
}
<commit_msg>solo5: Update kernel_start stubs needed for linking<commit_after>#include <kprint>
#include <info>
#include <service>
#include <smp>
#include <boot/multiboot.h>
#include <kernel/os.hpp>

extern "C" {
#include <solo5.h>
}

extern void __platform_init();
extern void default_stdout_handlers();
void __arch_subscribe_irq(unsigned char) {} // for now

char cmdline[256];
uintptr_t mem_size;

extern "C" {
  void __init_sanity_checks();
  void kernel_sanity_checks();
  uintptr_t _move_symbols(uintptr_t loc);
  void _init_bss();
  void _init_heap(uintptr_t);
  void _init_c_runtime();
  void _init_syscalls();
  void __libc_init_array();
  uintptr_t _end;
  void set_stack();
  void* get_cpu_ebp();

  void kernel_start()
  {

    // generate checksums of read-only areas etc.
    __init_sanity_checks();

    // Determine where free memory starts
    uintptr_t free_mem_begin = reinterpret_cast<uintptr_t>(&_end);

    // Preserve symbols from the ELF binary
    free_mem_begin += _move_symbols(free_mem_begin);

    // Do not zero out all solo5 global variables!! == don't touch the BSS
    //_init_bss();

    // Initialize heap
    // XXX: this is dangerous as solo5 might be doing malloc()'s using it's own
    // idea of a heap. Luckily there is no malloc instance at solo5/kernel/[ukvm|virtio|muen],
    // so might be OK (for now).
    _init_heap(free_mem_begin);

    //Initialize stack-unwinder, call global constructors etc.
    _init_c_runtime();

    // Initialize system calls
    _init_syscalls();

    //Initialize stdout handlers
    default_stdout_handlers();

    // Call global ctors
    __libc_init_array();

    // Initialize OS including devices
    OS::start(cmdline, mem_size);

    // Starting event loop from here allows us to profile OS::start
    OS::event_loop();
  }

  int solo5_app_main(char *_cmdline)
  {
     // cmdline is stored at 0x6000 by ukvm which is used by includeos. Move it fast.
     strncpy(cmdline, _cmdline, 256);

     // solo5 sets the stack to be at the end of memory, so let's use that as
     // our memory size (before we change).
     mem_size = (uintptr_t)get_cpu_ebp();

     // set the stack location to its new includeos location, and call kernel_start
     set_stack();
     return 0;
  }
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskExecutor.cpp
 */

#include "JPetTaskExecutor.h"
#include <cassert>
#include <stdlib.h>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"

JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
  fProcessedFile(processedFileId),
  ftaskGeneratorChain(taskGeneratorChain),
  fOptions(opt)
{
  if (fOptions.isLocalDB()) {
    fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
  } else {
    fParamManager = new JPetParamManager();
  }
  if (taskGeneratorChain) {
    for (auto taskGenerator : *ftaskGeneratorChain) {
      auto task = taskGenerator();
      task->setParamManager(fParamManager); // maybe that should not be here
      fTasks.push_back(task);
    }
  } else {
    ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
  }
}

bool JPetTaskExecutor::process()
{
  if(!processFromCmdLineArgs(fProcessedFile)) {
    ERROR("Error in processFromCmdLineArgs");
    return false;
  }
  for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
    JPetOptions::Options currOpts = fOptions.getOptions();
    if (currentTask != fTasks.begin()) {
    /// Ignore the event range options for all but the first task.
      currOpts = JPetOptions::resetEventRange(currOpts);
   /// For all but the first task,
   /// the input path must be changed if
   /// the output path argument -o was given, because the input
   /// data for them will lay in the location defined by -o.
      auto outPath  = currOpts.at("outputPath");
      if (!outPath.empty()) {
        currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
      }
    }

    INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
    (*currentTask)->init(currOpts);
    (*currentTask)->exec();
    (*currentTask)->terminate();
    INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
  }
  return true;
}

void* JPetTaskExecutor::processProxy(void* runner)
{
  assert(runner);
  static_cast<JPetTaskExecutor*>(runner)->process();
  return 0;
}

TThread* JPetTaskExecutor::run()
{
  TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);
  assert(thread);
  thread->Run();
  return thread;
}

bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
  auto runNum = fOptions.getRunNumber();
  if (runNum >= 0) {
    try {
      fParamManager->fillParameterBank(runNum);
    } catch (...) {
      ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
      return false;
    }
    if (fOptions.isLocalDBCreate()) {
      JPetParamSaverAscii saver;
      saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
    }
  }

  auto inputFileType = fOptions.getInputFileType();
  auto inputFile = fOptions.getInputFile();
  if (inputFileType == JPetOptions::kScope) {
    createScopeTaskAndAddToTaskList();
  } else if (inputFileType == JPetOptions::kHld) {
    long long nevents = fOptions.getTotalEvents();
    if (nevents > 0) {
      fUnpacker.setParams(fOptions.getInputFile(), nevents);
      WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
    } else {
      fUnpacker.setParams(fOptions.getInputFile());
    }
    unpackFile();
  }
  else if( inputFileType == JPetOptions::kZip){
    INFO( std::string("Unzipping file before unpacking") );
    unzipFile();

  }

  if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
    ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );

  return true;
}

void JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
  JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
  assert(module);
  module->setParamManager(fParamManager);
  auto scopeFile = fOptions.getScopeConfigFile();
  if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
    ERROR("Unable to generate Param Bank from Scope Config");
  }
  fTasks.push_front(module);
}

void JPetTaskExecutor::unpackFile()
{
  if (fOptions.getInputFileType() == JPetOptions::kHld) {
    fUnpacker.exec();
  } else {
    WARNING("Input file is not hld and unpacker was supposed to be called!");
  }
}

void JPetTaskExecutor::unzipFile()
{

  if( (fOptions.getInputFileType() == JPetOptions::kZip) ) {
    system(Form("gzip -d %s", fOptions.getInputFile() ) );

  }
  else {
    WARNING("Input file is not zip and cannot be unzipped");
  }
}

JPetTaskExecutor::~JPetTaskExecutor()
{
  for (auto & task : fTasks) {
    if (task) {
      delete task;
      task = 0;
    }
  }
}
<commit_msg>Added unzipping, after the unzipping unpacking is done automatically<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskExecutor.cpp
 */

#include "JPetTaskExecutor.h"
#include <cassert>
#include <stdlib.h>
#include "../JPetTaskInterface/JPetTaskInterface.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetTaskLoader/JPetTaskLoader.h"
#include "../JPetParamGetterAscii/JPetParamGetterAscii.h"
#include "../JPetParamGetterAscii/JPetParamSaverAscii.h"
#include "../JPetLoggerInclude.h"

JPetTaskExecutor::JPetTaskExecutor(TaskGeneratorChain* taskGeneratorChain, int processedFileId, JPetOptions opt) :
  fProcessedFile(processedFileId),
  ftaskGeneratorChain(taskGeneratorChain),
  fOptions(opt)
{
  if (fOptions.isLocalDB()) {
    fParamManager = new JPetParamManager(new JPetParamGetterAscii(fOptions.getLocalDB()));
  } else {
    fParamManager = new JPetParamManager();
  }
  if (taskGeneratorChain) {
    for (auto taskGenerator : *ftaskGeneratorChain) {
      auto task = taskGenerator();
      task->setParamManager(fParamManager); // maybe that should not be here
      fTasks.push_back(task);
    }
  } else {
    ERROR("taskGeneratorChain is null while constructing JPetTaskExecutor");
  }
}

bool JPetTaskExecutor::process()
{
  if(!processFromCmdLineArgs(fProcessedFile)) {
    ERROR("Error in processFromCmdLineArgs");
    return false;
  }
  for (auto currentTask = fTasks.begin(); currentTask != fTasks.end(); currentTask++) {
    JPetOptions::Options currOpts = fOptions.getOptions();
    if (currentTask != fTasks.begin()) {
    /// Ignore the event range options for all but the first task.
      currOpts = JPetOptions::resetEventRange(currOpts);
   /// For all but the first task,
   /// the input path must be changed if
   /// the output path argument -o was given, because the input
   /// data for them will lay in the location defined by -o.
      auto outPath  = currOpts.at("outputPath");
      if (!outPath.empty()) {
        currOpts.at("inputFile") = outPath + JPetCommonTools::extractPathFromFile(currOpts.at("inputFile")) + JPetCommonTools::extractFileNameFromFullPath(currOpts.at("inputFile"));
      }
    }

    INFO(Form("Starting task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
    (*currentTask)->init(currOpts);
    (*currentTask)->exec();
    (*currentTask)->terminate();
    INFO(Form("Finished task: %s", dynamic_cast<JPetTaskLoader*>(*currentTask)->getSubTask()->GetName()));
  }
  return true;
}

void* JPetTaskExecutor::processProxy(void* runner)
{
  assert(runner);
  static_cast<JPetTaskExecutor*>(runner)->process();
  return 0;
}

TThread* JPetTaskExecutor::run()
{
  TThread* thread = new TThread(to_string(fProcessedFile).c_str(), processProxy, (void*)this);
  assert(thread);
  thread->Run();
  return thread;
}

bool JPetTaskExecutor::processFromCmdLineArgs(int)
{
  auto runNum = fOptions.getRunNumber();
  if (runNum >= 0) {
    try {
      fParamManager->fillParameterBank(runNum);
    } catch (...) {
      ERROR("Param bank was not generated correctly.\n The run number used:" + JPetCommonTools::intToString(runNum));
      return false;
    }
    if (fOptions.isLocalDBCreate()) {
      JPetParamSaverAscii saver;
      saver.saveParamBank(fParamManager->getParamBank(), runNum, fOptions.getLocalDBCreate());
    }
  }

  auto inputFileType = fOptions.getInputFileType();
  auto inputFile = fOptions.getInputFile();
  if (inputFileType == JPetOptions::kScope) {
    createScopeTaskAndAddToTaskList();
  } else if (inputFileType == JPetOptions::kHld) {
    long long nevents = fOptions.getTotalEvents();
    if (nevents > 0) {
      fUnpacker.setParams(fOptions.getInputFile(), nevents);
      WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
    } else {
      fUnpacker.setParams(fOptions.getInputFile());
    }
    unpackFile();
  }
  else if( inputFileType == JPetOptions::kZip){
    INFO( std::string("Unzipping file before unpacking") );
    unzipFile();
    //Changing file name to proper one after unzipping
    std::string  sInputFile = inputFile;
    sInputFile = sInputFile.substr(0, sInputFile.find(".gz"));

    inputFile = sInputFile.c_str();
    // copied from above, since one cannot
    long long nevents = fOptions.getTotalEvents();
    if (nevents > 0) {
      fUnpacker.setParams( inputFile, nevents);
      WARNING(std::string("Even though the range of events was set, only the first ") + JPetCommonTools::intToString(nevents) + std::string(" will be unpacked by the unpacker. \n The unpacker always starts from the beginning of the file."));
    } else {
      fUnpacker.setParams(inputFile);
    }
    fUnpacker.exec();
  }

  if(fOptions.getInputFileType() == JPetOptions::kUndefinedFileType)
    ERROR( Form("Unknown file type provided for file: %s", fOptions.getInputFile()) );

  return true;
}

void JPetTaskExecutor::createScopeTaskAndAddToTaskList()
{
  JPetScopeLoader* module = new JPetScopeLoader(new JPetScopeTask("JPetScopeReader", "Process Oscilloscope ASCII data into JPetRecoSignal structures."));
  assert(module);
  module->setParamManager(fParamManager);
  auto scopeFile = fOptions.getScopeConfigFile();
  if (!fParamManager->getParametersFromScopeConfig(scopeFile)) {
    ERROR("Unable to generate Param Bank from Scope Config");
  }
  fTasks.push_front(module);
}

void JPetTaskExecutor::unpackFile()
{
  if (fOptions.getInputFileType() == JPetOptions::kHld) {
    fUnpacker.exec();
  } else {
    WARNING("Input file is not hld and unpacker was supposed to be called!");
  }
}

void JPetTaskExecutor::unzipFile()
{
  if( (fOptions.getInputFileType() == JPetOptions::kZip) ) {
    system(Form("gzip -d %s", fOptions.getInputFile() ) );
  }
  else {
    WARNING("Input file is not zip and cannot be unzipped");
  }
}

JPetTaskExecutor::~JPetTaskExecutor()
{
  for (auto & task : fTasks) {
    if (task) {
      delete task;
      task = 0;
    }
  }
}
<|endoftext|>


<commit_before>#include "carbon_user.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

// Suggested DVFS domain configuration:
// <1.0, CORE, L1_ICACHE, L1_DCACHE> <1.0, L2_CACHE, DIRECTORY> <1.0, NETWORK_MEMORY, NETWORK_USER>

void doMemoryWork()
{
   //int ARRAY_SIZE = 8192*64;
   int ARRAY_SIZE = 512*64;
   int NUM_ITERATIONS = 100;
   int8_t array [ARRAY_SIZE];
   for (int i=0; i<ARRAY_SIZE; i+=64){
      array[i] = i;
   }

   CarbonEnableModels();

   for (int j= 0; j<NUM_ITERATIONS; j++){
      for (int i=0; i<ARRAY_SIZE; i+=64){
         array[i] += i;
      }
   }

   CarbonDisableModels();

}

void doComputeWork()
{
   volatile int i;
   volatile double j;
   for (i=0; i<10000; i++){
      j = j*(i+2);
   }
}

int main()
{
   double frequency = 0;
   double voltage = 0;
   int rc;
   module_t domain1 = CarbonGetDVFSDomain(L2_CACHE);
   module_t domain2 = CarbonGetDVFSDomain(NETWORK_MEMORY);

   frequency = 1.0;
   rc = CarbonSetDVFSAllTiles(domain1, &frequency, AUTO);
   rc = CarbonSetDVFSAllTiles(domain2, &frequency, AUTO);
   assert(rc == 0);

   doComputeWork();
   doMemoryWork();
}
<commit_msg>[dvfs][tests] Better error statements for dvfs unit tests<commit_after>#include "carbon_user.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

// Suggested DVFS domain configuration:
// <1.0, CORE, L1_ICACHE, L1_DCACHE> <1.0, L2_CACHE, DIRECTORY> <1.0, NETWORK_MEMORY, NETWORK_USER>

void doMemoryWork()
{
   //int ARRAY_SIZE = 8192*64;
   int ARRAY_SIZE = 512*64;
   int NUM_ITERATIONS = 100;
   int8_t array [ARRAY_SIZE];
   for (int i=0; i<ARRAY_SIZE; i+=64){
      array[i] = i;
   }

   CarbonEnableModels();

   for (int j= 0; j<NUM_ITERATIONS; j++){
      for (int i=0; i<ARRAY_SIZE; i+=64){
         array[i] += i;
      }
   }

   CarbonDisableModels();

}

void doComputeWork()
{
   volatile int i;
   volatile double j;
   for (i=0; i<10000; i++){
      j = j*(i+2);
   }
}

int main()
{
   double frequency = 0;
   double voltage = 0;
   int rc;
   module_t domain1 = CarbonGetDVFSDomain(L2_CACHE);
   module_t domain2 = CarbonGetDVFSDomain(NETWORK_MEMORY);

   frequency = 1.0;

   rc = CarbonSetDVFSAllTiles(domain1, &frequency, AUTO);
   if (rc != 0)
   {
      fprintf(stderr, "*ERROR* Setting frequency for L2_CACHE, Domain(%u), Return-Code(%i)\n", domain1, rc);
      exit(EXIT_FAILURE);
   }

   rc = CarbonSetDVFSAllTiles(domain2, &frequency, AUTO);
   if (rc != 0)
   {
      fprintf(stderr, "*ERROR* Setting frequency for NETWORK_MEMORY, Domain(%u), Return-Code(%i)\n", domain2, rc);
      exit(EXIT_FAILURE);
   }

   doComputeWork();
   doMemoryWork();
}
<|endoftext|>