<commit_before>//---------------------------------------------------------------------------
//      $Id$
//    Version: $Name$
//
//    Copyright (C) 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <deal.II/base/mpi.h>
#include <deal.II/base/utilities.h>
#include <deal.II/base/exceptions.h>

#include <cstddef>
#include <iostream>

#ifdef DEAL_II_USE_TRILINOS
#  ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#    include <Epetra_MpiComm.h>
#    include <deal.II/lac/vector_memory.h>
#    include <deal.II/lac/trilinos_vector.h>
#    include <deal.II/lac/trilinos_block_vector.h>
#  endif
#endif

#ifdef DEAL_II_USE_PETSC
#  ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#    include <petscsys.h>
#include <deal.II/lac/petsc_block_vector.h>
#include <deal.II/lac/petsc_parallel_block_vector.h>
#include <deal.II/lac/petsc_vector.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#  endif
#endif

DEAL_II_NAMESPACE_OPEN

namespace Utilities
{

  namespace MPI
  {
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
                                // Unfortunately, we have to work
                                // around an oddity in the way PETSc
                                // and some gcc versions interact. If
                                // we use PETSc's MPI dummy
                                // implementation, it expands the
                                // calls to the two MPI functions
                                // basically as ``(n_jobs=1, 0)'',
                                // i.e. it assigns the number one to
                                // the variable holding the number of
                                // jobs, and then uses the comma
                                // operator to let the entire
                                // expression have the value zero. The
                                // latter is important, since
                                // ``MPI_Comm_size'' returns an error
                                // code that we may want to check (we
                                // don't here, but one could in
                                // principle), and the trick with the
                                // comma operator makes sure that both
                                // the number of jobs is correctly
                                // assigned, and the return value is
                                // zero. Unfortunately, if some recent
                                // versions of gcc detect that the
                                // comma expression just stands by
                                // itself, i.e. the result is not
                                // assigned to another variable, then
                                // they warn ``right-hand operand of
                                // comma has no effect''. This
                                // unwanted side effect can be
                                // suppressed by casting the result of
                                // the entire expression to type
                                // ``void'' -- not beautiful, but
                                // helps calming down unwarranted
                                // compiler warnings...
    unsigned int n_mpi_processes (const MPI_Comm &mpi_communicator)
    {
      int n_jobs=1;
      (void) MPI_Comm_size (mpi_communicator, &n_jobs);

      return n_jobs;
    }

    unsigned int this_mpi_process (const MPI_Comm &mpi_communicator)
    {
      int rank=0;
      (void) MPI_Comm_rank (mpi_communicator, &rank);

      return rank;
    }

    MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
    {
      MPI_Comm new_communicator;
      MPI_Comm_dup (mpi_communicator, &new_communicator);
      return new_communicator;
    }

    std::vector<unsigned int>
    compute_point_to_point_communication_pattern (const MPI_Comm & mpi_comm,
                                                  const std::vector<unsigned int> & destinations)
    {
      unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);
      unsigned int n_procs = Utilities::MPI::n_mpi_processes(mpi_comm);

      for (unsigned int i=0; i<destinations.size(); ++i)
        {
          Assert (destinations[i] < n_procs,
                  ExcIndexRange (destinations[i], 0, n_procs));
          Assert (destinations[i] != myid,
                  ExcMessage ("There is no point in communicating with ourselves."));
        }

                                       // let all processors
                                       // communicate the maximal
                                       // number of destinations they
                                       // have
      const unsigned int max_n_destinations
        = Utilities::MPI::max (destinations.size(), mpi_comm);

                                       // now that we know the number
                                       // of data packets every
                                       // processor wants to send, set
                                       // up a buffer with the maximal
                                       // size and copy our
                                       // destinations in there,
                                       // padded with -1's
      std::vector<unsigned int> my_destinations(max_n_destinations,
                                                numbers::invalid_unsigned_int);
      std::copy (destinations.begin(), destinations.end(),
                 my_destinations.begin());

                                       // now exchange these (we could
                                       // communicate less data if we
                                       // used MPI_Allgatherv, but
                                       // we'd have to communicate
                                       // my_n_destinations to all
                                       // processors in this case,
                                       // which is more expensive than
                                       // the reduction operation
                                       // above in MPI_Allreduce)
      std::vector<unsigned int> all_destinations (max_n_destinations * n_procs);
      MPI_Allgather (&my_destinations[0], max_n_destinations, MPI_UNSIGNED,
                     &all_destinations[0], max_n_destinations, MPI_UNSIGNED,
                     mpi_comm);

                                       // now we know who is going to
                                       // communicate with
                                       // whom. collect who is going
                                       // to communicate with us!
      std::vector<unsigned int> origins;
      for (unsigned int i=0; i<n_procs; ++i)
        for (unsigned int j=0; j<max_n_destinations; ++j)
          if (all_destinations[i*max_n_destinations + j] == myid)
            origins.push_back (i);
          else if (all_destinations[i*max_n_destinations + j] ==
                   numbers::invalid_unsigned_int)
            break;

      return origins;
    }

    namespace
    {
                                       // custom MIP_Op for
                                       // calculate_collective_mpi_min_max_avg
      void max_reduce ( const void * in_lhs_,
                        void * inout_rhs_,
                        int * len,
                        MPI_Datatype * )
      {
        const MinMaxAvg * in_lhs = static_cast<const MinMaxAvg*>(in_lhs_);
        MinMaxAvg * inout_rhs = static_cast<MinMaxAvg*>(inout_rhs_);

        Assert(*len==1, ExcInternalError());

        inout_rhs->sum += in_lhs->sum;
        if (inout_rhs->min>in_lhs->min)
          {
            inout_rhs->min = in_lhs->min;
            inout_rhs->min_index = in_lhs->min_index;
          }
        else if (inout_rhs->min == in_lhs->min)
          { // choose lower cpu index when tied to make operator cumutative
            if (inout_rhs->min_index > in_lhs->min_index)
              inout_rhs->min_index = in_lhs->min_index;
          }

        if (inout_rhs->max < in_lhs->max)
          {
          inout_rhs->max = in_lhs->max;
          inout_rhs->max_index = in_lhs->max_index;
          }
        else if (inout_rhs->max == in_lhs->max)
          { // choose lower cpu index when tied to make operator cumutative
            if (inout_rhs->max_index > in_lhs->max_index)
              inout_rhs->max_index = in_lhs->max_index;
          }
      }
    }

    MinMaxAvg
    min_max_avg(const double my_value,
                const MPI_Comm &mpi_communicator)
    {
      MinMaxAvg result;

      const unsigned int my_id
        = dealii::Utilities::MPI::this_mpi_process(mpi_communicator);
      const unsigned int numproc
        = dealii::Utilities::MPI::n_mpi_processes(mpi_communicator);

      MPI_Op op;
      int ierr = MPI_Op_create((MPI_User_function *)&max_reduce, true, &op);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      MinMaxAvg in;
      in.sum = in.min = in.max = my_value;
      in.min_index = in.max_index = my_id;

      MPI_Datatype type;
      int lengths[]={3,2};
      MPI_Aint displacements[]={0,offsetof(MinMaxAvg, min_index)};
      MPI_Datatype types[]={MPI_DOUBLE, MPI_INT};

      ierr = MPI_Type_struct(2, lengths, displacements, types, &type);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Type_commit(&type);
      ierr = MPI_Allreduce (&in, &result, 1, type, op, mpi_communicator);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Type_free (&type);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Op_free(&op);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      result.avg = result.sum / numproc;

      return result;
    }

#else

    unsigned int n_mpi_processes (const MPI_Comm &)
    {
      return 1;
    }

    unsigned int this_mpi_process (const MPI_Comm &)
    {
      return 0;
    }

    MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
    {
      return mpi_communicator;
    }

    MinMaxAvg
    min_max_avg(const double my_value,
                const MPI_Comm &)
    {
      MinMaxAvg result;

      result.sum = my_value;
      result.avg = my_value;
      result.min = my_value;
      result.max = my_value;
      result.min_index = 0;
      result.max_index = 0;

      return result;
    }

#endif

    MPI_InitFinalize::MPI_InitFinalize (int    &argc,
                                        char** &argv)
                    :
                    owns_mpi (true)
    {
      static bool constructor_has_already_run = false;
      Assert (constructor_has_already_run == false,
              ExcMessage ("You can only create a single object of this class "
                          "in a program since it initializes the MPI system."));

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
      // if we have PETSc, we will initialize it and let it handle MPI.
      // Otherwise, we will do it.
#ifdef DEAL_II_USE_PETSC
      PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
#else
      int MPI_has_been_started = 0;
      MPI_Initialized(&MPI_has_been_started);
      AssertThrow (MPI_has_been_started == 0,
                   ExcMessage ("MPI error. You can only start MPI once!"));

      int mpi_err;
      mpi_err = MPI_Init (&argc, &argv);
      AssertThrow (mpi_err == 0,
                   ExcMessage ("MPI could not be initialized."));
#endif
#else
                                       // make sure the compiler doesn't warn
                                       // about these variables
      (void)argc;
      (void)argv;
#endif

      constructor_has_already_run = true;
    }

    MPI_InitFinalize::~MPI_InitFinalize()
    {
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI

                                       // make memory pool release all
                                       // vectors that are no longer
                                       // used at this point. this is
                                       // relevant because the static
                                       // object destructors run for
                                       // these vectors at the end of
                                       // the program would run after
                                       // MPI_Finalize is called,
                                       // leading to errors
                                       //
#  if defined(DEAL_II_USE_TRILINOS) && !defined(__APPLE__)
                                       // TODO: On Mac OS X, shared libs can
                                       // only depend on other libs listed
                                       // later on the command line. This
                                       // means that libbase can't depend on
                                       // liblac, and we can't destroy the
                                       // memory pool here as long as we have
                                       // separate libraries. Consequently,
                                       // the #ifdef above. Deal will then
                                       // just continue to seg fault upon
                                       // completion of main()
      GrowingVectorMemory<TrilinosWrappers::MPI::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<TrilinosWrappers::MPI::BlockVector>
        ::release_unused_memory ();
#  endif

				       // Same for PETSc.
#ifdef DEAL_II_USE_PETSC
      GrowingVectorMemory<PETScWrappers::MPI::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::MPI::BlockVector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::BlockVector>
        ::release_unused_memory ();

				       // now end PETSc.
      PetscFinalize();
#else

      int mpi_err = 0;

      int MPI_has_been_started = 0;
      MPI_Initialized(&MPI_has_been_started);
      if (Utilities::System::program_uses_mpi() == true && owns_mpi == true &&
          MPI_has_been_started != 0)
        {
          if (std::uncaught_exception())
            {
              std::cerr << "ERROR: Uncaught exception in MPI_InitFinalize on proc "
                        << this_mpi_process(MPI_COMM_WORLD)
                        << ". Skipping MPI_Finalize() to avoid a deadlock."
                        << std::endl;
            }
          else
            mpi_err = MPI_Finalize();
        }

      AssertThrow (mpi_err == 0,
                   ExcMessage ("An error occurred while calling MPI_Finalize()"));
#endif
#endif
    }

  } // end of namespace MPI

} // end of namespace Utilities

DEAL_II_NAMESPACE_CLOSE
<commit_msg>Add missing vector_memory header (for PETSc).<commit_after>//---------------------------------------------------------------------------
//      $Id$
//    Version: $Name$
//
//    Copyright (C) 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <deal.II/base/mpi.h>
#include <deal.II/base/utilities.h>
#include <deal.II/base/exceptions.h>

#include <cstddef>
#include <iostream>

#ifdef DEAL_II_USE_TRILINOS
#  ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#    include <Epetra_MpiComm.h>
#    include <deal.II/lac/vector_memory.h>
#    include <deal.II/lac/trilinos_vector.h>
#    include <deal.II/lac/trilinos_block_vector.h>
#  endif
#endif

#ifdef DEAL_II_USE_PETSC
#  ifdef DEAL_II_COMPILER_SUPPORTS_MPI
#    include <petscsys.h>
#include <deal.II/lac/vector_memory.h>
#include <deal.II/lac/petsc_block_vector.h>
#include <deal.II/lac/petsc_parallel_block_vector.h>
#include <deal.II/lac/petsc_vector.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#  endif
#endif

DEAL_II_NAMESPACE_OPEN

namespace Utilities
{

  namespace MPI
  {
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
                                // Unfortunately, we have to work
                                // around an oddity in the way PETSc
                                // and some gcc versions interact. If
                                // we use PETSc's MPI dummy
                                // implementation, it expands the
                                // calls to the two MPI functions
                                // basically as ``(n_jobs=1, 0)'',
                                // i.e. it assigns the number one to
                                // the variable holding the number of
                                // jobs, and then uses the comma
                                // operator to let the entire
                                // expression have the value zero. The
                                // latter is important, since
                                // ``MPI_Comm_size'' returns an error
                                // code that we may want to check (we
                                // don't here, but one could in
                                // principle), and the trick with the
                                // comma operator makes sure that both
                                // the number of jobs is correctly
                                // assigned, and the return value is
                                // zero. Unfortunately, if some recent
                                // versions of gcc detect that the
                                // comma expression just stands by
                                // itself, i.e. the result is not
                                // assigned to another variable, then
                                // they warn ``right-hand operand of
                                // comma has no effect''. This
                                // unwanted side effect can be
                                // suppressed by casting the result of
                                // the entire expression to type
                                // ``void'' -- not beautiful, but
                                // helps calming down unwarranted
                                // compiler warnings...
    unsigned int n_mpi_processes (const MPI_Comm &mpi_communicator)
    {
      int n_jobs=1;
      (void) MPI_Comm_size (mpi_communicator, &n_jobs);

      return n_jobs;
    }

    unsigned int this_mpi_process (const MPI_Comm &mpi_communicator)
    {
      int rank=0;
      (void) MPI_Comm_rank (mpi_communicator, &rank);

      return rank;
    }

    MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
    {
      MPI_Comm new_communicator;
      MPI_Comm_dup (mpi_communicator, &new_communicator);
      return new_communicator;
    }

    std::vector<unsigned int>
    compute_point_to_point_communication_pattern (const MPI_Comm & mpi_comm,
                                                  const std::vector<unsigned int> & destinations)
    {
      unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);
      unsigned int n_procs = Utilities::MPI::n_mpi_processes(mpi_comm);

      for (unsigned int i=0; i<destinations.size(); ++i)
        {
          Assert (destinations[i] < n_procs,
                  ExcIndexRange (destinations[i], 0, n_procs));
          Assert (destinations[i] != myid,
                  ExcMessage ("There is no point in communicating with ourselves."));
        }

                                       // let all processors
                                       // communicate the maximal
                                       // number of destinations they
                                       // have
      const unsigned int max_n_destinations
        = Utilities::MPI::max (destinations.size(), mpi_comm);

                                       // now that we know the number
                                       // of data packets every
                                       // processor wants to send, set
                                       // up a buffer with the maximal
                                       // size and copy our
                                       // destinations in there,
                                       // padded with -1's
      std::vector<unsigned int> my_destinations(max_n_destinations,
                                                numbers::invalid_unsigned_int);
      std::copy (destinations.begin(), destinations.end(),
                 my_destinations.begin());

                                       // now exchange these (we could
                                       // communicate less data if we
                                       // used MPI_Allgatherv, but
                                       // we'd have to communicate
                                       // my_n_destinations to all
                                       // processors in this case,
                                       // which is more expensive than
                                       // the reduction operation
                                       // above in MPI_Allreduce)
      std::vector<unsigned int> all_destinations (max_n_destinations * n_procs);
      MPI_Allgather (&my_destinations[0], max_n_destinations, MPI_UNSIGNED,
                     &all_destinations[0], max_n_destinations, MPI_UNSIGNED,
                     mpi_comm);

                                       // now we know who is going to
                                       // communicate with
                                       // whom. collect who is going
                                       // to communicate with us!
      std::vector<unsigned int> origins;
      for (unsigned int i=0; i<n_procs; ++i)
        for (unsigned int j=0; j<max_n_destinations; ++j)
          if (all_destinations[i*max_n_destinations + j] == myid)
            origins.push_back (i);
          else if (all_destinations[i*max_n_destinations + j] ==
                   numbers::invalid_unsigned_int)
            break;

      return origins;
    }

    namespace
    {
                                       // custom MIP_Op for
                                       // calculate_collective_mpi_min_max_avg
      void max_reduce ( const void * in_lhs_,
                        void * inout_rhs_,
                        int * len,
                        MPI_Datatype * )
      {
        const MinMaxAvg * in_lhs = static_cast<const MinMaxAvg*>(in_lhs_);
        MinMaxAvg * inout_rhs = static_cast<MinMaxAvg*>(inout_rhs_);

        Assert(*len==1, ExcInternalError());

        inout_rhs->sum += in_lhs->sum;
        if (inout_rhs->min>in_lhs->min)
          {
            inout_rhs->min = in_lhs->min;
            inout_rhs->min_index = in_lhs->min_index;
          }
        else if (inout_rhs->min == in_lhs->min)
          { // choose lower cpu index when tied to make operator cumutative
            if (inout_rhs->min_index > in_lhs->min_index)
              inout_rhs->min_index = in_lhs->min_index;
          }

        if (inout_rhs->max < in_lhs->max)
          {
          inout_rhs->max = in_lhs->max;
          inout_rhs->max_index = in_lhs->max_index;
          }
        else if (inout_rhs->max == in_lhs->max)
          { // choose lower cpu index when tied to make operator cumutative
            if (inout_rhs->max_index > in_lhs->max_index)
              inout_rhs->max_index = in_lhs->max_index;
          }
      }
    }

    MinMaxAvg
    min_max_avg(const double my_value,
                const MPI_Comm &mpi_communicator)
    {
      MinMaxAvg result;

      const unsigned int my_id
        = dealii::Utilities::MPI::this_mpi_process(mpi_communicator);
      const unsigned int numproc
        = dealii::Utilities::MPI::n_mpi_processes(mpi_communicator);

      MPI_Op op;
      int ierr = MPI_Op_create((MPI_User_function *)&max_reduce, true, &op);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      MinMaxAvg in;
      in.sum = in.min = in.max = my_value;
      in.min_index = in.max_index = my_id;

      MPI_Datatype type;
      int lengths[]={3,2};
      MPI_Aint displacements[]={0,offsetof(MinMaxAvg, min_index)};
      MPI_Datatype types[]={MPI_DOUBLE, MPI_INT};

      ierr = MPI_Type_struct(2, lengths, displacements, types, &type);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Type_commit(&type);
      ierr = MPI_Allreduce (&in, &result, 1, type, op, mpi_communicator);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Type_free (&type);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      ierr = MPI_Op_free(&op);
      AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());

      result.avg = result.sum / numproc;

      return result;
    }

#else

    unsigned int n_mpi_processes (const MPI_Comm &)
    {
      return 1;
    }

    unsigned int this_mpi_process (const MPI_Comm &)
    {
      return 0;
    }

    MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
    {
      return mpi_communicator;
    }

    MinMaxAvg
    min_max_avg(const double my_value,
                const MPI_Comm &)
    {
      MinMaxAvg result;

      result.sum = my_value;
      result.avg = my_value;
      result.min = my_value;
      result.max = my_value;
      result.min_index = 0;
      result.max_index = 0;

      return result;
    }

#endif

    MPI_InitFinalize::MPI_InitFinalize (int    &argc,
                                        char** &argv)
                    :
                    owns_mpi (true)
    {
      static bool constructor_has_already_run = false;
      Assert (constructor_has_already_run == false,
              ExcMessage ("You can only create a single object of this class "
                          "in a program since it initializes the MPI system."));

#ifdef DEAL_II_COMPILER_SUPPORTS_MPI
      // if we have PETSc, we will initialize it and let it handle MPI.
      // Otherwise, we will do it.
#ifdef DEAL_II_USE_PETSC
      PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
#else
      int MPI_has_been_started = 0;
      MPI_Initialized(&MPI_has_been_started);
      AssertThrow (MPI_has_been_started == 0,
                   ExcMessage ("MPI error. You can only start MPI once!"));

      int mpi_err;
      mpi_err = MPI_Init (&argc, &argv);
      AssertThrow (mpi_err == 0,
                   ExcMessage ("MPI could not be initialized."));
#endif
#else
                                       // make sure the compiler doesn't warn
                                       // about these variables
      (void)argc;
      (void)argv;
#endif

      constructor_has_already_run = true;
    }

    MPI_InitFinalize::~MPI_InitFinalize()
    {
#ifdef DEAL_II_COMPILER_SUPPORTS_MPI

                                       // make memory pool release all
                                       // vectors that are no longer
                                       // used at this point. this is
                                       // relevant because the static
                                       // object destructors run for
                                       // these vectors at the end of
                                       // the program would run after
                                       // MPI_Finalize is called,
                                       // leading to errors
                                       //
#  if defined(DEAL_II_USE_TRILINOS) && !defined(__APPLE__)
                                       // TODO: On Mac OS X, shared libs can
                                       // only depend on other libs listed
                                       // later on the command line. This
                                       // means that libbase can't depend on
                                       // liblac, and we can't destroy the
                                       // memory pool here as long as we have
                                       // separate libraries. Consequently,
                                       // the #ifdef above. Deal will then
                                       // just continue to seg fault upon
                                       // completion of main()
      GrowingVectorMemory<TrilinosWrappers::MPI::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<TrilinosWrappers::MPI::BlockVector>
        ::release_unused_memory ();
#  endif

				       // Same for PETSc.
#ifdef DEAL_II_USE_PETSC
      GrowingVectorMemory<PETScWrappers::MPI::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::MPI::BlockVector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::Vector>
        ::release_unused_memory ();
      GrowingVectorMemory<PETScWrappers::BlockVector>
        ::release_unused_memory ();

				       // now end PETSc.
      PetscFinalize();
#else

      int mpi_err = 0;

      int MPI_has_been_started = 0;
      MPI_Initialized(&MPI_has_been_started);
      if (Utilities::System::program_uses_mpi() == true && owns_mpi == true &&
          MPI_has_been_started != 0)
        {
          if (std::uncaught_exception())
            {
              std::cerr << "ERROR: Uncaught exception in MPI_InitFinalize on proc "
                        << this_mpi_process(MPI_COMM_WORLD)
                        << ". Skipping MPI_Finalize() to avoid a deadlock."
                        << std::endl;
            }
          else
            mpi_err = MPI_Finalize();
        }

      AssertThrow (mpi_err == 0,
                   ExcMessage ("An error occurred while calling MPI_Finalize()"));
#endif
#endif
    }

  } // end of namespace MPI

} // end of namespace Utilities

DEAL_II_NAMESPACE_CLOSE
<|endoftext|>


<commit_before>#include "VoronoiCell.h"
//#include "Cognition/Modules/Modeling/PathPlanner/AStarSearchParameters.h"

<commit_msg>Deleted empty file to remove Linker Warning<commit_after><|endoftext|>


<commit_before>/*
Copyright 2017 creatorlxd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/BoundingBox.h"

SpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox()
{
	m_MinPosition = XMFLOAT3(0, 0, 0);
	m_MaxPosition = XMFLOAT3(0, 0, 0);
}

SpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox(const XMFLOAT3 & minl, const XMFLOAT3 & maxl)
{
	m_MinPosition = minl;
	m_MaxPosition = maxl;
}

bool SpaceGameEngine::IfIntersect(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)
{
	if (aabb1.m_MinPosition.x >= aabb2.m_MaxPosition.x || aabb1.m_MaxPosition.x <= aabb2.m_MinPosition.x)
		return false;
	if (aabb1.m_MinPosition.y >= aabb2.m_MaxPosition.y || aabb1.m_MaxPosition.y <= aabb2.m_MinPosition.y)
		return false;
	if (aabb1.m_MinPosition.z >= aabb2.m_MaxPosition.z || aabb1.m_MaxPosition.z <= aabb2.m_MinPosition.z)
		return false;
	return true;
}

bool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb, const XMFLOAT3 & position)
{
	if (aabb.m_MinPosition.x > position.x || aabb.m_MaxPosition.x < position.x)
		return false;
	if (aabb.m_MinPosition.y > position.y || aabb.m_MaxPosition.y < position.y)
		return false;
	if (aabb.m_MinPosition.z > position.z || aabb.m_MaxPosition.z < position.z)
		return false;
	return true;
}

bool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)
{
	if ((aabb1.m_MinPosition.x <= aabb2.m_MinPosition.x&&aabb1.m_MaxPosition.x >= aabb2.m_MaxPosition.x) &&
		(aabb1.m_MinPosition.y <= aabb2.m_MinPosition.y&&aabb1.m_MaxPosition.y >= aabb2.m_MaxPosition.y) &&
		(aabb1.m_MinPosition.z <= aabb2.m_MinPosition.z&&aabb1.m_MaxPosition.z >= aabb2.m_MaxPosition.z))
		return true;
	else
		return false;
}

SpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<XMFLOAT3>& points)
{
	XMFLOAT3 minl((float)MaxIntValue,(float)MaxIntValue,(float)MaxIntValue), maxl(0.0f,0.0f,0.0f);
	for (auto& i : points)
	{
		minl.x = min(minl.x, i.x);
		minl.y = min(minl.y, i.y);
		minl.z = min(minl.z, i.z);
		maxl.x = max(maxl.x, i.x);
		maxl.y = max(maxl.y, i.y);
		maxl.z = max(maxl.z, i.z);
	}
	return AxisAlignedBoundingBox(minl, maxl);
}

SpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<AxisAlignedBoundingBox>& aabbs)
{
	XMFLOAT3 minl((float)MaxIntValue, (float)MaxIntValue, (float)MaxIntValue), maxl(0.0f, 0.0f, 0.0f);
	for (auto i : aabbs)
	{
		minl.x = min(minl.x, i.m_MinPosition.x);
		minl.y = min(minl.y, i.m_MinPosition.y);
		minl.z = min(minl.z, i.m_MinPosition.z);
		maxl.x = max(maxl.x, i.m_MaxPosition.x);
		maxl.y = max(maxl.y, i.m_MaxPosition.y);
		maxl.z = max(maxl.z, i.m_MaxPosition.z);
	}
	return AxisAlignedBoundingBox(minl, maxl);
}

bool SpaceGameEngine::IfIntersectWithFrustum(const AxisAlignedBoundingBox & aabb)
{
	XMFLOAT3 point[8];
	point[0] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);
	point[1] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);
	point[2] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MinPosition.z);
	point[3] = XMFLOAT3(aabb.m_MinPosition);
	point[4] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MaxPosition.z);
	point[5] = XMFLOAT3(aabb.m_MaxPosition);
	point[6] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);
	point[7] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);

	XMFLOAT3 point_after[8];
	bool if_front = true, if_behind = true;
	int flag_x = 0, flag_y = 0;
	int ans_x = 0, ans_y = 0;
	for (int i = 0; i < 8; i++)
	{
		point_after[i] = TransformByViewProjectionMatrix(point[i]);
		if (point_after[i].z >= 0)
			if_front = false;
		if (point_after[i].z <= 1)
			if_behind = false;
		if (point_after[i].x >= -1.0f&&point_after[i].x <= 1.0f&&
			point_after[i].y >= -1.0f&&point_after[i].y <= 1.0f&&
			point_after[i].z >= 0.0f&&point_after[i].z <= 1.0f)
			return true;
		if (flag_x == 0)
			flag_x = (point_after[i].x > 0 ? 1 : -1);
		if (flag_y == 0)
			flag_y = (point_after[i].y > 0 ? 1 : -1);
		if (flag_x*point_after[i].x == 1)
			ans_x += 1;
		if (flag_y*point_after[i].y == 1)
			ans_y += 1;
	}
	if (if_front || if_behind)
		return false;
	if (ans_x == 8 || ans_y == 8)
		return false;
	return true;
}
<commit_msg>fix a bug<commit_after>/*
Copyright 2017 creatorlxd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/BoundingBox.h"

SpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox()
{
	m_MinPosition = XMFLOAT3(0, 0, 0);
	m_MaxPosition = XMFLOAT3(0, 0, 0);
}

SpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox(const XMFLOAT3 & minl, const XMFLOAT3 & maxl)
{
	m_MinPosition = minl;
	m_MaxPosition = maxl;
}

bool SpaceGameEngine::IfIntersect(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)
{
	if (aabb1.m_MinPosition.x >= aabb2.m_MaxPosition.x || aabb1.m_MaxPosition.x <= aabb2.m_MinPosition.x)
		return false;
	if (aabb1.m_MinPosition.y >= aabb2.m_MaxPosition.y || aabb1.m_MaxPosition.y <= aabb2.m_MinPosition.y)
		return false;
	if (aabb1.m_MinPosition.z >= aabb2.m_MaxPosition.z || aabb1.m_MaxPosition.z <= aabb2.m_MinPosition.z)
		return false;
	return true;
}

bool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb, const XMFLOAT3 & position)
{
	if (aabb.m_MinPosition.x > position.x || aabb.m_MaxPosition.x < position.x)
		return false;
	if (aabb.m_MinPosition.y > position.y || aabb.m_MaxPosition.y < position.y)
		return false;
	if (aabb.m_MinPosition.z > position.z || aabb.m_MaxPosition.z < position.z)
		return false;
	return true;
}

bool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)
{
	if ((aabb1.m_MinPosition.x <= aabb2.m_MinPosition.x&&aabb1.m_MaxPosition.x >= aabb2.m_MaxPosition.x) &&
		(aabb1.m_MinPosition.y <= aabb2.m_MinPosition.y&&aabb1.m_MaxPosition.y >= aabb2.m_MaxPosition.y) &&
		(aabb1.m_MinPosition.z <= aabb2.m_MinPosition.z&&aabb1.m_MaxPosition.z >= aabb2.m_MaxPosition.z))
		return true;
	else
		return false;
}

SpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<XMFLOAT3>& points)
{
	XMFLOAT3 minl((float)MaxIntValue,(float)MaxIntValue,(float)MaxIntValue), maxl(0.0f,0.0f,0.0f);
	for (auto& i : points)
	{
		minl.x = min(minl.x, i.x);
		minl.y = min(minl.y, i.y);
		minl.z = min(minl.z, i.z);
		maxl.x = max(maxl.x, i.x);
		maxl.y = max(maxl.y, i.y);
		maxl.z = max(maxl.z, i.z);
	}
	return AxisAlignedBoundingBox(minl, maxl);
}

SpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<AxisAlignedBoundingBox>& aabbs)
{
	XMFLOAT3 minl((float)MaxIntValue, (float)MaxIntValue, (float)MaxIntValue), maxl(0.0f, 0.0f, 0.0f);
	for (auto i : aabbs)
	{
		minl.x = min(minl.x, i.m_MinPosition.x);
		minl.y = min(minl.y, i.m_MinPosition.y);
		minl.z = min(minl.z, i.m_MinPosition.z);
		maxl.x = max(maxl.x, i.m_MaxPosition.x);
		maxl.y = max(maxl.y, i.m_MaxPosition.y);
		maxl.z = max(maxl.z, i.m_MaxPosition.z);
	}
	return AxisAlignedBoundingBox(minl, maxl);
}

bool SpaceGameEngine::IfIntersectWithFrustum(const AxisAlignedBoundingBox & aabb)
{
	XMFLOAT3 point[8];
	point[0] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);
	point[1] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);
	point[2] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MinPosition.z);
	point[3] = XMFLOAT3(aabb.m_MinPosition);
	point[4] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MaxPosition.z);
	point[5] = XMFLOAT3(aabb.m_MaxPosition);
	point[6] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);
	point[7] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);

	XMFLOAT3 point_after[8];
	bool if_front = true, if_behind = true;
	int flag_x = 0, flag_y = 0;
	int ans_x = 0, ans_y = 0;
	for (int i = 0; i < 8; i++)
	{
		point_after[i] = TransformByViewProjectionMatrix(point[i]);
		if (point_after[i].z >= 0)
			if_front = false;
		if (point_after[i].z <= 1)
			if_behind = false;
		if (point_after[i].x >= -1.0f&&point_after[i].x <= 1.0f&&
			point_after[i].y >= -1.0f&&point_after[i].y <= 1.0f&&
			point_after[i].z >= 0.0f&&point_after[i].z <= 1.0f)
			return true;
		if (flag_x == 0)
			flag_x = (point_after[i].x > 0 ? 1 : -1);
		if (flag_y == 0)
			flag_y = (point_after[i].y > 0 ? 1 : -1);
		if (flag_x*(point_after[i].x > 0 ? 1 : -1) == 1)
			ans_x += 1;
		if (flag_y*(point_after[i].y > 0 ? 1 : -1) == 1)
			ans_y += 1;
	}
	if (if_front || if_behind)
		return false;
	if (ans_x == 8 && ans_y == 8)
		return false;
	return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"

#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceResponse.h"
#include "public/platform/WebWaitableEvent.h"
#include "wtf/Functional.h"
#include "wtf/MainThread.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
{
    return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));
}

WorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    for (size_t i = 0; i < m_receivedData.size(); ++i)
        delete m_receivedData[i];
}

void WorkerLoaderClientBridgeSyncHelper::run()
{
    // This must be called only after m_event is signalled.
    MutexLocker lock(m_lock);
    ASSERT(m_done);
    for (size_t i = 0; i < m_clientTasks.size(); ++i)
        (*m_clientTasks[i])();
}

void WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didSendData, &m_client, bytesSent, totalBytesToBeSent));
}

static void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData, PassOwnPtr<WebDataConsumerHandle> handle)
{
    OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
    client->didReceiveResponse(identifier, *response, handle);
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&didReceiveResponseAdapter, &m_client, identifier, response.copyData(), handle));
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, unsigned dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    Vector<char>* buffer = new Vector<char>(dataLength);
    memcpy(buffer->data(), data, dataLength);
    m_receivedData.append(buffer);
    m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveData, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didDownloadData, &m_client, dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    Vector<char>* buffer = new Vector<char>(dataLength);
    memcpy(buffer->data(), data, dataLength);
    m_receivedData.append(buffer);
    m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveCachedMetadata, &m_client, static_cast<const char*>(buffer->data()), dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didFinishLoading, &m_client, identifier, finishTime));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didFail, &m_client, error.copy()));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didFailAccessControlCheck, &m_client, error.copy()));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(bind(&ThreadableLoaderClient::didFailRedirectCheck, &m_client));
    m_done = true;
    m_event->signal();
}

WorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
    : m_done(false)
    , m_client(client)
    , m_event(event)
{
    ASSERT(m_event);
}

} // namespace blink
<commit_msg>Use threadSafeBind() in WorkerLoaderClientBridgeSyncHelper<commit_after>/*
 * Copyright (C) 2014 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/loader/WorkerLoaderClientBridgeSyncHelper.h"

#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "platform/ThreadSafeFunctional.h"
#include "platform/network/ResourceError.h"
#include "platform/network/ResourceResponse.h"
#include "public/platform/WebWaitableEvent.h"
#include "wtf/MainThread.h"
#include "wtf/OwnPtr.h"

namespace blink {

PassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
{
    return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));
}

WorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    for (size_t i = 0; i < m_receivedData.size(); ++i)
        delete m_receivedData[i];
}

void WorkerLoaderClientBridgeSyncHelper::run()
{
    // This must be called only after m_event is signalled.
    MutexLocker lock(m_lock);
    ASSERT(m_done);
    for (size_t i = 0; i < m_clientTasks.size(); ++i)
        (*m_clientTasks[i])();
}

void WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didSendData, AllowCrossThreadAccess(&m_client), bytesSent, totalBytesToBeSent));
}

static void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData, PassOwnPtr<WebDataConsumerHandle> handle)
{
    OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
    client->didReceiveResponse(identifier, *response, handle);
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&didReceiveResponseAdapter, AllowCrossThreadAccess(&m_client), identifier, response, handle));
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, unsigned dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    Vector<char>* buffer = new Vector<char>(dataLength);
    memcpy(buffer->data(), data, dataLength);
    m_receivedData.append(buffer);
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didReceiveData, AllowCrossThreadAccess(&m_client), AllowCrossThreadAccess(static_cast<const char*>(buffer->data())), dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didDownloadData, AllowCrossThreadAccess(&m_client), dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    Vector<char>* buffer = new Vector<char>(dataLength);
    memcpy(buffer->data(), data, dataLength);
    m_receivedData.append(buffer);
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didReceiveCachedMetadata, AllowCrossThreadAccess(&m_client), AllowCrossThreadAccess(static_cast<const char*>(buffer->data())), dataLength));
}

void WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFinishLoading, AllowCrossThreadAccess(&m_client), identifier, finishTime));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFail, AllowCrossThreadAccess(&m_client), error));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFailAccessControlCheck, AllowCrossThreadAccess(&m_client), error));
    m_done = true;
    m_event->signal();
}

void WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()
{
    MutexLocker lock(m_lock);
    ASSERT(isMainThread());
    m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFailRedirectCheck, AllowCrossThreadAccess(&m_client)));
    m_done = true;
    m_event->signal();
}

WorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)
    : m_done(false)
    , m_client(client)
    , m_event(event)
{
    ASSERT(m_event);
}

} // namespace blink
<|endoftext|>


<commit_before>/**
* Copyright (C) 2013 kangliqiang ,kangliq@163.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "SocketUtil.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <sstream>
#include <vector>
#include <iostream>

int SocketInit()
{
#ifdef WIN32

	WSADATA wsaData;
	WORD versionRequested;

	versionRequested = MAKEWORD(2, 2);

	if (0 != WSAStartup(versionRequested, &wsaData))
	{
		return -1;
	}

#else

	signal(SIGPIPE, SIG_IGN);

#endif

	return 0;
}

int MakeSocketNonblocking (SOCKET fd)
{
#ifdef WIN32
	unsigned long para = 1;
	return ioctlsocket (fd,FIONBIO,&para);
#else
	int flags = fcntl (fd, F_GETFL, 0);
	assert (flags != -1);
	flags = (flags | O_NONBLOCK);
	return fcntl (fd, F_SETFL, flags);
#endif
}

int SetTcpNoDelay(SOCKET fd)
{
	int flag = 1;
	return setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag));
}

bool SplitURL(const std::string& serverURL, std::string &addr, short &nPort)
{
	size_t pos = serverURL.find(':');
	if (pos == std::string::npos)
	{
		return false;
	}

	addr = serverURL.substr(0, pos);
	if (0 == addr.compare("localhost"))
	{
		addr = "127.0.0.1";
	} else {
		addr = MixAll::filterIP(addr);
	}

	pos ++;

	std::string port = serverURL.substr(pos, serverURL.length() - pos);
	nPort = atoi(port.c_str());
	return true;
}

sockaddr string2SocketAddress(const std::string& addrString)
{
	std::string strAddr;
	short port;
	SplitURL(addrString,strAddr,port);

	struct sockaddr_in sa;
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);

	sa.sin_addr.s_addr = inet_addr(strAddr.c_str());

	sockaddr addr;
	memcpy(&addr,&sa,sizeof(sockaddr));

	return addr;
}

std::string socketAddress2String(sockaddr addr)
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	return inet_ntoa(in.sin_addr);
}

void GetLocalAddrs(std::vector<unsigned int> &addrs)
{
	addrs.clear();

#ifdef WIN32
	WSADATA wsaData;
	int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (ret != 0) {
		return;
	}

	SOCKET sfd = socket(AF_INET, SOCK_DGRAM, 0);

	if(sfd != INVALID_SOCKET)
	{
		DWORD bytesRet = 0;
		char * buffer;
		int bufSize = 1024;
		do
		{
			buffer = (char*)malloc(bufSize);
			if (WSAIoctl(sfd, SIO_GET_INTERFACE_LIST, NULL, 0, buffer, bufSize, &bytesRet, NULL, NULL) == SOCKET_ERROR)
			{
				if (WSAGetLastError() == WSAEFAULT)
				{
					bufSize <<= 1;
					free(buffer);
					continue;
				}
				else
				{
					bytesRet = 0;
					break;
				}
			}
			else
			{
				break;
			}
		}while (true);

		int size = bytesRet / sizeof(INTERFACE_INFO);
		INTERFACE_INFO* iinfo = (INTERFACE_INFO*)buffer;

		for (int i = 0; i < size; i++)
		{
			if (iinfo[i].iiAddress.AddressIn.sin_family == AF_INET)
			{
				addrs.push_back(ntohl(iinfo[i].iiAddress.AddressIn.sin_addr.s_addr));
			}
		}

		free(buffer);
		buffer = NULL;
		closesocket(sfd);
	}
#else

	struct ifconf ifc;
	ifc.ifc_buf = NULL;
	ifc.ifc_len = 0;

	int sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sfd != INVALID_SOCKET)
	{
		int ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);

		if(ret != -1)
		{
			ifc.ifc_req=(struct ifreq *)malloc(ifc.ifc_len);
			ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);
			if(ret != -1)
			{
				for(int i=0; i<ifc.ifc_len/sizeof(struct ifreq); i++)
				{
					struct sockaddr* sa = (struct sockaddr *)&(ifc.ifc_req[i].ifr_addr);
					if (AF_INET==sa->sa_family)
					{
						unsigned int addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
						addrs.push_back(htonl(addr));
					}
				}
			}

			free(ifc.ifc_req);
			ifc.ifc_req = NULL;
		}

		close(sfd);
	}

#endif

	if(addrs.empty())
	{
		char hostname[1024];

		int ret = gethostname(hostname, sizeof(hostname));
		if (ret == 0)
		{
			struct addrinfo *result = NULL;
			struct addrinfo *ptr = NULL;
			struct addrinfo hints;

			memset(&hints, 0,sizeof(hints) );
			hints.ai_family = AF_INET;
			hints.ai_socktype = SOCK_STREAM;
			hints.ai_protocol = IPPROTO_TCP;

			ret = getaddrinfo(hostname, NULL, &hints, &result);
			if ( ret == 0 )
			{
				for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
				{

					struct sockaddr_in  *sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr;
					addrs.push_back(ntohl(sockaddr_ipv4->sin_addr.s_addr));
				}
			}

			freeaddrinfo(result);
		}
	}

	std::vector<unsigned int>::iterator it = addrs.begin();
	for (;it!=addrs.end();)
	{
		if (*it>= 0x7F000000U && *it < 0x80000000U)
		{
			it = addrs.erase(it);
		}
		else
		{
			it++;
		}
	}

	if (addrs.empty())
	{
		addrs.push_back(INADDR_LOOPBACK);
	}

#ifdef WIN32
		WSACleanup();
#endif
}

std::string getLocalAddress()
{
	std::vector<unsigned int> addrs;
	GetLocalAddrs(addrs);
	struct in_addr addr;
	addr.s_addr=htonl(addrs[0]);

	return inet_ntoa(addr);
}

std::string getHostName(sockaddr addr)
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	struct hostent *remoteHost = gethostbyaddr((char*) &(in.sin_addr), 4, AF_INET);
	char** alias = remoteHost->h_aliases;
	if (*alias!=0)
	{
		return *alias;
	}
	else
	{
		return inet_ntoa(in.sin_addr);
	}
}

unsigned long long swapll(unsigned long long v)
{
#ifdef ENDIANMODE_BIG
	return v;
#else
	unsigned long long ret = ((v << 56)
								| ((v & 0xff00) << 40)
								| ((v & 0xff0000) << 24)
								| ((v & 0xff000000) << 8)
								| ((v >> 8 ) & 0xff000000)
								| ((v >> 24 ) & 0xff0000)
								| ((v >> 40 ) & 0xff00)
								| (v >> 56 ));

	return ret;
#endif
}

unsigned long long h2nll(unsigned long long v)
{
	return swapll(v);
}

unsigned long long n2hll(unsigned long long v)
{
	return swapll(v);
}

std::string socketAddress2IPPort( sockaddr addr )
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	char tmp[32];
	sprintf(tmp,"%s:%d",inet_ntoa(in.sin_addr),ntohs(in.sin_port));

	std::string ipport = tmp;
	return ipport;
}

void load_certificate(SSL_CTX* ctx, char* cacert, char* cakey, char* trustCALocation) {
    if (SSL_CTX_use_certificate_file(ctx, cacert, SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        abort();
    }

    if(SSL_CTX_use_PrivateKey_file(ctx, cakey, SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        abort();
    }

    if (SSL_CTX_check_private_key(ctx) <= 0) {
        fprintf(stderr, "Private key does not match the public certificate\n");
        abort();
    }

    /*
     * @param CAfile
     * A pointer to the name of the file that contains the certificates of the trusted CAs and CRLs.
     * The file must be in base64 privacy enhanced mail (PEM) format.
     * The value of this parameter can be NULL if the value of the CApath parameter is not NULL.
     * The maximum length is 255 characters.
     *
     * @param CApath
     * A pointer to the name of the directory that contains the certificates of the trusted CAs and CRLs.
     * The files in the directory must be in PEM format.
     * The value of this parameter can be NULL if the value of the CAfile parameter is not NULL.
     * The maximum length is 255 characters.
     */
    SSL_CTX_load_verify_locations(ctx, NULL, trustCALocation);
    SSL_CTX_set_verify_depth(ctx, 5);
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
	Logger::get_logger()->info("Load Certificate Successfully");
}

SSL_CTX* initializeSSL() {
	SSL_library_init();
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms(); // load and register all encryption algorithms.
	SSL_CTX* ctx = SSL_CTX_new(SSLv23_method());
    load_certificate(ctx, //SSL_CTX*
                     "/dianyi/config/RocketMQ/SSL/client.pem", // public CA certificate
                     "/dianyi/config/RocketMQ/SSL/client.pkey", // private CA  key
                     "/dianyi/config/RocketMQ/SSL/" // trust CA certificates
    );

	return ctx;
}

void destroySSL() {
	ERR_free_strings();
	EVP_cleanup();
}

void show_certificate(SSL* ssl) {
    X509 *cert;
    char *line;
    cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
    if ( cert != NULL ) {
		Logger::get_logger()->info("Server certificates:");
		line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
		Logger::get_logger()->info("Subject: {}", line);
		free(line);
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
		Logger::get_logger()->info("Issuer: {}", line);
        free(line);
        X509_free(cert);
    } else {
		Logger::get_logger()->warn("No certificates.");
    }
}

void shutdownSSL(SSL * ssl) {
	SSL_shutdown(ssl);
	SSL_free(ssl);
}<commit_msg>fix a warning<commit_after>/**
* Copyright (C) 2013 kangliqiang ,kangliq@163.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "SocketUtil.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <sstream>
#include <vector>
#include <iostream>

int SocketInit()
{
#ifdef WIN32

	WSADATA wsaData;
	WORD versionRequested;

	versionRequested = MAKEWORD(2, 2);

	if (0 != WSAStartup(versionRequested, &wsaData))
	{
		return -1;
	}

#else

	signal(SIGPIPE, SIG_IGN);

#endif

	return 0;
}

int MakeSocketNonblocking (SOCKET fd)
{
#ifdef WIN32
	unsigned long para = 1;
	return ioctlsocket (fd,FIONBIO,&para);
#else
	int flags = fcntl (fd, F_GETFL, 0);
	assert (flags != -1);
	flags = (flags | O_NONBLOCK);
	return fcntl (fd, F_SETFL, flags);
#endif
}

int SetTcpNoDelay(SOCKET fd)
{
	int flag = 1;
	return setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag));
}

bool SplitURL(const std::string& serverURL, std::string &addr, short &nPort)
{
	size_t pos = serverURL.find(':');
	if (pos == std::string::npos)
	{
		return false;
	}

	addr = serverURL.substr(0, pos);
	if (0 == addr.compare("localhost"))
	{
		addr = "127.0.0.1";
	} else {
		addr = MixAll::filterIP(addr);
	}

	pos ++;

	std::string port = serverURL.substr(pos, serverURL.length() - pos);
	nPort = atoi(port.c_str());
	return true;
}

sockaddr string2SocketAddress(const std::string& addrString)
{
	std::string strAddr;
	short port;
	SplitURL(addrString,strAddr,port);

	struct sockaddr_in sa;
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);

	sa.sin_addr.s_addr = inet_addr(strAddr.c_str());

	sockaddr addr;
	memcpy(&addr,&sa,sizeof(sockaddr));

	return addr;
}

std::string socketAddress2String(sockaddr addr)
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	return inet_ntoa(in.sin_addr);
}

void GetLocalAddrs(std::vector<unsigned int> &addrs)
{
	addrs.clear();

#ifdef WIN32
	WSADATA wsaData;
	int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (ret != 0) {
		return;
	}

	SOCKET sfd = socket(AF_INET, SOCK_DGRAM, 0);

	if(sfd != INVALID_SOCKET)
	{
		DWORD bytesRet = 0;
		char * buffer;
		int bufSize = 1024;
		do
		{
			buffer = (char*)malloc(bufSize);
			if (WSAIoctl(sfd, SIO_GET_INTERFACE_LIST, NULL, 0, buffer, bufSize, &bytesRet, NULL, NULL) == SOCKET_ERROR)
			{
				if (WSAGetLastError() == WSAEFAULT)
				{
					bufSize <<= 1;
					free(buffer);
					continue;
				}
				else
				{
					bytesRet = 0;
					break;
				}
			}
			else
			{
				break;
			}
		}while (true);

		int size = bytesRet / sizeof(INTERFACE_INFO);
		INTERFACE_INFO* iinfo = (INTERFACE_INFO*)buffer;

		for (int i = 0; i < size; i++)
		{
			if (iinfo[i].iiAddress.AddressIn.sin_family == AF_INET)
			{
				addrs.push_back(ntohl(iinfo[i].iiAddress.AddressIn.sin_addr.s_addr));
			}
		}

		free(buffer);
		buffer = NULL;
		closesocket(sfd);
	}
#else

	struct ifconf ifc;
	ifc.ifc_buf = NULL;
	ifc.ifc_len = 0;

	int sfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sfd != INVALID_SOCKET)
	{
		int ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);

		if(ret != -1)
		{
			ifc.ifc_req=(struct ifreq *)malloc(ifc.ifc_len);
			ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);
			if(ret != -1)
			{
				for(int i=0; i<ifc.ifc_len/sizeof(struct ifreq); i++)
				{
					struct sockaddr* sa = (struct sockaddr *)&(ifc.ifc_req[i].ifr_addr);
					if (AF_INET==sa->sa_family)
					{
						unsigned int addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
						addrs.push_back(htonl(addr));
					}
				}
			}

			free(ifc.ifc_req);
			ifc.ifc_req = NULL;
		}

		close(sfd);
	}

#endif

	if(addrs.empty())
	{
		char hostname[1024];

		int ret = gethostname(hostname, sizeof(hostname));
		if (ret == 0)
		{
			struct addrinfo *result = NULL;
			struct addrinfo *ptr = NULL;
			struct addrinfo hints;

			memset(&hints, 0,sizeof(hints) );
			hints.ai_family = AF_INET;
			hints.ai_socktype = SOCK_STREAM;
			hints.ai_protocol = IPPROTO_TCP;

			ret = getaddrinfo(hostname, NULL, &hints, &result);
			if ( ret == 0 )
			{
				for(ptr=result; ptr != NULL ;ptr=ptr->ai_next)
				{

					struct sockaddr_in  *sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr;
					addrs.push_back(ntohl(sockaddr_ipv4->sin_addr.s_addr));
				}
			}

			freeaddrinfo(result);
		}
	}

	std::vector<unsigned int>::iterator it = addrs.begin();
	for (;it!=addrs.end();)
	{
		if (*it>= 0x7F000000U && *it < 0x80000000U)
		{
			it = addrs.erase(it);
		}
		else
		{
			it++;
		}
	}

	if (addrs.empty())
	{
		addrs.push_back(INADDR_LOOPBACK);
	}

#ifdef WIN32
		WSACleanup();
#endif
}

std::string getLocalAddress()
{
	std::vector<unsigned int> addrs;
	GetLocalAddrs(addrs);
	struct in_addr addr;
	addr.s_addr=htonl(addrs[0]);

	return inet_ntoa(addr);
}

std::string getHostName(sockaddr addr)
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	struct hostent *remoteHost = gethostbyaddr((char*) &(in.sin_addr), 4, AF_INET);
	char** alias = remoteHost->h_aliases;
	if (*alias!=0)
	{
		return *alias;
	}
	else
	{
		return inet_ntoa(in.sin_addr);
	}
}

unsigned long long swapll(unsigned long long v)
{
#ifdef ENDIANMODE_BIG
	return v;
#else
	unsigned long long ret = ((v << 56)
								| ((v & 0xff00) << 40)
								| ((v & 0xff0000) << 24)
								| ((v & 0xff000000) << 8)
								| ((v >> 8 ) & 0xff000000)
								| ((v >> 24 ) & 0xff0000)
								| ((v >> 40 ) & 0xff00)
								| (v >> 56 ));

	return ret;
#endif
}

unsigned long long h2nll(unsigned long long v)
{
	return swapll(v);
}

unsigned long long n2hll(unsigned long long v)
{
	return swapll(v);
}

std::string socketAddress2IPPort( sockaddr addr )
{
	sockaddr_in in;
	memcpy(&in,&addr,sizeof(sockaddr));

	char tmp[32];
	sprintf(tmp,"%s:%d",inet_ntoa(in.sin_addr),ntohs(in.sin_port));

	std::string ipport = tmp;
	return ipport;
}

void load_certificate(SSL_CTX* ctx, char const * cacert, char const * cakey, char const * trustCALocation) {
    if (SSL_CTX_use_certificate_file(ctx, cacert, SSL_FILETYPE_PEM) <= 0) {
		Logger::get_logger()->error("Failed to apply public certeificate");
        abort();
    }

    if(SSL_CTX_use_PrivateKey_file(ctx, cakey, SSL_FILETYPE_PEM) <= 0) {
		Logger::get_logger()->error("Failed to apply private key.");
        abort();
    }

    if (SSL_CTX_check_private_key(ctx) <= 0) {
		Logger::get_logger()->error("Private key does not match the public certificate.");
        abort();
    }

    /*
     * @param CAfile
     * A pointer to the name of the file that contains the certificates of the trusted CAs and CRLs.
     * The file must be in base64 privacy enhanced mail (PEM) format.
     * The value of this parameter can be NULL if the value of the CApath parameter is not NULL.
     * The maximum length is 255 characters.
     *
     * @param CApath
     * A pointer to the name of the directory that contains the certificates of the trusted CAs and CRLs.
     * The files in the directory must be in PEM format.
     * The value of this parameter can be NULL if the value of the CAfile parameter is not NULL.
     * The maximum length is 255 characters.
     */
    SSL_CTX_load_verify_locations(ctx, NULL, trustCALocation);
    SSL_CTX_set_verify_depth(ctx, 5);
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
	Logger::get_logger()->info("Load Certificate Successfully");
}

SSL_CTX* initializeSSL() {
	SSL_library_init();
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms(); // load and register all encryption algorithms.
	SSL_CTX* ctx = SSL_CTX_new(SSLv23_method());
	char const * client_certificate = "/dianyi/config/RocketMQ/SSL/client.pem";
	char const * client_private_key = "/dianyi/config/RocketMQ/SSL/client.pkey";
	char const * cacerts = "/dianyi/config/RocketMQ/SSL/";

    load_certificate(ctx, //SSL_CTX*
					 client_certificate, // public CA certificate
                     client_private_key, // private CA  key
                     cacerts // trust CA certificates

    );

	return ctx;
}

void destroySSL() {
	ERR_free_strings();
	EVP_cleanup();
}

void show_certificate(SSL* ssl) {
    X509 *cert;
    char *line;
    cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
    if ( cert != NULL ) {
		Logger::get_logger()->info("Server certificates:");
		line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
		Logger::get_logger()->info("Subject: {}", line);
		free(line);
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
		Logger::get_logger()->info("Issuer: {}", line);
        free(line);
        X509_free(cert);
    } else {
		Logger::get_logger()->warn("No certificates.");
    }
}

void shutdownSSL(SSL * ssl) {
	SSL_shutdown(ssl);
	SSL_free(ssl);
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: basicrange.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: thb $ $Date: 2004-03-15 14:27:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_RANGE_BASICRANGE_HXX
#define _BGFX_RANGE_BASICRANGE_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _INC_FLOAT
#include <float.h>
#endif

namespace basegfx
{
    template< typename T, typename Traits > class BasicRange
    {
    protected:
        T       mnMinimum;
        T       mnMaximum;

    public:
        BasicRange() :
            mnMinimum(Traits::initMin()),
            mnMaximum(Traits::initMax())
        {
        }

        BasicRange( T nValue ) :
            mnMinimum(nValue),
            mnMaximum(nValue)
        {
        }

        BasicRange(const BasicRange& rRange) :
            mnMinimum(rRange.mnMinimum),
            mnMaximum(rRange.mnMaximum)
        {
        }

        void reset()
        {
            mnMinimum = Traits::initMin();
            mnMaximum = Traits::initMax();
        }

        bool isEmpty() const
        {
            return Traits::initMin() == mnMinimum && Traits::initMax() == mnMaximum;
        }

        T getMinimum() const { return mnMinimum; }
        T getMaximum() const { return mnMaximum; }

        double getCenter() const
        {
            return ((mnMaximum + mnMinimum) / 2.0);
        }

        bool isInside(T nValue) const
        {
            return (nValue >= mnMinimum) && (nValue <= mnMaximum);
        }

        bool isInside(const BasicRange& rRange) const
        {
            return (rRange.mnMinimum >= mnMinimum) && (rRange.mnMaximum <= mnMaximum);
        }

        bool overlaps(const BasicRange& rRange) const
        {
            return !((rRange.mnMaximum < mnMinimum) || (rRange.mnMinimum > mnMaximum));
        }

        bool operator==( const BasicRange& rRange ) const
        {
            return (mnMinimum == rRange.mnMinimum && mnMaximum == rRange.mnMaximum);
        }

        bool operator!=( const BasicRange& rRange ) const
        {
            return (mnMinimum != rRange.mnMinimum || mnMaximum != rRange.mnMaximum);
        }

        void operator=(const BasicRange& rRange)
        {
            mnMinimum = rRange.mnMinimum;
            mnMaximum = rRange.mnMaximum;
        }

        void expand(T nValue)
        {
            if(nValue < mnMinimum)
            {
                mnMinimum = nValue;
            }

            if(nValue > mnMaximum)
            {
                mnMaximum = nValue;
            }
        }

        void expand(const BasicRange& rRange)
        {
            if(rRange.mnMinimum < mnMinimum)
            {
                mnMinimum = rRange.mnMinimum;
            }

            if(rRange.mnMaximum > mnMaximum)
            {
                mnMaximum = rRange.mnMaximum;
            }
        }

        void grow(T nValue)
        {
            bool bLessThanZero(nValue < 0);

            if(nValue > 0 || bLessThanZero)
            {
                mnMinimum -= nValue;
                mnMaximum += nValue;

                if(bLessThanZero)
                {
                    // test if range did collapse
                    if(mnMinimum > mnMaximum)
                    {
                        // if yes, collapse to center
                        mnMinimum = mnMaximum = (mnMinimum + mnMaximum) / 2.0;
                    }
                }
            }
        }

        typename Traits::DifferenceType getRange() const
        {
            return (mnMaximum - mnMinimum);
        }
    };

    // some pre-fabricated traits
    struct DoubleTraits
    {
        static double initMin() { return DBL_MAX; };
        static double initMax() { return DBL_MIN; };

        typedef double DifferenceType;
    };

    struct Int32Traits
    {
        static sal_Int32 initMin() { return 0x7FFFFFFFL; };
        static sal_Int32 initMax() { return 0x80000000UL; };

        typedef sal_Int64 DifferenceType;
    };

} // end of namespace basegfx

#endif /* _BGFX_RANGE_BASICRANGE_HXX */
<commit_msg>INTEGRATION: CWS aw019 (1.6.36); FILE MERGED 2004/10/06 11:14:08 aw 1.6.36.1: #i34831#<commit_after>/*************************************************************************
 *
 *  $RCSfile: basicrange.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-03 08:36:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_RANGE_BASICRANGE_HXX
#define _BGFX_RANGE_BASICRANGE_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _INC_FLOAT
#include <float.h>
#endif

namespace basegfx
{
    template< typename T, typename Traits > class BasicRange
    {
    protected:
        T       mnMinimum;
        T       mnMaximum;

    public:
        BasicRange() :
            mnMinimum(Traits::initMin()),
            mnMaximum(Traits::initMax())
        {
        }

        BasicRange( T nValue ) :
            mnMinimum(nValue),
            mnMaximum(nValue)
        {
        }

        BasicRange(const BasicRange& rRange) :
            mnMinimum(rRange.mnMinimum),
            mnMaximum(rRange.mnMaximum)
        {
        }

        void reset()
        {
            mnMinimum = Traits::initMin();
            mnMaximum = Traits::initMax();
        }

        bool isEmpty() const
        {
            return Traits::initMin() == mnMinimum && Traits::initMax() == mnMaximum;
        }

        T getMinimum() const { return mnMinimum; }
        T getMaximum() const { return mnMaximum; }

        double getCenter() const
        {
            return ((mnMaximum + mnMinimum) / 2.0);
        }

        bool isInside(T nValue) const
        {
            return (nValue >= mnMinimum) && (nValue <= mnMaximum);
        }

        bool isInside(const BasicRange& rRange) const
        {
            return (rRange.mnMinimum >= mnMinimum) && (rRange.mnMaximum <= mnMaximum);
        }

        bool overlaps(const BasicRange& rRange) const
        {
            return !((rRange.mnMaximum < mnMinimum) || (rRange.mnMinimum > mnMaximum));
        }

        bool operator==( const BasicRange& rRange ) const
        {
            return (mnMinimum == rRange.mnMinimum && mnMaximum == rRange.mnMaximum);
        }

        bool operator!=( const BasicRange& rRange ) const
        {
            return (mnMinimum != rRange.mnMinimum || mnMaximum != rRange.mnMaximum);
        }

        void operator=(const BasicRange& rRange)
        {
            mnMinimum = rRange.mnMinimum;
            mnMaximum = rRange.mnMaximum;
        }

        void expand(T nValue)
        {
            if(nValue < mnMinimum)
            {
                mnMinimum = nValue;
            }

            if(nValue > mnMaximum)
            {
                mnMaximum = nValue;
            }
        }

        void expand(const BasicRange& rRange)
        {
            if(rRange.mnMinimum < mnMinimum)
            {
                mnMinimum = rRange.mnMinimum;
            }

            if(rRange.mnMaximum > mnMaximum)
            {
                mnMaximum = rRange.mnMaximum;
            }
        }

        void grow(T nValue)
        {
            bool bLessThanZero(nValue < 0);

            if(nValue > 0 || bLessThanZero)
            {
                mnMinimum -= nValue;
                mnMaximum += nValue;

                if(bLessThanZero)
                {
                    // test if range did collapse
                    if(mnMinimum > mnMaximum)
                    {
                        // if yes, collapse to center
                        mnMinimum = mnMaximum = (mnMinimum + mnMaximum) / 2;
                    }
                }
            }
        }

        typename Traits::DifferenceType getRange() const
        {
            return (mnMaximum - mnMinimum);
        }
    };

    // some pre-fabricated traits
    struct DoubleTraits
    {
        static double initMin() { return DBL_MAX; };
        static double initMax() { return DBL_MIN; };

        typedef double DifferenceType;
    };

    struct Int32Traits
    {
        static sal_Int32 initMin() { return 0x7FFFFFFFL; };
        static sal_Int32 initMax() { return 0x80000000UL; };

        typedef sal_Int64 DifferenceType;
    };

} // end of namespace basegfx

#endif /* _BGFX_RANGE_BASICRANGE_HXX */
<|endoftext|>


<commit_before>#include "athena/CubeMesh.h"
#include "athena/GraphicDevice.h"

using namespace Athena;

static const float s_positions[24 * 3] =
{
	//Front
	-1,  1, -1,
	-1, -1, -1,
	 1,  1, -1,
	 1, -1, -1,
	 //Back
	 1, -1,  1,
	-1, -1,  1,
	 1,  1,  1,
	-1,  1,  1,
	 //Left
	-1, -1,  1,
	-1, -1, -1,
	-1,  1,  1,
	-1,  1, -1,
	 //Right
	 1,  1, -1,
	 1, -1, -1,
	 1,  1,  1,
	 1, -1,  1,
	//Bottom
	 1, -1, -1,
	-1, -1, -1,
	 1, -1,  1,
	-1, -1,  1,
	//Top
	-1,  1,  1,
	-1,  1, -1,
	 1,  1,  1,
	 1,  1, -1,
};

static const float s_texCoords[24 * 2] =
{
	//Front
	0,  0,
	0,  1,
	1,  0,
	1,  1,
	//Back
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Left
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Right
	0,  0,
	0,  1,
	1,  0,
	1,  1,
	//Bottom
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Top
	0,  0,
	0,  1,
	1,  0,
	1,  1,
};

CCubeMesh::CCubeMesh()
{
	VERTEX_BUFFER_DESCRIPTOR bufferDesc = GenerateVertexBufferDescriptor(24, 36,
		VERTEX_BUFFER_HAS_POS | VERTEX_BUFFER_HAS_UV0);
	const auto& posVertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_POSITION);
	const auto& uv0VertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_UV0);

	m_primitiveType = PRIMITIVE_TRIANGLE_LIST;
	m_primitiveCount = 12;
	m_vertexBuffer = CGraphicDevice::GetInstance().CreateVertexBuffer(bufferDesc);

	uint8* vertices = reinterpret_cast<uint8*>(m_vertexBuffer->LockVertices());
	for(unsigned int i = 0; i < 24; i++)
	{
		*reinterpret_cast<CVector3*>(vertices + posVertexItem->offset) = CVector3(&s_positions[i * 3]);
		*reinterpret_cast<CVector2*>(vertices + uv0VertexItem->offset) = CVector2(&s_texCoords[i * 2]);
		vertices += bufferDesc.GetVertexSize();
	}
	m_vertexBuffer->UnlockVertices();

	uint16* indices = m_vertexBuffer->LockIndices();
	for(unsigned int i = 0; i < 6; i++)
	{
		indices[(i * 6) + 0] = (i * 4) + 1;
		indices[(i * 6) + 1] = (i * 4) + 0;
		indices[(i * 6) + 2] = (i * 4) + 2;
		indices[(i * 6) + 3] = (i * 4) + 1;
		indices[(i * 6) + 4] = (i * 4) + 2;
		indices[(i * 6) + 5] = (i * 4) + 3;
	}
	m_vertexBuffer->UnlockIndices();
}

CCubeMesh::~CCubeMesh()
{

}

MeshPtr CCubeMesh::Create()
{
	return MeshPtr(new CCubeMesh());
}
<commit_msg>Simplified index generation in CubeMesh.<commit_after>#include "athena/CubeMesh.h"
#include "athena/GraphicDevice.h"

using namespace Athena;

static const float s_positions[24 * 3] =
{
	//Front
	-1,  1, -1,
	-1, -1, -1,
	 1,  1, -1,
	 1, -1, -1,
	 //Back
	 1, -1,  1,
	-1, -1,  1,
	 1,  1,  1,
	-1,  1,  1,
	 //Left
	-1, -1,  1,
	-1, -1, -1,
	-1,  1,  1,
	-1,  1, -1,
	 //Right
	 1,  1, -1,
	 1, -1, -1,
	 1,  1,  1,
	 1, -1,  1,
	//Bottom
	 1, -1, -1,
	-1, -1, -1,
	 1, -1,  1,
	-1, -1,  1,
	//Top
	-1,  1,  1,
	-1,  1, -1,
	 1,  1,  1,
	 1,  1, -1,
};

static const float s_texCoords[24 * 2] =
{
	//Front
	0,  0,
	0,  1,
	1,  0,
	1,  1,
	//Back
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Left
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Right
	0,  0,
	0,  1,
	1,  0,
	1,  1,
	//Bottom
	0,  1,
	1,  1,
	0,  0,
	1,  0,
	//Top
	0,  0,
	0,  1,
	1,  0,
	1,  1,
};

#define GENERATE_FACE_INDICES(i) (i * 4) + 1, (i * 4) + 0, (i * 4) + 2, (i * 4) + 1, (i * 4) + 2, (i * 4) + 3

static const uint16 s_indices[36] =
{
	GENERATE_FACE_INDICES(0),
	GENERATE_FACE_INDICES(1),
	GENERATE_FACE_INDICES(2),
	GENERATE_FACE_INDICES(3),
	GENERATE_FACE_INDICES(4),
	GENERATE_FACE_INDICES(5)
};

CCubeMesh::CCubeMesh()
{
	VERTEX_BUFFER_DESCRIPTOR bufferDesc = GenerateVertexBufferDescriptor(24, 36,
		VERTEX_BUFFER_HAS_POS | VERTEX_BUFFER_HAS_UV0);
	const auto& posVertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_POSITION);
	const auto& uv0VertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_UV0);

	m_primitiveType = PRIMITIVE_TRIANGLE_LIST;
	m_primitiveCount = 12;
	m_vertexBuffer = CGraphicDevice::GetInstance().CreateVertexBuffer(bufferDesc);

	uint8* vertices = reinterpret_cast<uint8*>(m_vertexBuffer->LockVertices());
	for(unsigned int i = 0; i < 24; i++)
	{
		*reinterpret_cast<CVector3*>(vertices + posVertexItem->offset) = CVector3(&s_positions[i * 3]);
		*reinterpret_cast<CVector2*>(vertices + uv0VertexItem->offset) = CVector2(&s_texCoords[i * 2]);
		vertices += bufferDesc.GetVertexSize();
	}
	m_vertexBuffer->UnlockVertices();

	uint16* indices = m_vertexBuffer->LockIndices();
	memcpy(indices, s_indices, sizeof(s_indices));
	m_vertexBuffer->UnlockIndices();
}

CCubeMesh::~CCubeMesh()
{

}

MeshPtr CCubeMesh::Create()
{
	return MeshPtr(new CCubeMesh());
}
<|endoftext|>


<commit_before>#include <fstream>
#include <string>

#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <random>

#include "midi_misc.h"

using namespace std;

/* Ended up using boost::filesystem instead
 * This bool func is not in use
 */
bool does_file_exist(string fileName)
{
    ifstream infile(fileName);
    return infile.good();
}

int random_int(int min, int max) {
	random_device rd;		// I think I prefer seeding with random device vs ctime
	mt19937 rng(rd()); 		// seed with Mersenne-Twister engine VS ctime
	uniform_int_distribution<int> uni(min, max);
	return uni(rng);
}

/* Another way to implement random function
void MIDI_Scale::seed_gen() {
	gen.seed(static_cast<unsigned int>(std::time(0)));
}

int MIDI_Scale::gen_rand_num() {
	// seed_gen();
	boost::uniform_int<> dist(1, 2);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > num(gen, dist);
    return num();
}
*/<commit_msg>Update midi_misc.cpp<commit_after>#include <fstream>
#include <string>

#include <boost/random.hpp>
#include <boost/generator_iterator.hpp>
#include <random>

#include "midi_misc.h"

using namespace std;

/* Ended up using boost::filesystem instead
 * This bool func is not in use
 */
bool does_file_exist(string fileName)
{
    ifstream infile(fileName);
    return infile.good();
}

int random_int(int min, int max) {
	random_device rd;		// I think I prefer seeding with random device vs ctime
	mt19937 rng(rd()); 		// seed with Mersenne-Twister engine VS ctime
	uniform_int_distribution<int> uni(min, max);
	return uni(rng);
}

/* Another way to implement random function
void MIDI_Scale::seed_gen() {
	gen.seed(static_cast<unsigned int>(std::time(0)));
}

int MIDI_Scale::gen_rand_num() {
	// seed_gen(); // put in main.cpp
	boost::uniform_int<> dist(1, 2);
    	boost::variate_generator<boost::mt19937&, boost::uniform_int<> > num(gen, dist);
    	return num();
}
*/
<|endoftext|>


<commit_before><commit_msg>coverity#738656 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: frm_module.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 22:56:59 $
 *
 *  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 FRM_MODULE_HXX
#define FRM_MODULE_HXX

#define FORMS_MODULE_INCLUDE_CONTEXT
    #define FORMS_MODULE_NAMESPACE frm
    #include "forms_module.hxx"
#undef FORMS_MODULE_INCLUDE_CONTEXT

#endif // FRM_MODULE_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.244); FILE MERGED 2008/03/31 13:11:39 rt 1.3.244.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: frm_module.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef FRM_MODULE_HXX
#define FRM_MODULE_HXX

#define FORMS_MODULE_INCLUDE_CONTEXT
    #define FORMS_MODULE_NAMESPACE frm
    #include "forms_module.hxx"
#undef FORMS_MODULE_INCLUDE_CONTEXT

#endif // FRM_MODULE_HXX

<|endoftext|>