<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "TransientExecutioner.h"

//Moose includes
#include "Kernel.h"
#include "MaterialFactory.h"
#include "MooseSystem.h"
#include "ComputeJacobian.h"
#include "ComputeResidual.h"

//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"

// C++ Includes
#include <iomanip>

template<>
InputParameters validParams<TransientExecutioner>()
{
  InputParameters params = validParams<Executioner>();
  std::vector<Real> sync_times(1);
  sync_times[0] = -1;

  params.addParam<Real>("start_time",      0.0,    "The start time of the simulation");
  params.addParam<Real>("end_time",        1.0e30, "The end time of the simulation");
  params.addRequiredParam<Real>("dt", "The timestep size between solves");
  params.addParam<Real>("dtmin",           0.0,    "The minimum timestep size in an adaptive run");
  params.addParam<Real>("dtmax",           1.0e30, "The maximum timestep size in an adaptive run");
  params.addParam<Real>("num_steps",       std::numeric_limits<Real>::max(),     "The number of timesteps in a transient run");
  params.addParam<int> ("n_startup_steps", 0,      "The number of timesteps during startup");
  params.addParam<bool>("trans_ss_check",  false,  "Whether or not to check for steady state conditions");
  params.addParam<Real>("ss_check_tol",    1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
  params.addParam<Real>("ss_tmin",         0.0,    "Minimum number of timesteps to take before checking for steady state conditions.");
  params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");

  return params;
}

TransientExecutioner::TransientExecutioner(const std::string & name, MooseSystem & moose_system, InputParameters parameters)
  :Executioner(name, moose_system, parameters),
   _t_step(moose_system.parameters().set<int> ("t_step") = 0),
   _time(moose_system.parameters().set<Real>("time") = getParam<Real>("start_time")),
   _input_dt(getParam<Real>("dt")),
   _dt(moose_system.parameters().set<Real>("dt") = 0),
   _prev_dt(-1),
   _reset_dt(false),
   _end_time(getParam<Real>("end_time")),
   _dtmin(getParam<Real>("dtmin")),
   _dtmax(getParam<Real>("dtmax")),
   _num_steps(getParam<Real>("num_steps")),
   _n_startup_steps(getParam<int>("n_startup_steps")),
   _trans_ss_check(getParam<bool>("trans_ss_check")),
   _ss_check_tol(getParam<Real>("ss_check_tol")),
   _ss_tmin(getParam<Real>("ss_tmin")),
   _converged(true),
   _sync_times(getParam<std::vector<Real> >("sync_times")),
   _curr_sync_time_iter(_sync_times.begin()),
   _remaining_sync_time(true)
{
  _moose_system.reinitDT();

  // Advance to the first sync time if one is provided in sim time range
  while (_remaining_sync_time && *_curr_sync_time_iter < _time)
    if (++_curr_sync_time_iter == _sync_times.end())
      _remaining_sync_time = false;
}

void
TransientExecutioner::execute()
{
  preExecute();
  // Start time loop...
  while(keepGoing())
  {
    takeStep();
  }
  postExecute();
}

void
TransientExecutioner::takeStep()
{
  // If this is the first step
  if(_t_step == 0)
  {
    _t_step = 1;
    _dt = _input_dt;
  }

  if(_converged)
  {
//    std::cout << "copy" << std::endl;
    // Update backward time solution vectors
    _moose_system.copy_old_solutions();
  }

  _moose_system.getNonlinearSystem()->update();

  Real dt_cur = computeDT();

  // Don't let the time step size exceed maximum time step size
  if(dt_cur > _dtmax)
    dt_cur = _dtmax;

  // Don't allow time step size to be smaller than minimum time step size
  if(dt_cur < _dtmin)
    dt_cur = _dtmin;

  // Don't let time go beyond simulation end time
  if(_time + dt_cur > _end_time)
    dt_cur = _end_time - _time;

  // Adjust to a sync time if supplied and skipped over
  if (_remaining_sync_time && _time + dt_cur > *_curr_sync_time_iter)
  {
    dt_cur = *_curr_sync_time_iter - _time;
    if (++_curr_sync_time_iter == _sync_times.end())
      _remaining_sync_time = false;

    _prev_dt = _dt;

    _reset_dt = true;
  }
  else
  {
    if (_reset_dt)
    {
      dt_cur = _prev_dt;
      _reset_dt = false;
    }
  }

  _dt = dt_cur;
  _moose_system.reinitDT();
  _moose_system.onTimestepBegin();

  if(_converged)
  {
    // Update backward material data structures
    _moose_system.updateMaterials();
  }

  // Increment time
  _time += dt_cur;

  _moose_system.reinitDT();

  std::cout<<"DT: "<<dt_cur<<std::endl;

  std::cout << " Solving time step ";
  {
    OStringStream out;

    OSSInt(out,2,_t_step);
    out << ", time=";
    OSSRealzeroleft(out,9,6,_time);
    out <<  "...";
    std::cout << out.str() << std::endl;
  }

  Moose::setSolverDefaults(_moose_system, this);

  setScaling();

  preSolve();

  Moose::perf_log.push("solve()","Solve");
  // System Solve
  _moose_system.solve();
  Moose::perf_log.pop("solve()","Solve");

  _converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;

  postSolve();

  std::cout<<"Norm of each nonlinear variable:"<<std::endl;
  for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)
    std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << ": "
              << _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;

  // We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
  bool last_solve_converged = lastSolveConverged();

  // If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
  if (last_solve_converged && ((_t_step+1)%_moose_system._interval == 0 || _reset_dt))
  {
    _moose_system.outputPostprocessors();
    _moose_system.outputSystem(_t_step, _time);
  }

  if(last_solve_converged)
  {
    adaptMesh();
    _t_step++;
  }
}

Real
TransientExecutioner::computeDT()
{
  if(!lastSolveConverged())
  {
    std::cout<<"Solve failed... cutting timestep"<<std::endl;
    return _dt / 2.0;
  }

  // If start up steps are needed
  if(_t_step == 1 && _n_startup_steps > 1)
    return _dt/(double)(_n_startup_steps);
  else
    return _dt;
}

bool
TransientExecutioner::keepGoing()
{
  // Check for stop condition based upon steady-state check flag:
  if(_converged && _trans_ss_check == true && _time > _ss_tmin)
  {
    // Compute new time solution l2_norm
    Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();

    // Compute l2_norm relative error
    Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;

    // Check current solution relative error norm against steady-state tolerance
    if(ss_relerr_norm < _ss_check_tol)
    {
      std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
      return false;
    }
    else // Keep going
    {
      // Update solution norm for next time step
      _old_time_solution_norm = new_time_solution_norm;
      // Print steady-state relative error norm
      std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
    }
  }

  // Check for stop condition based upon number of simulation steps and/or solution end time:
  if(_t_step>_num_steps)
    return false;

  if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
    return false;

  return true;
}

bool
TransientExecutioner::lastSolveConverged()
{
  return _converged;
}
<commit_msg>fixed initial time steps<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "TransientExecutioner.h"

//Moose includes
#include "Kernel.h"
#include "MaterialFactory.h"
#include "MooseSystem.h"
#include "ComputeJacobian.h"
#include "ComputeResidual.h"

//libMesh includes
#include "implicit_system.h"
#include "nonlinear_implicit_system.h"
#include "transient_system.h"
#include "numeric_vector.h"

// C++ Includes
#include <iomanip>

template<>
InputParameters validParams<TransientExecutioner>()
{
  InputParameters params = validParams<Executioner>();
  std::vector<Real> sync_times(1);
  sync_times[0] = -1;

  params.addParam<Real>("start_time",      0.0,    "The start time of the simulation");
  params.addParam<Real>("end_time",        1.0e30, "The end time of the simulation");
  params.addRequiredParam<Real>("dt", "The timestep size between solves");
  params.addParam<Real>("dtmin",           0.0,    "The minimum timestep size in an adaptive run");
  params.addParam<Real>("dtmax",           1.0e30, "The maximum timestep size in an adaptive run");
  params.addParam<Real>("num_steps",       std::numeric_limits<Real>::max(),     "The number of timesteps in a transient run");
  params.addParam<int> ("n_startup_steps", 0,      "The number of timesteps during startup");
  params.addParam<bool>("trans_ss_check",  false,  "Whether or not to check for steady state conditions");
  params.addParam<Real>("ss_check_tol",    1.0e-08,"Whenever the relative residual changes by less than this the solution will be considered to be at steady state.");
  params.addParam<Real>("ss_tmin",         0.0,    "Minimum number of timesteps to take before checking for steady state conditions.");
  params.addParam<std::vector<Real> >("sync_times", sync_times, "A list of times that will be solved for provided they are within the simulation time");

  return params;
}

TransientExecutioner::TransientExecutioner(const std::string & name, MooseSystem & moose_system, InputParameters parameters)
  :Executioner(name, moose_system, parameters),
   _t_step(moose_system.parameters().set<int> ("t_step") = 0),
   _time(moose_system.parameters().set<Real>("time") = getParam<Real>("start_time")),
   _input_dt(getParam<Real>("dt")),
   _dt(moose_system.parameters().set<Real>("dt") = 0),
   _prev_dt(-1),
   _reset_dt(false),
   _end_time(getParam<Real>("end_time")),
   _dtmin(getParam<Real>("dtmin")),
   _dtmax(getParam<Real>("dtmax")),
   _num_steps(getParam<Real>("num_steps")),
   _n_startup_steps(getParam<int>("n_startup_steps")),
   _trans_ss_check(getParam<bool>("trans_ss_check")),
   _ss_check_tol(getParam<Real>("ss_check_tol")),
   _ss_tmin(getParam<Real>("ss_tmin")),
   _converged(true),
   _sync_times(getParam<std::vector<Real> >("sync_times")),
   _curr_sync_time_iter(_sync_times.begin()),
   _remaining_sync_time(true)
{
  _moose_system.reinitDT();

  // Advance to the first sync time if one is provided in sim time range
  while (_remaining_sync_time && *_curr_sync_time_iter < _time)
    if (++_curr_sync_time_iter == _sync_times.end())
      _remaining_sync_time = false;
}

void
TransientExecutioner::execute()
{
  preExecute();
  // Start time loop...
  while(keepGoing())
  {
    takeStep();
  }
  postExecute();
}

void
TransientExecutioner::takeStep()
{
  // If this is the first step
  if(_t_step == 0)
  {
    _t_step = 1;
    _dt = _input_dt;
  }

  if(_converged)
  {
//    std::cout << "copy" << std::endl;
    // Update backward time solution vectors
    _moose_system.copy_old_solutions();
  }

  _moose_system.getNonlinearSystem()->update();

  Real dt_cur = computeDT();

  // Don't let the time step size exceed maximum time step size
  if(dt_cur > _dtmax)
    dt_cur = _dtmax;

  // Don't allow time step size to be smaller than minimum time step size
  if(dt_cur < _dtmin)
    dt_cur = _dtmin;

  // Don't let time go beyond simulation end time
  if(_time + dt_cur > _end_time)
    dt_cur = _end_time - _time;

  // Adjust to a sync time if supplied and skipped over
  if (_remaining_sync_time && _time + dt_cur > *_curr_sync_time_iter)
  {
    dt_cur = *_curr_sync_time_iter - _time;
    if (++_curr_sync_time_iter == _sync_times.end())
      _remaining_sync_time = false;

    _prev_dt = _dt;

    _reset_dt = true;
  }
  else
  {
    if (_reset_dt)
    {
      dt_cur = _prev_dt;
      _reset_dt = false;
    }
  }

  _dt = dt_cur;
  _moose_system.reinitDT();
  _moose_system.onTimestepBegin();

  if(_converged)
  {
    // Update backward material data structures
    _moose_system.updateMaterials();
  }

  // Increment time
  _time += dt_cur;

  _moose_system.reinitDT();

  std::cout<<"DT: "<<dt_cur<<std::endl;

  std::cout << " Solving time step ";
  {
    OStringStream out;

    OSSInt(out,2,_t_step);
    out << ", time=";
    OSSRealzeroleft(out,9,6,_time);
    out <<  "...";
    std::cout << out.str() << std::endl;
  }

  Moose::setSolverDefaults(_moose_system, this);

  setScaling();

  preSolve();

  Moose::perf_log.push("solve()","Solve");
  // System Solve
  _moose_system.solve();
  Moose::perf_log.pop("solve()","Solve");

  _converged = _moose_system.getNonlinearSystem()->nonlinear_solver->converged;

  postSolve();

  std::cout<<"Norm of each nonlinear variable:"<<std::endl;
  for(unsigned int var = 0; var < _moose_system.getNonlinearSystem()->n_vars(); var++)
    std::cout << _moose_system.getNonlinearSystem()->variable_name(var) << ": "
              << _moose_system.getNonlinearSystem()->calculate_norm(*_moose_system.getNonlinearSystem()->rhs,var,DISCRETE_L2) << std::endl;

  // We know whether or not the nonlinear solver thinks it converged, but we need to see if the executioner concurs
  bool last_solve_converged = lastSolveConverged();

  // If _reset_dt is true, the time step was synced to the user defined value and we dump the solution in an output file
  if (last_solve_converged && ((_t_step+1)%_moose_system._interval == 0 || _reset_dt))
  {
    _moose_system.outputPostprocessors();
    _moose_system.outputSystem(_t_step, _time);
  }

  if(last_solve_converged)
  {
    adaptMesh();
    _t_step++;
  }
}

Real
TransientExecutioner::computeDT()
{
  if(!lastSolveConverged())
  {
    std::cout<<"Solve failed... cutting timestep"<<std::endl;
    return _dt / 2.0;
  }

  // If start up steps are needed
  if(_t_step == 1 && _n_startup_steps > 1)
    return _dt/(double)(_n_startup_steps);
  else if (_t_step == 1+_n_startup_steps)
    return _dt*(double)(_n_startup_steps);
  else
    return _dt;
}

bool
TransientExecutioner::keepGoing()
{
  // Check for stop condition based upon steady-state check flag:
  if(_converged && _trans_ss_check == true && _time > _ss_tmin)
  {
    // Compute new time solution l2_norm
    Real new_time_solution_norm = _moose_system.getNonlinearSystem()->current_local_solution->l2_norm();

    // Compute l2_norm relative error
    Real ss_relerr_norm = fabs(new_time_solution_norm - _old_time_solution_norm)/new_time_solution_norm;

    // Check current solution relative error norm against steady-state tolerance
    if(ss_relerr_norm < _ss_check_tol)
    {
      std::cout<<"Steady-State Solution Achieved at time: "<<_time<<std::endl;
      return false;
    }
    else // Keep going
    {
      // Update solution norm for next time step
      _old_time_solution_norm = new_time_solution_norm;
      // Print steady-state relative error norm
      std::cout<<"Steady-State Relative Differential Norm: "<<ss_relerr_norm<<std::endl;
    }
  }

  // Check for stop condition based upon number of simulation steps and/or solution end time:
  if(_t_step>_num_steps)
    return false;

  if((_time>_end_time) || (fabs(_time-_end_time)<1.e-14))
    return false;

  return true;
}

bool
TransientExecutioner::lastSolveConverged()
{
  return _converged;
}
<|endoftext|>


<commit_before>#include "hooks_py.h"
#include "simulator.h"
#include "core_manager.h"
#include "config.hpp"
#include "fxsupport.h"

bool HooksPy::pyInit = false;

void HooksPy::init()
{
   UInt64 numscripts = Sim()->getCfg()->getInt("hooks/numscripts");
   for(UInt64 i = 0; i < numscripts; ++i) {
      String scriptname = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "name");
      if (scriptname.substr(scriptname.length()-3) == ".py") {
         if (! pyInit) {
            setup();
         }

         String args = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "args");
         char *argv[] = { (char*)(scriptname.c_str()), (char*)(args.c_str()) };
         PySys_SetArgvEx(2, argv, 0 /* updatepath */);

         printf("Executing Python script %s\n", scriptname.c_str());
         int s = PyRun_SimpleFileEx(fopen(scriptname.c_str(), "r"), scriptname.c_str(), 1 /* closeit */);
         if (s != 0) {
            PyErr_Print();
            fprintf(stderr, "Cannot open Python script %s\n", scriptname.c_str());
            exit(-1);
         }
      }
   }
}

void HooksPy::setup()
{
   pyInit = true;
   const char* graphite_root = getenv("GRAPHITE_ROOT");
   LOG_ASSERT_ERROR(graphite_root, "Please make sure GRAPHITE_ROOT is set");
#ifdef TARGET_INTEL64
   String python_home = String(graphite_root) + "/python_kit/intel64";
#else
   String python_home = String(graphite_root) + "/python_kit/ia32";
#endif
   Py_SetPythonHome(strdup(python_home.c_str()));
   Py_InitializeEx(0 /* don't initialize signal handlers */);

   // set up all components
   PyConfig::setup();
   PyStats::setup();
   PyHooks::setup();
   PyDvfs::setup();
   PyControl::setup();
   PyBbv::setup();
}

void HooksPy::fini()
{
   if (pyInit)
      Py_Finalize();
}

PyObject * HooksPy::callPythonFunction(PyObject *pFunc, PyObject *pArgs)
{
   PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
   Py_XDECREF(pArgs);
   if (pResult == NULL) {
      PyErr_Print();
   }
   return pResult;
}
<commit_msg>[PATCH 44/85] [scripting] Find Sniper's root directory in either SNIPER_ROOT or GRAPHITE_ROOT<commit_after>#include "hooks_py.h"
#include "simulator.h"
#include "core_manager.h"
#include "config.hpp"
#include "fxsupport.h"

bool HooksPy::pyInit = false;

void HooksPy::init()
{
   UInt64 numscripts = Sim()->getCfg()->getInt("hooks/numscripts");
   for(UInt64 i = 0; i < numscripts; ++i) {
      String scriptname = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "name");
      if (scriptname.substr(scriptname.length()-3) == ".py") {
         if (! pyInit) {
            setup();
         }

         String args = Sim()->getCfg()->getString(String("hooks/script") + itostr(i) + "args");
         char *argv[] = { (char*)(scriptname.c_str()), (char*)(args.c_str()) };
         PySys_SetArgvEx(2, argv, 0 /* updatepath */);

         printf("Executing Python script %s\n", scriptname.c_str());
         int s = PyRun_SimpleFileEx(fopen(scriptname.c_str(), "r"), scriptname.c_str(), 1 /* closeit */);
         if (s != 0) {
            PyErr_Print();
            fprintf(stderr, "Cannot open Python script %s\n", scriptname.c_str());
            exit(-1);
         }
      }
   }
}

void HooksPy::setup()
{
   pyInit = true;
   const char* sim_root = NULL;
   const char env_roots[2][16] = {"SNIPER_ROOT", "GRAPHITE_ROOT"};
   for (unsigned int i = 0 ; i < 2 ; i++)
   {
      sim_root = getenv(env_roots[i]);
      if (sim_root)
         break;
   }
   LOG_ASSERT_ERROR(sim_root, "Please make sure SNIPER_ROOT or GRAPHITE_ROOT is set");
#ifdef TARGET_INTEL64
   String python_home = String(sim_root) + "/python_kit/intel64";
#else
   String python_home = String(sim_root) + "/python_kit/ia32";
#endif
   Py_SetPythonHome(strdup(python_home.c_str()));
   Py_InitializeEx(0 /* don't initialize signal handlers */);

   // set up all components
   PyConfig::setup();
   PyStats::setup();
   PyHooks::setup();
   PyDvfs::setup();
   PyControl::setup();
   PyBbv::setup();
}

void HooksPy::fini()
{
   if (pyInit)
      Py_Finalize();
}

PyObject * HooksPy::callPythonFunction(PyObject *pFunc, PyObject *pArgs)
{
   PyObject *pResult = PyObject_CallObject(pFunc, pArgs);
   Py_XDECREF(pArgs);
   if (pResult == NULL) {
      PyErr_Print();
   }
   return pResult;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AGroup.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:28:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_GROUP_HXX_
#include "ado/AGroup.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_USERS_HXX_
#include "ado/AUsers.hxx"
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;

// -------------------------------------------------------------------------
void WpADOGroup::Create()
{
    IClassFactory2* pIUnknown   = NULL;
    IUnknown        *pOuter     = NULL;
    HRESULT         hr = -1;
    ADOGroup* pGroup = NULL;
    hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          ADOS::IID_ADOGROUP_25,
                          (void**)&pGroup );

    if( !FAILED( hr ) )
    {
        operator=( pGroup );
        pGroup->Release();
    }
}
// -------------------------------------------------------------------------
OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase,    ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)
{
    construct();
    if(_pGroup)
        m_aGroup = WpADOGroup(_pGroup);
    else
        m_aGroup.Create();

}
// -------------------------------------------------------------------------
OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)
{
    construct();
    m_aGroup.Create();
    m_aGroup.put_Name(_Name);
}
// -------------------------------------------------------------------------
void OAdoGroup::refreshUsers()
{
    TStringVector aVector;

    WpADOUsers aUsers = m_aGroup.get_Users();
    aUsers.fillElementNames(aVector);

    if(m_pUsers)
        m_pUsers->reFill(aVector);
    else
        m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());
}
//--------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()
{
    static ::cppu::OImplementationId * pId = 0;
    if (! pId)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (! pId)
        {
            static ::cppu::OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
                ?
            (sal_Int64)this
                :
            OGroup_ADO::getSomething(rId);
}

// -------------------------------------------------------------------------
void OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)
{
    if(m_aGroup.IsValid())
    {

        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                {
                    ::rtl::OUString aVal;
                    rValue >>= aVal;
                    m_aGroup.put_Name(aVal);
                }
                break;
        }
    }
}
// -------------------------------------------------------------------------
void OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    if(m_aGroup.IsValid())
    {
        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                rValue <<= m_aGroup.get_Name();
                break;
        }
    }
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));
    if(eNum & adRightWithGrant)
        return MapRight(eNum);
    return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));
}
// -------------------------------------------------------------------------
void SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));
}

// -----------------------------------------------------------------------------
void SAL_CALL OAdoGroup::acquire() throw(::com::sun::star::uno::RuntimeException)
{
    OGroup_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoGroup::release() throw(::com::sun::star::uno::RuntimeException)
{
    OGroup_ADO::release();
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.16.30); FILE MERGED 2005/12/22 11:44:34 fs 1.16.30.2: #i57457# warning-free code 2005/11/07 14:43:06 fs 1.16.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AGroup.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:13:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_GROUP_HXX_
#include "ado/AGroup.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_USERS_HXX_
#include "ado/AUsers.hxx"
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADO_BCONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace connectivity::ado;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;

// -------------------------------------------------------------------------
void WpADOGroup::Create()
{
    HRESULT         hr = -1;
    ADOGroup* pGroup = NULL;
    hr = CoCreateInstance(ADOS::CLSID_ADOGROUP_25,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          ADOS::IID_ADOGROUP_25,
                          (void**)&pGroup );

    if( !FAILED( hr ) )
    {
        operator=( pGroup );
        pGroup->Release();
    }
}
// -------------------------------------------------------------------------
OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase,    ADOGroup* _pGroup) : OGroup_ADO(_bCase),m_pCatalog(_pParent)
{
    construct();
    if(_pGroup)
        m_aGroup = WpADOGroup(_pGroup);
    else
        m_aGroup.Create();

}
// -------------------------------------------------------------------------
OAdoGroup::OAdoGroup(OCatalog* _pParent,sal_Bool _bCase, const ::rtl::OUString& _Name) : OGroup_ADO(_Name,_bCase),m_pCatalog(_pParent)
{
    construct();
    m_aGroup.Create();
    m_aGroup.put_Name(_Name);
}
// -------------------------------------------------------------------------
void OAdoGroup::refreshUsers()
{
    TStringVector aVector;

    WpADOUsers aUsers = m_aGroup.get_Users();
    aUsers.fillElementNames(aVector);

    if(m_pUsers)
        m_pUsers->reFill(aVector);
    else
        m_pUsers = new OUsers(m_pCatalog,m_aMutex,aVector,aUsers,isCaseSensitive());
}
//--------------------------------------------------------------------------
Sequence< sal_Int8 > OAdoGroup::getUnoTunnelImplementationId()
{
    static ::cppu::OImplementationId * pId = 0;
    if (! pId)
    {
        ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
        if (! pId)
        {
            static ::cppu::OImplementationId aId;
            pId = &aId;
        }
    }
    return pId->getImplementationId();
}

// com::sun::star::lang::XUnoTunnel
//------------------------------------------------------------------
sal_Int64 OAdoGroup::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
{
    return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(),  rId.getConstArray(), 16 ) )
                ? reinterpret_cast< sal_Int64 >( this )
                : OGroup_ADO::getSomething(rId);
}

// -------------------------------------------------------------------------
void OAdoGroup::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue)throw (Exception)
{
    if(m_aGroup.IsValid())
    {

        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                {
                    ::rtl::OUString aVal;
                    rValue >>= aVal;
                    m_aGroup.put_Name(aVal);
                }
                break;
        }
    }
}
// -------------------------------------------------------------------------
void OAdoGroup::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const
{
    if(m_aGroup.IsValid())
    {
        switch(nHandle)
        {
            case PROPERTY_ID_NAME:
                rValue <<= m_aGroup.get_Name();
                break;
        }
    }
}
// -------------------------------------------------------------------------

sal_Int32 SAL_CALL OAdoGroup::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    return MapRight(m_aGroup.GetPermissions(objName,MapObjectType(objType)));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdoGroup::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    RightsEnum eNum = m_aGroup.GetPermissions(objName,MapObjectType(objType));
    if(eNum & adRightWithGrant)
        return MapRight(eNum);
    return 0;
}
// -------------------------------------------------------------------------
void SAL_CALL OAdoGroup::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessGrant,Map2Right(objPrivileges));
}
// -------------------------------------------------------------------------
void SAL_CALL OAdoGroup::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(::com::sun::star::sdbc::SQLException, RuntimeException)
{
    m_aGroup.SetPermissions(objName,MapObjectType(objType),adAccessDeny,Map2Right(objPrivileges));
}

// -----------------------------------------------------------------------------
void SAL_CALL OAdoGroup::acquire() throw(::com::sun::star::uno::RuntimeException)
{
    OGroup_ADO::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OAdoGroup::release() throw(::com::sun::star::uno::RuntimeException)
{
    OGroup_ADO::release();
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "modify_asmbar.hpp"
#include "qhexedit.hpp"
#include <QMessageBox>
#include <QHBoxLayout>
#include <iostream>
#include <QDebug>

ModifyASMBar::ModifyASMBar(CodeContainer *container, ASMViewer *asmViewer, QHexEdit *hexEditor,
    QWidget *parent) : QWidget(parent), container(container), asmViewer(asmViewer),
                       hexEditor(hexEditor)
{
    modify = new QLabel(QString("Modify:"), this);
    text = new QLineEdit(this);
    ok = new QPushButton(QString("OK"), this);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->setContentsMargins(QMargins());
    layout->addWidget(modify);
    layout->addWidget(text);
    layout->addWidget(ok);
    setLayout(layout);
    setMaximumHeight(80);

    connect(ok, SIGNAL(clicked()), this, SLOT(editInstruction()));
}

void ModifyASMBar::editInstruction()
{
    std::cerr << "OK!\n";
    QModelIndexList list = asmViewer->selectionModel()->selectedIndexes();
    QString inputInstruction = text->text();

    if (!list.size())
    {
        QMessageBox::critical(this, QString("Error"),
                              QString("You must select the instruction to be replaced."));
        return;
    }

    std::string binaryCode;
    int fullyCovered;
    int rest;
    QString machineCode = list[1].data().toString();
    unsigned int instrSize = (machineCode.size() + 1) / 3;
    int selectedRow = list[0].row();

    if (inputInstruction.isEmpty())
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "Confirmation required",
            "You left the \"Modify\" field blank. Do you want to delete the currently selected "
            "instruction? Its content will be replaced with NOP instructions.",
            QMessageBox::Yes | QMessageBox::No);
        if (reply == QMessageBox::No)
            return;
        fullyCovered = 0;
        rest = instrSize;
    }
    else
    {
        bool assembled;
        binaryCode = FileAssembly::assembleCode(inputInstruction.toStdString(), assembled);
        if (!assembled)
        {
            QMessageBox::critical(this, QString("Error"),
                QString("The instruction provided could not be assembled. "
                        "Please check your input and try again."));
            return;
        }

        if (binaryCode.size() < instrSize)
        {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(this, "Confirmation required",
                QString("The instruction provided is shorter than the instruction to be replaced. "
                        "The last %1 byte(s) of the currently selected instruction will be "
                        "overwritten with NOP instructions.\nDo you want to proceed?")
                        .arg(instrSize - binaryCode.size()),
                QMessageBox::Yes | QMessageBox::No);
            if (reply == QMessageBox::No)
                return;
            fullyCovered = 0;
            rest = instrSize - binaryCode.size();
        }
        else if (binaryCode.size() > instrSize)
        {
            int row = selectedRow;
            int bytesLeft = binaryCode.size();
            rest = 0;

            while (bytesLeft > 0 && row < asmViewer->getModel()->rowCount())
            {
                int currentSize = (asmViewer->getModel()->item(row, 1)->text().size() + 1) / 3;
                if (currentSize >= bytesLeft)
                    rest = currentSize - bytesLeft;
                bytesLeft -= currentSize;
                ++row;
            }

            if (bytesLeft > 0 && row == asmViewer->getModel()->rowCount())
            {
                QMessageBox::critical(this, QString("Error"),
                    QString("The new instruction cannot exceed the section limit."));
                return;
            }

            fullyCovered = row - selectedRow;
            if (rest)
                --fullyCovered;

            QString message = QString("The instruction provided is longer than the instruction to "
                "be replaced. %1 instruction(s) starting with the one you selected will be fully "
                "overwritten.").arg(fullyCovered);
            QString ord;
            if (fullyCovered + 1 == 2)
                ord = QString("nd");
            else if (fullyCovered + 1 == 3)
                ord = QString("rd");
            else
                ord = QString("th");
            if (rest)
                message += QString(" Additionally, the %1%2 instruction will be partially "
                    "overwritten: its last %3 bytes will be replaced with NOP instructions. ")
                    .arg(fullyCovered + 1).arg(ord).arg(rest);
            message += QString("\nDo you want to proceed?");

            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(this, "Confirmation required", message,
                QMessageBox::Yes | QMessageBox::No);
            if (reply == QMessageBox::No)
                return;
        }
        else
        {
            fullyCovered = 1;
            rest = 0;
        }
    }

    bool ok;
    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);
    int row = selectedRow;

    if (binaryCode != "")
    {
        std::string opcode;
        std::string arguments;
        ASMViewer::splitInstruction(binaryCode, opcode, arguments);

        QList<QStandardItem *> newInstructionEntry {
            new QStandardItem(QString::number(address, 16)),
            new QStandardItem(ASMViewer::bufferToHex(binaryCode)),
            new QStandardItem(QString(opcode.c_str())),
            new QStandardItem(QString(arguments.c_str()))
        };

        asmViewer->getModel()->insertRow(row, newInstructionEntry);
        address += binaryCode.size();
        ++row;
    }

    for (int i = 0; i < rest; ++i)
    {
        QList<QStandardItem *> newInstructionEntry {
            new QStandardItem(QString::number(address, 16)),
            new QStandardItem(QString("90")),
            new QStandardItem(QString("nop")),
            new QStandardItem(QString(""))
        };
        asmViewer->getModel()->insertRow(row, newInstructionEntry);
        ++address;
        ++row;
    }

    asmViewer->getModel()->removeRows(row, fullyCovered + (rest ? 1 : 0));

    /* TODO: The input instruction will also be updated in the elfio backend
     * and hexedit */
}

void ModifyASMBar::changeViewerSelection(const QItemSelection &selected,
                                         const QItemSelection &deselected)
{
    QModelIndexList list = selected.indexes();
    text->setText(list[2].data().toString() + ' ' + list[3].data().toString());

    bool ok;
    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);
    hexEditor->selectData(container->addressToOffset(address), (list[1].data().toString().size() + 1) / 3);
}
<commit_msg>Call ELFCodeContainer::overwrite after updating the ASMViewer model<commit_after>/* The MIT License (MIT)
 *
 * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "modify_asmbar.hpp"
#include "qhexedit.hpp"
#include <QMessageBox>
#include <QHBoxLayout>
#include <iostream>
#include <QDebug>

ModifyASMBar::ModifyASMBar(CodeContainer *container, ASMViewer *asmViewer, QHexEdit *hexEditor,
    QWidget *parent) : QWidget(parent), container(container), asmViewer(asmViewer),
                       hexEditor(hexEditor)
{
    modify = new QLabel(QString("Modify:"), this);
    text = new QLineEdit(this);
    ok = new QPushButton(QString("OK"), this);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->setContentsMargins(QMargins());
    layout->addWidget(modify);
    layout->addWidget(text);
    layout->addWidget(ok);
    setLayout(layout);
    setMaximumHeight(80);

    connect(ok, SIGNAL(clicked()), this, SLOT(editInstruction()));
}

void ModifyASMBar::editInstruction()
{
    std::cerr << "OK!\n";
    QModelIndexList list = asmViewer->selectionModel()->selectedIndexes();
    QString inputInstruction = text->text();

    if (!list.size())
    {
        QMessageBox::critical(this, QString("Error"),
                              QString("You must select the instruction to be replaced."));
        return;
    }

    std::string binaryCode;
    int fullyCovered;
    int rest;
    QString machineCode = list[1].data().toString();
    unsigned int instrSize = (machineCode.size() + 1) / 3;
    int selectedRow = list[0].row();

    if (inputInstruction.isEmpty())
    {
        QMessageBox::StandardButton reply;
        reply = QMessageBox::question(this, "Confirmation required",
            "You left the \"Modify\" field blank. Do you want to delete the currently selected "
            "instruction? Its content will be replaced with NOP instructions.",
            QMessageBox::Yes | QMessageBox::No);
        if (reply == QMessageBox::No)
            return;
        fullyCovered = 0;
        rest = instrSize;
    }
    else
    {
        bool assembled;
        binaryCode = FileAssembly::assembleCode(inputInstruction.toStdString(), assembled);
        if (!assembled)
        {
            QMessageBox::critical(this, QString("Error"),
                QString("The instruction provided could not be assembled. "
                        "Please check your input and try again."));
            return;
        }

        if (binaryCode.size() < instrSize)
        {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(this, "Confirmation required",
                QString("The instruction provided is shorter than the instruction to be replaced. "
                        "The last %1 byte(s) of the currently selected instruction will be "
                        "overwritten with NOP instructions.\nDo you want to proceed?")
                        .arg(instrSize - binaryCode.size()),
                QMessageBox::Yes | QMessageBox::No);
            if (reply == QMessageBox::No)
                return;
            fullyCovered = 0;
            rest = instrSize - binaryCode.size();
        }
        else if (binaryCode.size() > instrSize)
        {
            int row = selectedRow;
            int bytesLeft = binaryCode.size();
            rest = 0;

            while (bytesLeft > 0 && row < asmViewer->getModel()->rowCount())
            {
                int currentSize = (asmViewer->getModel()->item(row, 1)->text().size() + 1) / 3;
                if (currentSize >= bytesLeft)
                    rest = currentSize - bytesLeft;
                bytesLeft -= currentSize;
                ++row;
            }

            if (bytesLeft > 0 && row == asmViewer->getModel()->rowCount())
            {
                QMessageBox::critical(this, QString("Error"),
                    QString("The new instruction cannot exceed the section limit."));
                return;
            }

            fullyCovered = row - selectedRow;
            if (rest)
                --fullyCovered;

            QString message = QString("The instruction provided is longer than the instruction to "
                "be replaced. %1 instruction(s) starting with the one you selected will be fully "
                "overwritten.").arg(fullyCovered);
            QString ord;
            if (fullyCovered + 1 == 2)
                ord = QString("nd");
            else if (fullyCovered + 1 == 3)
                ord = QString("rd");
            else
                ord = QString("th");
            if (rest)
                message += QString(" Additionally, the %1%2 instruction will be partially "
                    "overwritten: its last %3 bytes will be replaced with NOP instructions. ")
                    .arg(fullyCovered + 1).arg(ord).arg(rest);
            message += QString("\nDo you want to proceed?");

            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(this, "Confirmation required", message,
                QMessageBox::Yes | QMessageBox::No);
            if (reply == QMessageBox::No)
                return;
        }
        else
        {
            fullyCovered = 1;
            rest = 0;
        }
    }

    bool ok;
    unsigned long long initialAddress = list[0].data().toString().toULongLong(&ok, 16);
    unsigned long long address = initialAddress;
    int row = selectedRow;

    if (binaryCode != "")
    {
        std::string opcode;
        std::string arguments;
        ASMViewer::splitInstruction(binaryCode, opcode, arguments);

        QList<QStandardItem *> newInstructionEntry {
            new QStandardItem(QString::number(address, 16)),
            new QStandardItem(ASMViewer::bufferToHex(binaryCode)),
            new QStandardItem(QString(opcode.c_str())),
            new QStandardItem(QString(arguments.c_str()))
        };

        asmViewer->getModel()->insertRow(row, newInstructionEntry);
        address += binaryCode.size();
        ++row;
    }

    std::string codeContainerUpdate = binaryCode;
    for (int i = 0; i < rest; ++i)
    {
        QList<QStandardItem *> newInstructionEntry {
            new QStandardItem(QString::number(address, 16)),
            new QStandardItem(QString("90")),
            new QStandardItem(QString("nop")),
            new QStandardItem(QString(""))
        };
        codeContainerUpdate += (char)0x90;
        asmViewer->getModel()->insertRow(row, newInstructionEntry);
        ++address;
        ++row;
    }

    asmViewer->getModel()->removeRows(row, fullyCovered + (rest ? 1 : 0));

    /* TODO: The input instruction will also be updated in the elfio backend
     * and hexedit */
    container->overwrite(initialAddress, codeContainerUpdate);
}

void ModifyASMBar::changeViewerSelection(const QItemSelection &selected,
                                         const QItemSelection &deselected)
{
    QModelIndexList list = selected.indexes();
    text->setText(list[2].data().toString() + ' ' + list[3].data().toString());

    bool ok;
    unsigned long long address = list[0].data().toString().toULongLong(&ok, 16);
    hexEditor->selectData(container->addressToOffset(address), (list[1].data().toString().size() + 1) / 3);
}
<|endoftext|>


<commit_before>#include "../records/RandomAccessFilm.h"

void reportVisualError(const RandomAccessFilm &in,
                       const RandomAccessFilm &ref)
{
  float displayMax = 100.0f;

  // scale to display max
  RandomAccessFilm displayIn = in;
  displayIn.scale(Spectrum(displayMax, displayMax, displayMax));

  RandomAccessFilm displayRef = ref;
  displayRef.scale(Spectrum(displayMax, displayMax, displayMax));

  // compute target image
  RandomAccessFilm target(ref.getWidth(), ref.getHeight());
  for(size_t y = 0; y != target.getHeight(); ++y)
  {
    for(size_t x = 0; x != target.getWidth(); ++x)
    {
      float e = fabs(displayRef.raster(x,y).luminance() - displayIn.raster(x,y).luminance());
      target.raster(x,y) = Spectrum::white();
      target.raster(x,y).setLuminance(e);
    } // end for x
  } // end for y

  RandomAccessFilm tvi = ref;
  tvi.applyThresholdVersusIntensityFunction();

  // divide by tvi
  target.divideLuminance(tvi, 0);

  // now add everything up
  float sum = 0;
  for(size_t y = 0; y != target.getHeight(); ++y)
  {
    for(size_t x = 0; x != target.getWidth(); ++x)
    {
      sum += target.raster(x,y).luminance();
    } // end for x
  } // end for y
  sum /= (target.getWidth() * target.getHeight());

  std::cerr << "Visual error: " << sum << std::endl;
} // end reportVisualError()

int main(int argc, char **argv)
{
  if(argc < 2)
  {
    std::cerr << "usage: imgstat in.exr [ref.exr]" << std::endl;
    exit(-1);
  } // end if

  RandomAccessFilm in;
  in.readEXR(argv[1]);

  // first compute mean
  Spectrum mean(Spectrum::black());
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      mean += in.raster(x,y);
    } // end for x
  } // end for y

  mean /= (in.getWidth() * in.getHeight());

  // now compute variance
  float variance = 0;
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      float diff2 = in.raster(x,y).luminance() - mean.luminance();
      diff2 *= diff2;
      variance += diff2;
    } // end for x
  } // end for y

  variance /= (in.getWidth() * in.getHeight());

  // now compute skew & kurtosis
  float kurtosisNumerator = 0;
  float skewNumerator = 0;
  float denom = 0;
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      float diff = in.raster(x,y).luminance() - mean.luminance();
      float diff2 = diff * diff;
      float diff3 = diff * diff2;
      float diff4 = diff2 * diff2;

      skewNumerator += diff3;
      kurtosisNumerator += diff4;
      denom += diff2;
    } // end for x
  } // end for y

  skewNumerator *= sqrtf(static_cast<float>(in.getWidth() * in.getHeight()));
  kurtosisNumerator *= (in.getWidth() * in.getHeight());

  float skew = skewNumerator / powf(denom,1.5f);
  float kurtosis = kurtosisNumerator / powf(denom,2.0f) - 3.0f;

  std::cout << "Filename: " << argv[0] << std::endl;
  std::cout << "mean: " << mean << std::endl;
  std::cout << "variance: " << variance << std::endl;
  std::cout << "skew: " << skew << std::endl;
  std::cout << "kurtosis: " << kurtosis << std::endl;

  if(argc > 2)
  {
    RandomAccessFilm ref;
    ref.readEXR(argv[2]);
    if(ref.getWidth() != in.getWidth() ||
       ref.getHeight() != in.getHeight())
    {
      RandomAccessFilm resampled(in.getWidth(), in.getHeight());
      ref.resample(resampled);
      ref = resampled;
    } // end if

    // downsample then upsample the reference
    RandomAccessFilm down(ref.getWidth() / 4, ref.getHeight() / 4);
    ref.resample(down);
    down.resample(ref);

    // first normalize the input's mean luminance to match the reference
    float referenceLuminance = ref.computeMeanLuminance();
    float s = referenceLuminance / in.computeMeanLuminance();
    in.scale(Spectrum(s,s,s));

    // measure squared error
    float squaredError = 0;
    for(size_t y = 0; y != in.getHeight(); ++y)
    {
      for(size_t x = 0; x != in.getWidth(); ++x)
      {
        float r = ref.raster(x,y).luminance();

        if(r == r && r != std::numeric_limits<float>::infinity())
        {
          float i = in.raster(x,y).luminance();
          //i = std::min(powf(i,1.0f / 2.1f), 1.0f);
          //r = std::min(powf(i,1.0f / 2.1f), 1.0f);

          float diff = i - r;
          squaredError += diff * diff;
        } // end if
        else
        {
          std::cerr << "Warning: skipped inf or nan in reference at " << x << "," << y << std::endl;
        } // end else
      } // end for x
    } // end for y
    squaredError /= (in.getWidth() * in.getHeight());

    // measure relative error
    float m = ref.computeLuminancePercentileIgnoreZero(0);

    float relError = 0;
    for(size_t y = 0; y != in.getHeight(); ++y)
    {
      for(size_t x = 0; x != in.getWidth(); ++x)
      {
        float r = ref.raster(x,y).luminance();

        if(r == r && r != std::numeric_limits<float>::infinity())
        {

          float i = in.raster(x,y).luminance();

          float diff = fabs(i - r);

          diff /= std::max(0.0005f, r);

          relError += diff;
        } // end if
        else
        {
          std::cerr << "Warning: skipped inf or nan in reference at " << x << "," << y << std::endl;
        } // end else
      } // end for x
    } // end for y
    relError /= (in.getWidth() * in.getHeight());

    std::cout << "squared error: " << squaredError << std::endl;
    std::cout << "relative error: " << relError << std::endl;

    reportVisualError(in, ref);
  } // end if

  return 0;
} // end main()

<commit_msg>Kill warning<commit_after>#include "../records/RandomAccessFilm.h"

void reportVisualError(const RandomAccessFilm &in,
                       const RandomAccessFilm &ref)
{
  float displayMax = 100.0f;

  // scale to display max
  RandomAccessFilm displayIn = in;
  displayIn.scale(Spectrum(displayMax, displayMax, displayMax));

  RandomAccessFilm displayRef = ref;
  displayRef.scale(Spectrum(displayMax, displayMax, displayMax));

  // compute target image
  RandomAccessFilm target(ref.getWidth(), ref.getHeight());
  for(size_t y = 0; y != target.getHeight(); ++y)
  {
    for(size_t x = 0; x != target.getWidth(); ++x)
    {
      float e = fabs(displayRef.raster(x,y).luminance() - displayIn.raster(x,y).luminance());
      target.raster(x,y) = Spectrum::white();
      target.raster(x,y).setLuminance(e);
    } // end for x
  } // end for y

  RandomAccessFilm tvi = ref;
  tvi.applyThresholdVersusIntensityFunction();

  // divide by tvi
  target.divideLuminance(tvi, 0);

  // now add everything up
  float sum = 0;
  for(size_t y = 0; y != target.getHeight(); ++y)
  {
    for(size_t x = 0; x != target.getWidth(); ++x)
    {
      sum += target.raster(x,y).luminance();
    } // end for x
  } // end for y
  sum /= (target.getWidth() * target.getHeight());

  std::cerr << "Visual error: " << sum << std::endl;
} // end reportVisualError()

int main(int argc, char **argv)
{
  if(argc < 2)
  {
    std::cerr << "usage: imgstat in.exr [ref.exr]" << std::endl;
    exit(-1);
  } // end if

  RandomAccessFilm in;
  in.readEXR(argv[1]);

  // first compute mean
  Spectrum mean(Spectrum::black());
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      mean += in.raster(x,y);
    } // end for x
  } // end for y

  mean /= (in.getWidth() * in.getHeight());

  // now compute variance
  float variance = 0;
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      float diff2 = in.raster(x,y).luminance() - mean.luminance();
      diff2 *= diff2;
      variance += diff2;
    } // end for x
  } // end for y

  variance /= (in.getWidth() * in.getHeight());

  // now compute skew & kurtosis
  float kurtosisNumerator = 0;
  float skewNumerator = 0;
  float denom = 0;
  for(size_t y = 0; y != in.getHeight(); ++y)
  {
    for(size_t x = 0; x != in.getWidth(); ++x)
    {
      float diff = in.raster(x,y).luminance() - mean.luminance();
      float diff2 = diff * diff;
      float diff3 = diff * diff2;
      float diff4 = diff2 * diff2;

      skewNumerator += diff3;
      kurtosisNumerator += diff4;
      denom += diff2;
    } // end for x
  } // end for y

  skewNumerator *= sqrtf(static_cast<float>(in.getWidth() * in.getHeight()));
  kurtosisNumerator *= (in.getWidth() * in.getHeight());

  float skew = skewNumerator / powf(denom,1.5f);
  float kurtosis = kurtosisNumerator / powf(denom,2.0f) - 3.0f;

  std::cout << "Filename: " << argv[0] << std::endl;
  std::cout << "mean: " << mean << std::endl;
  std::cout << "variance: " << variance << std::endl;
  std::cout << "skew: " << skew << std::endl;
  std::cout << "kurtosis: " << kurtosis << std::endl;

  if(argc > 2)
  {
    RandomAccessFilm ref;
    ref.readEXR(argv[2]);
    if(ref.getWidth() != in.getWidth() ||
       ref.getHeight() != in.getHeight())
    {
      RandomAccessFilm resampled(in.getWidth(), in.getHeight());
      ref.resample(resampled);
      ref = resampled;
    } // end if

    // downsample then upsample the reference
    RandomAccessFilm down(ref.getWidth() / 4, ref.getHeight() / 4);
    ref.resample(down);
    down.resample(ref);

    // first normalize the input's mean luminance to match the reference
    float referenceLuminance = ref.computeMeanLuminance();
    float s = referenceLuminance / in.computeMeanLuminance();
    in.scale(Spectrum(s,s,s));

    // measure squared error
    float squaredError = 0;
    for(size_t y = 0; y != in.getHeight(); ++y)
    {
      for(size_t x = 0; x != in.getWidth(); ++x)
      {
        float r = ref.raster(x,y).luminance();

        if(r == r && r != std::numeric_limits<float>::infinity())
        {
          float i = in.raster(x,y).luminance();
          //i = std::min(powf(i,1.0f / 2.1f), 1.0f);
          //r = std::min(powf(i,1.0f / 2.1f), 1.0f);

          float diff = i - r;
          squaredError += diff * diff;
        } // end if
        else
        {
          std::cerr << "Warning: skipped inf or nan in reference at " << x << "," << y << std::endl;
        } // end else
      } // end for x
    } // end for y
    squaredError /= (in.getWidth() * in.getHeight());

    // measure relative error
    float relError = 0;
    for(size_t y = 0; y != in.getHeight(); ++y)
    {
      for(size_t x = 0; x != in.getWidth(); ++x)
      {
        float r = ref.raster(x,y).luminance();

        if(r == r && r != std::numeric_limits<float>::infinity())
        {

          float i = in.raster(x,y).luminance();

          float diff = fabs(i - r);

          diff /= std::max(0.0005f, r);

          relError += diff;
        } // end if
        else
        {
          std::cerr << "Warning: skipped inf or nan in reference at " << x << "," << y << std::endl;
        } // end else
      } // end for x
    } // end for y
    relError /= (in.getWidth() * in.getHeight());

    std::cout << "squared error: " << squaredError << std::endl;
    std::cout << "relative error: " << relError << std::endl;

    reportVisualError(in, ref);
  } // end if

  return 0;
} // end main()

<|endoftext|>


<commit_before>#include "neonsessionfactory.h"

#include <glibmm/error.h>
#include <glibmm/quark.h>

#include <cstring>

namespace Davix {

const char* proto_support[] = { "http", "https", NULL };
const unsigned int ports[] = { 80 ,443 , 0};

NEONSessionFactory::NEONSessionFactory()
{
    ne_sock_init();
    _ca_check=true;
    _user_auth_callback_data = NULL;
    _call = NULL;
}

NEONSessionFactory::~NEONSessionFactory(){
    Glib::Mutex::Lock lock(_sess_mut);
    for(std::multimap<std::string, ne_session*>::iterator it = _sess_map.begin(); it != _sess_map.end(); ++it){
        ne_session_destroy(it->second);
    }
    ne_sock_exit();
}

Request* NEONSessionFactory::take_request(RequestType typ, const std::string &url){
    std::string host, protocol, path;
    unsigned int port;
    parse_http_neon_url(url, protocol, host, path, &port);
    ne_session* sess = create_recycled_session(protocol, host, port);
    NEONRequest* req = new NEONRequest(this, sess, typ, path, _user_auth_callback_data, _call);
    if(_ca_check == false)
        req->disable_ssl_ca_check();
    return static_cast<Request*>(req);
}

void NEONSessionFactory::set_authentification_controller(void *userdata, davix_auth_callback call){
    _call = call;
    _user_auth_callback_data = userdata;
}

void NEONSessionFactory::release_request(Request *req){
    delete req;
}

void NEONSessionFactory::set_ssl_ca_check(bool chk){
    _ca_check = chk;
}

ne_session* NEONSessionFactory::create_session(const std::string & protocol, const std::string &host, unsigned int port){
    ne_session *se;
    se = ne_session_create(protocol.c_str(), host.c_str(), (int) port);
    return se;
}

ne_session* NEONSessionFactory::create_recycled_session(const std::string &protocol, const std::string &host, unsigned int port){

    ne_session* se= NULL;
    {
        Glib::Mutex::Lock lock(_sess_mut);
        std::multimap<std::string, ne_session*>::iterator it;
        if( (it = _sess_map.find(create_map_keys_from_URL(protocol, host, port))) != _sess_map.end()){
            davix_log_debug("cached ne_session found ! taken from cache ");
            se = it->second;
            _sess_map.erase(it);
            return se;
        }

    }
    davix_log_debug(" no cached ne_session, create a new one ");
    return create_session(protocol, host, port);
}

void NEONSessionFactory::internal_release_session_handle(ne_session* sess){
    Glib::Mutex::Lock lock(_sess_mut);
    std::multimap<std::string, ne_session*>::iterator it;
    const std::string protocol(ne_get_scheme(sess));
    const std::string hostport(ne_get_server_hostport(sess));
    davix_log_debug("add old session to cache %s%s", protocol.c_str(), hostport.c_str());

    _sess_map.insert(std::pair<std::string, ne_session*>(protocol + hostport, sess));
}

void parse_http_neon_url(const std::string &url, std::string &protocol, std::string &host, std::string &path, unsigned int * port){
    char * c_url = (char*) url.c_str();
    char * comma;
    if( (comma = strchr(c_url,':')) != NULL){ // determine protocol
        char ** proto;
        for(proto= (char**) proto_support;
            *proto != NULL;
            ++proto){
            if(strncmp(c_url, *proto, comma - c_url) == 0){
                protocol = std::string(c_url, comma-c_url);
                break;
            }
        }
        // verify if end of list -> failure
        if(*proto != NULL){
           char * second_slash, *first_slash_next = comma +1;
           while(*first_slash_next == '/') // finish prefix
               first_slash_next ++;
           if(*first_slash_next != '\0'){ // if not end, find the path
               second_slash = strchr(first_slash_next, '/');
               std::string host_port;
               if(second_slash == NULL){
                   path = std::string("/");
                   host_port = std::string(first_slash_next);
               }else{
                   path = std::string(second_slash);
                   host_port = std::string(first_slash_next, second_slash- first_slash_next);
               }
               const char * p_host = host_port.c_str();
               const char * comma_port = strchr(p_host, ':');
               *port=0;
               if(comma_port != NULL){
                   *port = (unsigned int) strtoul(comma_port+1,NULL,10);
                    if( *port != ULONG_MAX && *port != 0){
                        host = std::string(p_host, comma_port- p_host);
                        davix_log_debug(" host: %s path: %s protocol: %s port: %d", host.c_str(), path.c_str(), protocol.c_str(), *port);
                        return;
                    }
               }else{
                   *port = (*proto  == (proto_support[0]))?ports[0]:ports[1];
                   host = std::string(p_host);
                   davix_log_debug(" host: %s path: %s protocol: %s port: %d", host.c_str(), path.c_str(), protocol.c_str(), *port);
                   return;
               }

           }

        }
    }
   throw Glib::Error(Glib::Quark("NEONSessionFactory::parse_http_neon_url"), EINVAL, std::string("Invalid url format : ").append(url));
}

std::string create_map_keys_from_URL(const std::string & protocol, const std::string &host, unsigned int port){
    std::ostringstream oss;
    if( (strcmp(protocol.c_str(), "http") ==0 && port == 80)
            || ( strcmp(protocol.c_str(), "https") ==0 && port == 443)){
      oss <<  protocol << host;
    }else
        oss <<  protocol << host << ":" << port;
    std::string res = oss.str();
    davix_log_debug(" creating session keys... %s", res.c_str());
    return res;
}

} // namespace Davix
<commit_msg>-correct compilation problem with gcc 4.1<commit_after>#include "neonsessionfactory.h"

#include <glibmm/error.h>
#include <glibmm/quark.h>
#include <string>
#include <sstream>

#include <cstring>

namespace Davix {

const char* proto_support[] = { "http", "https", NULL };
const unsigned int ports[] = { 80 ,443 , 0};

NEONSessionFactory::NEONSessionFactory()
{
    ne_sock_init();
    _ca_check=true;
    _user_auth_callback_data = NULL;
    _call = NULL;
}

NEONSessionFactory::~NEONSessionFactory(){
    Glib::Mutex::Lock lock(_sess_mut);
    for(std::multimap<std::string, ne_session*>::iterator it = _sess_map.begin(); it != _sess_map.end(); ++it){
        ne_session_destroy(it->second);
    }
    ne_sock_exit();
}

Request* NEONSessionFactory::take_request(RequestType typ, const std::string &url){
    std::string host, protocol, path;
    unsigned int port;
    parse_http_neon_url(url, protocol, host, path, &port);
    ne_session* sess = create_recycled_session(protocol, host, port);
    NEONRequest* req = new NEONRequest(this, sess, typ, path, _user_auth_callback_data, _call);
    if(_ca_check == false)
        req->disable_ssl_ca_check();
    return static_cast<Request*>(req);
}

void NEONSessionFactory::set_authentification_controller(void *userdata, davix_auth_callback call){
    _call = call;
    _user_auth_callback_data = userdata;
}

void NEONSessionFactory::release_request(Request *req){
    delete req;
}

void NEONSessionFactory::set_ssl_ca_check(bool chk){
    _ca_check = chk;
}

ne_session* NEONSessionFactory::create_session(const std::string & protocol, const std::string &host, unsigned int port){
    ne_session *se;
    se = ne_session_create(protocol.c_str(), host.c_str(), (int) port);
    return se;
}

ne_session* NEONSessionFactory::create_recycled_session(const std::string &protocol, const std::string &host, unsigned int port){

    ne_session* se= NULL;
    {
        Glib::Mutex::Lock lock(_sess_mut);
        std::multimap<std::string, ne_session*>::iterator it;
        if( (it = _sess_map.find(create_map_keys_from_URL(protocol, host, port))) != _sess_map.end()){
            davix_log_debug("cached ne_session found ! taken from cache ");
            se = it->second;
            _sess_map.erase(it);
            return se;
        }

    }
    davix_log_debug(" no cached ne_session, create a new one ");
    return create_session(protocol, host, port);
}

void NEONSessionFactory::internal_release_session_handle(ne_session* sess){
    Glib::Mutex::Lock lock(_sess_mut);
    std::multimap<std::string, ne_session*>::iterator it;
    const std::string protocol(ne_get_scheme(sess));
    const std::string hostport(ne_get_server_hostport(sess));
    davix_log_debug("add old session to cache %s%s", protocol.c_str(), hostport.c_str());

    _sess_map.insert(std::pair<std::string, ne_session*>(protocol + hostport, sess));
}

void parse_http_neon_url(const std::string &url, std::string &protocol, std::string &host, std::string &path, unsigned int * port){
    char * c_url = (char*) url.c_str();
    char * comma;
    if( (comma = strchr(c_url,':')) != NULL){ // determine protocol
        char ** proto;
        for(proto= (char**) proto_support;
            *proto != NULL;
            ++proto){
            if(strncmp(c_url, *proto, comma - c_url) == 0){
                protocol = std::string(c_url, comma-c_url);
                break;
            }
        }
        // verify if end of list -> failure
        if(*proto != NULL){
           char * second_slash, *first_slash_next = comma +1;
           while(*first_slash_next == '/') // finish prefix
               first_slash_next ++;
           if(*first_slash_next != '\0'){ // if not end, find the path
               second_slash = strchr(first_slash_next, '/');
               std::string host_port;
               if(second_slash == NULL){
                   path = std::string("/");
                   host_port = std::string(first_slash_next);
               }else{
                   path = std::string(second_slash);
                   host_port = std::string(first_slash_next, second_slash- first_slash_next);
               }
               const char * p_host = host_port.c_str();
               const char * comma_port = strchr(p_host, ':');
               *port=0;
               if(comma_port != NULL){
                   *port = (unsigned int) strtoul(comma_port+1,NULL,10);
                    if( *port != ULONG_MAX && *port != 0){
                        host = std::string(p_host, comma_port- p_host);
                        davix_log_debug(" host: %s path: %s protocol: %s port: %d", host.c_str(), path.c_str(), protocol.c_str(), *port);
                        return;
                    }
               }else{
                   *port = (*proto  == (proto_support[0]))?ports[0]:ports[1];
                   host = std::string(p_host);
                   davix_log_debug(" host: %s path: %s protocol: %s port: %d", host.c_str(), path.c_str(), protocol.c_str(), *port);
                   return;
               }

           }

        }
    }
   throw Glib::Error(Glib::Quark("NEONSessionFactory::parse_http_neon_url"), EINVAL, std::string("Invalid url format : ").append(url));
}

std::string create_map_keys_from_URL(const std::string & protocol, const std::string &host, unsigned int port){
    std::ostringstream oss;
    if( (strcmp(protocol.c_str(), "http") ==0 && port == 80)
            || ( strcmp(protocol.c_str(), "https") ==0 && port == 443)){
      oss <<  protocol << host;
    }else
        oss <<  protocol << host << ":" << port;
    std::string res = oss.str();
    davix_log_debug(" creating session keys... %s", res.c_str());
    return res;
}

} // namespace Davix
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef STATIC_SOCKET_ADDRESS_HXX
#define STATIC_SOCKET_ADDRESS_HXX

#include <sys/socket.h>
#include <stddef.h>

struct sockaddr;
class Error;

class StaticSocketAddress {
    friend class SocketDescriptor;

    socklen_t size;
    struct sockaddr_storage address;

public:
    StaticSocketAddress() = default;

    constexpr size_t GetCapacity() const {
        return sizeof(address);
    }

    constexpr size_t GetSize() const {
        return size;
    }

    operator struct sockaddr *() {
        return reinterpret_cast<struct sockaddr *>(&address);
    }

    operator const struct sockaddr *() const {
        return reinterpret_cast<const struct sockaddr *>(&address);
    }

    int GetFamily() const {
        return address.ss_family;
    }

    bool IsDefined() const {
        return GetFamily() != AF_UNSPEC;
    }

    void Clear() {
        address.ss_family = AF_UNSPEC;
    }

    /**
     * Make this a "local" address (UNIX domain socket).
     */
    void SetLocal(const char *path);

    bool Lookup(const char *host, int default_port, int socktype,
                Error &error);
};

#endif
<commit_msg>StaticSocketAddress: add SocketAddress cast operator<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef STATIC_SOCKET_ADDRESS_HXX
#define STATIC_SOCKET_ADDRESS_HXX

#include "SocketAddress.hxx"

#include <stddef.h>

struct sockaddr;
class Error;

class StaticSocketAddress {
    friend class SocketDescriptor;

    socklen_t size;
    struct sockaddr_storage address;

public:
    StaticSocketAddress() = default;

    constexpr size_t GetCapacity() const {
        return sizeof(address);
    }

    constexpr size_t GetSize() const {
        return size;
    }

    operator SocketAddress() const {
        return SocketAddress(reinterpret_cast<const struct sockaddr *>(&address),
                             size);
    }

    operator struct sockaddr *() {
        return reinterpret_cast<struct sockaddr *>(&address);
    }

    operator const struct sockaddr *() const {
        return reinterpret_cast<const struct sockaddr *>(&address);
    }

    int GetFamily() const {
        return address.ss_family;
    }

    bool IsDefined() const {
        return GetFamily() != AF_UNSPEC;
    }

    void Clear() {
        address.ss_family = AF_UNSPEC;
    }

    /**
     * Make this a "local" address (UNIX domain socket).
     */
    void SetLocal(const char *path);

    bool Lookup(const char *host, int default_port, int socktype,
                Error &error);
};

#endif
<|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */

#include "maintranslations.h"

static const DcpCategoryInfo
AccountsAndApplicationsElements[] =
{
    {
        //% "Service accounts"
        QT_TRID_NOOP ("qtn_sett_main_account"),
        "Service accounts",
        PageHandle::ServiceAccounts,
        NULL
    },
    {
        //% "Applications"
        QT_TRID_NOOP ("qtn_sett_main_application"),
        "Applications",
        PageHandle::Applications,
        NULL
    },
    {
        // The last element must have the .titleId == 0
	    0, 0, PageHandle::NOPAGE, NULL
    }
};

/*
 * The applet categories that will be shown in the main window of the control
 * panel.
 */
const DcpCategoryInfo
DcpMain::CategoryInfos[] =
{
    {
        //% "Look & Feel"
	    QT_TRID_NOOP ("qtn_sett_main_look"),
    	"Look & Feel",
    	PageHandle::LOOKANDFEEL,
        NULL
    },
    {
        //% "Sounds"
        QT_TRID_NOOP ("qtn_sett_main_sound"),
        "Sound",
        PageHandle::SOUND,
        NULL
    },
    {
        //% "Connectivity"
        QT_TRID_NOOP ("qtn_sett_main_connectivity"),
        "Connectivity",
        PageHandle::CONNECTIVITY,
        NULL
    },
    {
        //% "Regional settings"
        QT_TRID_NOOP ("qtn_sett_main_region"),
        "Regional settings",
        PageHandle::REGIONALSETTING,
        NULL
    },
    {
        //% "Device utilities"
        QT_TRID_NOOP ("qtn_sett_main_device"),
        "Device utilities",
        PageHandle::DEVICEUTILITIES,
        NULL
    },
    {
        //% "Device system"
        QT_TRID_NOOP ("qtn_sett_main_data"),
        "Device system",
        PageHandle::DEVICESYSTEM,
        NULL
    },
    {
        //% "Accounts & Applications"
        QT_TRID_NOOP ("qtn_sett_main_combined"),
        "Accounts & Applications",
        PageHandle::ACCOUNTSANDAPPLICATIONS,
        AccountsAndApplicationsElements
    },
    {
        // The last element must have the .titleId == 0
	    0, 0, PageHandle::NOPAGE, NULL
    }
};

//% "Settings"
const char* DcpMain::settingsTitleId = QT_TRID_NOOP("qtn_sett_main_title");

//% "Most recently used"
const char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP("qtn_sett_main_most");

//% "Exit"
const char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP("qtn_comm_exit");

/*!
 * Will find a DcpCategoryInfo by the page type id. Uses recirsive search to
 * find sub-categories.
 */
const DcpCategoryInfo *
dcp_find_category_info (
        PageHandle::PageTypeId   id,
        const DcpCategoryInfo   *info)
{
    /*
     * The default place to find infos.
     */
    if (info == NULL) {
        info = DcpMain::CategoryInfos;
    }

    for (int n = 0; ; ++n) {
        /*
         * The end of the array.
         */
        if (info[n].titleId == 0) {
            return 0;
        }

        /*
         * If found it.
         */
        if (info[n].subPageId == id)
            return &info[n];

        /*
         * If we have a chance to search recursively.
         */
        if (info[n].staticElements != NULL) {
            const DcpCategoryInfo *retval;

            retval = dcp_find_category_info (id, info[n].staticElements);
            if (retval)
                return retval;
        }
    }

    return NULL;
}
<commit_msg>updated category names<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */

#include "maintranslations.h"

static const DcpCategoryInfo
AccountsAndApplicationsElements[] =
{
    {
        //% "Service accounts"
        QT_TRID_NOOP ("qtn_sett_main_account"),
        "Service accounts",
        PageHandle::ServiceAccounts,
        NULL
    },
    {
        //% "Applications"
        QT_TRID_NOOP ("qtn_sett_main_application"),
        "Applications",
        PageHandle::Applications,
        NULL
    },
    {
        // The last element must have the .titleId == 0
	    0, 0, PageHandle::NOPAGE, NULL
    }
};

/*
 * The applet categories that will be shown in the main window of the control
 * panel.
 */
const DcpCategoryInfo
DcpMain::CategoryInfos[] =
{
    {
        //% "Look & Feel"
	    QT_TRID_NOOP ("qtn_sett_main_look"),
    	"Look & Feel",
    	PageHandle::LOOKANDFEEL,
        NULL
    },
    {
        //% "Connectivity"
        QT_TRID_NOOP ("qtn_sett_main_connectivity"),
        "Connectivity",
        PageHandle::CONNECTIVITY,
        NULL
    },
    {
        //% "Language & Region"
        QT_TRID_NOOP ("qtn_sett_main_region"),
        "Language & Region",
        PageHandle::REGIONALSETTING,
        NULL
    },
        {
        //% "Device system"
        QT_TRID_NOOP ("qtn_sett_main_data"),
        "Device system",
        PageHandle::DEVICESYSTEM,
        NULL
    },
    {
        //% "Accounts & Applications"
        QT_TRID_NOOP ("qtn_sett_main_combined"),
        "Accounts & Applications",
        PageHandle::ACCOUNTSANDAPPLICATIONS,
        AccountsAndApplicationsElements
    },
    {
        // The last element must have the .titleId == 0
	    0, 0, PageHandle::NOPAGE, NULL
    }
};

//% "Settings"
const char* DcpMain::settingsTitleId = QT_TRID_NOOP("qtn_sett_main_title");

//% "Most recently used"
const char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP("qtn_sett_main_most");

//% "Exit"
const char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP("qtn_comm_exit");

/*!
 * Will find a DcpCategoryInfo by the page type id. Uses recirsive search to
 * find sub-categories.
 */
const DcpCategoryInfo *
dcp_find_category_info (
        PageHandle::PageTypeId   id,
        const DcpCategoryInfo   *info)
{
    /*
     * The default place to find infos.
     */
    if (info == NULL) {
        info = DcpMain::CategoryInfos;
    }

    for (int n = 0; ; ++n) {
        /*
         * The end of the array.
         */
        if (info[n].titleId == 0) {
            return 0;
        }

        /*
         * If found it.
         */
        if (info[n].subPageId == id)
            return &info[n];

        /*
         * If we have a chance to search recursively.
         */
        if (info[n].staticElements != NULL) {
            const DcpCategoryInfo *retval;

            retval = dcp_find_category_info (id, info[n].staticElements);
            if (retval)
                return retval;
        }
    }

    return NULL;
}
<|endoftext|>


<commit_before>#include "kernel.h"
#include "raster.h"
#include "rastercoverage.h"
#include "pixeliterator.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "numericdomain.h"
#include "numericitem.h"
#include "numericitemrange.h"
#include "ilwisoperation.h"
#include "indexslicer.h"

using namespace Ilwis;

IndexSlicer::IndexSlicer(const IRasterCoverage &cov) : _raster(cov)
{
}

void IndexSlicer::grid(const IRasterCoverage &cov)
{
    _raster = cov;
}

IRasterCoverage IndexSlicer::operator()(const QString &item)
{
    IDomain indexDomain = _raster->datadef().domain(DataDefinition::daLAYERINDEX);
    if (!indexDomain.isValid())
        return IRasterCoverage();
    if ( hasType(indexDomain->valueType(), itNUMERIC)) {

        QString basename = makeBaseName();

        double index;
        if ( indexDomain->valueType() == itNUMERICITEM)  {
            index = _raster->layerIndex(item);
        } else if ( hasType(indexDomain->valueType(),itNUMBER)) {
            index  = findIndexNumber(indexDomain, item.toDouble());
        }
        if ( index == rUNDEF){
            ERROR2(ERR_INVALID_PROPERTY_FOR_2, TR("item boundary"), TR("Index slicing"));
            return IRasterCoverage();
        }
        QString cname;
        QString expr = makeExpression(index, basename, cname);

        IRasterCoverage mp = Operation::calculate<IRasterCoverage>(cname,expr);
        if ( mp.isValid())
            return mp;
    }
    return IRasterCoverage();
}

QString IndexSlicer::makeBaseName() const {
    QString basename = _raster->name();
    int ind = 0;
    if( (ind=basename.lastIndexOf(".")) != -1){
        basename = basename.left(ind);
    }
    return basename;
}

QString IndexSlicer::makeExpression(double index, const QString& basename, QString& cname) {
    double rest1 = index - (int)index;
    QString expr =  _raster->datadef().range(DataDefinition::daLAYERINDEX)->interpolation();
    bool isContinous = _raster->datadef().range(DataDefinition::daLAYERINDEX)->isContinuous();
    if ( std::abs(rest1) > EPS8 && isContinous) {
        int lowerIndex = std::floor(index);
        double rest2 = 1.0 - rest1;
        cname = QString("%1_%2_%3").arg(basename).arg(lowerIndex).arg(lowerIndex+1);
        expr = cname + "=" + expr.arg(QString("%1*%2[%3]")
                                      .arg(rest2)
                                      .arg(_raster->name())
                                      .arg(lowerIndex))
                .arg(QString("%1*%2[%3]").
                     arg(rest1).
                     arg(_raster->name()).
                     arg(lowerIndex+1));
    } else {
        cname = QString("%1_%2").arg(basename).arg((int)index);
        expr = QString("%1=%2[%3]").arg(cname).arg( _raster->name()).arg((int)index);

    }
    return expr;
}

double IndexSlicer::findIndexNumber(const IDomain& indexDomain, double itemIndex) const{
    INumericDomain numdom = indexDomain.get<NumericDomain>();
    SPNumericRange numrange = numdom->range<NumericRange>();
    if ( numrange->contains(itemIndex))
        return itemIndex;
    return rUNDEF;
}

double IndexSlicer::findIndexNumericalItem(const IDomain& indexDomain, const QString& itemIndex) const{
//    INumericItemDomain numdom = indexDomain.get<NumericItemDomain>();
//    SPNumericItemRange numrange = numdom->range<NumericItemRange>();
//    //double index1 = _raster->index(indexItem);
//    double index1 = numrange->index(itemIndex);

//    return index1;
}
<commit_msg>added initialization<commit_after>#include "kernel.h"
#include "raster.h"
#include "rastercoverage.h"
#include "pixeliterator.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "domainitem.h"
#include "itemdomain.h"
#include "numericdomain.h"
#include "numericitem.h"
#include "numericitemrange.h"
#include "ilwisoperation.h"
#include "indexslicer.h"

using namespace Ilwis;

IndexSlicer::IndexSlicer(const IRasterCoverage &cov) : _raster(cov)
{
}

void IndexSlicer::grid(const IRasterCoverage &cov)
{
    _raster = cov;
}

IRasterCoverage IndexSlicer::operator()(const QString &item)
{
    IDomain indexDomain = _raster->datadef().domain(DataDefinition::daLAYERINDEX);
    if (!indexDomain.isValid())
        return IRasterCoverage();
    if ( hasType(indexDomain->valueType(), itNUMERIC)) {

        QString basename = makeBaseName();

        double index = rUNDEF;
        if ( indexDomain->valueType() == itNUMERICITEM)  {
            index = _raster->layerIndex(item);
        } else if ( hasType(indexDomain->valueType(),itNUMBER)) {
            index  = findIndexNumber(indexDomain, item.toDouble());
        }
        if ( index == rUNDEF){
            ERROR2(ERR_INVALID_PROPERTY_FOR_2, TR("item boundary"), TR("Index slicing"));
            return IRasterCoverage();
        }
        QString cname;
        QString expr = makeExpression(index, basename, cname);

        IRasterCoverage mp = Operation::calculate<IRasterCoverage>(cname,expr);
        if ( mp.isValid())
            return mp;
    }
    return IRasterCoverage();
}

QString IndexSlicer::makeBaseName() const {
    QString basename = _raster->name();
    int ind = 0;
    if( (ind=basename.lastIndexOf(".")) != -1){
        basename = basename.left(ind);
    }
    return basename;
}

QString IndexSlicer::makeExpression(double index, const QString& basename, QString& cname) {
    double rest1 = index - (int)index;
    QString expr =  _raster->datadef().range(DataDefinition::daLAYERINDEX)->interpolation();
    bool isContinous = _raster->datadef().range(DataDefinition::daLAYERINDEX)->isContinuous();
    if ( std::abs(rest1) > EPS8 && isContinous) {
        int lowerIndex = std::floor(index);
        double rest2 = 1.0 - rest1;
        cname = QString("%1_%2_%3").arg(basename).arg(lowerIndex).arg(lowerIndex+1);
        expr = cname + "=" + expr.arg(QString("%1*%2[%3]")
                                      .arg(rest2)
                                      .arg(_raster->name())
                                      .arg(lowerIndex))
                .arg(QString("%1*%2[%3]").
                     arg(rest1).
                     arg(_raster->name()).
                     arg(lowerIndex+1));
    } else {
        cname = QString("%1_%2").arg(basename).arg((int)index);
        expr = QString("%1=%2[%3]").arg(cname).arg( _raster->name()).arg((int)index);

    }
    return expr;
}

double IndexSlicer::findIndexNumber(const IDomain& indexDomain, double itemIndex) const{
    INumericDomain numdom = indexDomain.get<NumericDomain>();
    SPNumericRange numrange = numdom->range<NumericRange>();
    if ( numrange->contains(itemIndex))
        return itemIndex;
    return rUNDEF;
}

double IndexSlicer::findIndexNumericalItem(const IDomain& indexDomain, const QString& itemIndex) const{
//    INumericItemDomain numdom = indexDomain.get<NumericItemDomain>();
//    SPNumericItemRange numrange = numdom->range<NumericItemRange>();
//    //double index1 = _raster->index(indexItem);
//    double index1 = numrange->index(itemIndex);

//    return index1;
}
<|endoftext|>


<commit_before>/**********************************************************************
 *
 *	FILE:			LOD.cpp
 *
 *	DESCRIPTION:	Read/Write osg::LOD in binary format to disk.
 *
 *	CREATED BY:		Auto generated by iveGenerate
 *					and later modified by Rune Schmidt Jensen.
 *
 *	HISTORY:		Created 24.3.2003
 *
 *	Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "PagedLOD.h"
#include "Node.h"

using namespace ive;

void PagedLOD::write(DataOutputStream* out){
	// Write LOD's identification.
	out->writeInt(IVEPAGEDLOD);
	// If the osg class is inherited by any other class we should also write this to file.

        osg::Node* node = dynamic_cast<osg::Node*>(this);
        if(node){
            static_cast<ive::Node*>(node)->write(out);
        }
        else
		throw Exception("PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD.");

        unsigned int numChildrenToWriteOut = 0;

        int i;
        for(i=0; i<(int)getNumFileNames();++i)
        {
            if (getFileName(i).empty())
            {
                ++numChildrenToWriteOut;
            }
        }

	// Write Group's properties.
        // Write number of children.
        out->writeInt(numChildrenToWriteOut);
        // Write children.
        for(i=0; i<(int)getNumChildren(); i++){
            if (getFileName(i).empty())
            {
                osg::Node* child = getChild(i);
                out->writeNode(child);
            }
        }

        // LOD properties
	// Write centermode
	out->writeInt(getCenterMode());
	out->writeVec3(getCenter());
        // Write rangelist
	int size = getNumRanges();
	out->writeInt(size);
	for(i=0;i<size;i++){
		out->writeFloat(getMinRange(i));
		out->writeFloat(getMaxRange(i));
	}

        // PagedLOD properties
	size = getNumFileNames();
	out->writeInt(size);
	for(i=0;i<size;i++){
		out->writeString(getFileName(i));
	}
}

void PagedLOD::read(DataInputStream* in){
	// Peek on LOD's identification.
	int id = in->peekInt();
	if(id == IVEPAGEDLOD){
		// Read LOD's identification.
		id = in->readInt();
		// If the osg class is inherited by any other class we should also read this from file.
                osg::Node* node = dynamic_cast<osg::Node*>(this);
                if(node){
                    ((ive::Node*)(node))->read(in);
                }
                else
                    throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node.");

                // Read groups properties.
                // Read number of children.
                int size = in->readInt();
                // Read children.
                for(int i=0; i<size; i++)
                {
                    addChild(in->readNode());
                }

		// Read centermode
		setCenterMode((osg::LOD::CenterMode)in->readInt());
		setCenter(in->readVec3());
		// Read rangelist
		size = in->readInt();
		for(int i=0;i<size;i++){
			float min = in->readFloat();
			float max = in->readFloat();
			setRange(i, min, max);
		}

		size = in->readInt();
		for(int i=0;i<size;i++){
			setFileName(i, in->readString());
		}
	}
	else{
		throw Exception("LOD::read(): Expected LOD identification.");
	}
}
<commit_msg>Fixed VC6 for scoping problem in ive plugin.<commit_after>/**********************************************************************
 *
 *	FILE:			LOD.cpp
 *
 *	DESCRIPTION:	Read/Write osg::LOD in binary format to disk.
 *
 *	CREATED BY:		Auto generated by iveGenerate
 *					and later modified by Rune Schmidt Jensen.
 *
 *	HISTORY:		Created 24.3.2003
 *
 *	Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "PagedLOD.h"
#include "Node.h"

using namespace ive;

void PagedLOD::write(DataOutputStream* out){
	// Write LOD's identification.
	out->writeInt(IVEPAGEDLOD);
	// If the osg class is inherited by any other class we should also write this to file.

        osg::Node* node = dynamic_cast<osg::Node*>(this);
        if(node){
            static_cast<ive::Node*>(node)->write(out);
        }
        else
		throw Exception("PagedLOD::write(): Could not cast this osg::PagedLOD to an osg::LOD.");

        unsigned int numChildrenToWriteOut = 0;

        int i;
        for(i=0; i<(int)getNumFileNames();++i)
        {
            if (getFileName(i).empty())
            {
                ++numChildrenToWriteOut;
            }
        }

	// Write Group's properties.
        // Write number of children.
        out->writeInt(numChildrenToWriteOut);
        // Write children.
        for(i=0; i<(int)getNumChildren(); i++){
            if (getFileName(i).empty())
            {
                osg::Node* child = getChild(i);
                out->writeNode(child);
            }
        }

        // LOD properties
	// Write centermode
	out->writeInt(getCenterMode());
	out->writeVec3(getCenter());
        // Write rangelist
	int size = getNumRanges();
	out->writeInt(size);
	for(i=0;i<size;i++){
		out->writeFloat(getMinRange(i));
		out->writeFloat(getMaxRange(i));
	}

        // PagedLOD properties
	size = getNumFileNames();
	out->writeInt(size);
	for(i=0;i<size;i++){
		out->writeString(getFileName(i));
	}
}

void PagedLOD::read(DataInputStream* in){
	// Peek on LOD's identification.
	int id = in->peekInt();
	if(id == IVEPAGEDLOD){
		// Read LOD's identification.
		id = in->readInt();
		// If the osg class is inherited by any other class we should also read this from file.
                osg::Node* node = dynamic_cast<osg::Node*>(this);
                if(node){
                    ((ive::Node*)(node))->read(in);
                }
                else
                    throw Exception("Group::read(): Could not cast this osg::Group to an osg::Node.");

                // Read groups properties.
                // Read number of children.
                int size = in->readInt();
                // Read children.
		int i;
                for(i=0; i<size; i++)
                {
                    addChild(in->readNode());
                }

		// Read centermode
		setCenterMode((osg::LOD::CenterMode)in->readInt());
		setCenter(in->readVec3());
		// Read rangelist
		size = in->readInt();
		for(i=0;i<size;i++){
			float min = in->readFloat();
			float max = in->readFloat();
			setRange(i, min, max);
		}

		size = in->readInt();
		for(i=0;i<size;i++){
			setFileName(i, in->readString());
		}
	}
	else{
		throw Exception("LOD::read(): Expected LOD identification.");
	}
}
<|endoftext|>