<commit_before>//----------------------------  sparse_matrix_01a.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2004, 2005 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.
//
//----------------------------  sparse_matrix_01a.cc  ---------------------------

// check setting elements in a sparse matrix using SparseMatrix::set(). make
// sure they are correct, and make sure that for the nonexisting entries
// SparseMatrix::el() returns zero and operator() throws an exception

#include "../tests.h"
#include <lac/sparse_matrix.h>
#include <fstream>
#include <iomanip>

void test ()
{
  SparsityPattern sp (5,5,3,false);
  for (unsigned int i=0; i<5; ++i)
    for (unsigned int j=0; j<5; ++j)
      if ((i+2*j+1) % 3 == 0)
        sp.add (i,j);
  sp.compress ();

  SparseMatrix<double> m(sp);

                                   // first set a few entries
  for (unsigned int i=0; i<m.m(); ++i)
    for (unsigned int j=0; j<m.n(); ++j)
      if ((i+2*j+1) % 3 == 0)
        m.set (i,j, i*j*.5+.5);

                                   // then make sure we retrieve the same ones
  for (unsigned int i=0; i<m.m(); ++i)
    for (unsigned int j=0; j<m.n(); ++j)
      if ((i+2*j+1) % 3 == 0)
        {
          Assert (m(i,j) == i*j*.5+.5, ExcInternalError());
          Assert (m.el(i,j) == i*j*.5+.5, ExcInternalError());
        }
      else
        {
          Assert (m.el(i,j) == 0, ExcInternalError());
          bool exc_thrown = false;
          double d;
          try
            {
              d = m(i,j);
            }
          catch (const std::exception &)
            {
              exc_thrown = true;
            }
          Assert (exc_thrown == true, ExcInternalError());
        }

  deallog << "OK" << std::endl;
}

int main ()
{
  std::ofstream logfile("sparse_matrix_01a/output");
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  try
    {
      test ();
    }
  catch (std::exception &exc)
    {
      deallog << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      deallog << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      deallog << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      deallog << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    };
}
<commit_msg>Fix one test. Explanation in the comment at the top.<commit_after>//----------------------------  sparse_matrix_01a.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2004, 2005, 2010 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.
//
//----------------------------  sparse_matrix_01a.cc  ---------------------------

// check setting elements in a sparse matrix using SparseMatrix::set(). make
// sure they are correct, and make sure that for the nonexisting entries
// SparseMatrix::el() returns zero (operator() terminates with an exception
// since sometime in the first half of 2010).

#include "../tests.h"
#include <lac/sparse_matrix.h>
#include <fstream>
#include <iomanip>

void test ()
{
  SparsityPattern sp (5,5,3,false);
  for (unsigned int i=0; i<5; ++i)
    for (unsigned int j=0; j<5; ++j)
      if ((i+2*j+1) % 3 == 0)
        sp.add (i,j);
  sp.compress ();

  SparseMatrix<double> m(sp);

                                   // first set a few entries
  for (unsigned int i=0; i<m.m(); ++i)
    for (unsigned int j=0; j<m.n(); ++j)
      if ((i+2*j+1) % 3 == 0)
        m.set (i,j, i*j*.5+.5);

                                   // then make sure we retrieve the same ones
  for (unsigned int i=0; i<m.m(); ++i)
    for (unsigned int j=0; j<m.n(); ++j)
      if ((i+2*j+1) % 3 == 0)
        {
          Assert (m(i,j) == i*j*.5+.5, ExcInternalError());
          Assert (m.el(i,j) == i*j*.5+.5, ExcInternalError());
        }
      else
        {
          Assert (m.el(i,j) == 0, ExcInternalError());
        }

  deallog << "OK" << std::endl;
}

int main ()
{
  std::ofstream logfile("sparse_matrix_01a/output");
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  try
    {
      test ();
    }
  catch (std::exception &exc)
    {
      deallog << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      deallog << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      deallog << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      deallog << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    };
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "common.h"
#include <Eigen/Eigenvalues>

// computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges
EIGEN_LAPACK_FUNC(syev,(char *jobz, char *uplo, int* n, Scalar* a, int *lda, Scalar* w, Scalar* work, int* lwork, int *info))
{
  bool query_size = *lwork==-1;

  *info = 0;
        if(*jobz!='N' && *jobz!='V')                    *info = -1;
  else  if(UPLO(*uplo)==INVALID)                        *info = -2;
  else  if(*n<0)                                        *info = -3;
  else  if(*lda<std::max(1,*n))                         *info = -5;
  else  if((!query_size) && *lwork<std::max(1,3**n-1))  *info = -8;

//   if(*info==0)
//   {
//     int nb = ILAENV( 1, 'SSYTRD', UPLO, N, -1, -1, -1 )
//          LWKOPT = MAX( 1, ( NB+2 )*N )
//          WORK( 1 ) = LWKOPT
// *
//          IF( LWORK.LT.MAX( 1, 3*N-1 ) .AND. .NOT.LQUERY )
//      $      INFO = -8
//       END IF
// *
//       IF( INFO.NE.0 ) THEN
//          CALL XERBLA( 'SSYEV ', -INFO )
//          RETURN
//       ELSE IF( LQUERY ) THEN
//          RETURN
//       END IF

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"SYEV ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0)
    return 0;

  PlainMatrixType mat(*n,*n);
  if(UPLO(*uplo)==UP) mat = matrix(a,*n,*n,*lda).adjoint();
  else                mat = matrix(a,*n,*n,*lda);

  bool computeVectors = *jobz=='V' || *jobz=='v';
  SelfAdjointEigenSolver<PlainMatrixType> eig(mat,computeVectors?ComputeEigenvectors:EigenvaluesOnly);

  if(eig.info()==NoConvergence)
  {
    vector(w,*n).setZero();
    if(computeVectors)
      matrix(a,*n,*n,*lda).setIdentity();
    //*info = 1;
    return 0;
  }

  vector(w,*n) = eig.eigenvalues();
  if(computeVectors)
    matrix(a,*n,*n,*lda) = eig.eigenvectors();

  return 0;
}
<commit_msg>suppress unused warning<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "common.h"
#include <Eigen/Eigenvalues>

// computes an LU factorization of a general M-by-N matrix A using partial pivoting with row interchanges
EIGEN_LAPACK_FUNC(syev,(char *jobz, char *uplo, int* n, Scalar* a, int *lda, Scalar* w, Scalar* /*work*/, int* lwork, int *info))
{
  // TODO exploit the work buffer
  bool query_size = *lwork==-1;

  *info = 0;
        if(*jobz!='N' && *jobz!='V')                    *info = -1;
  else  if(UPLO(*uplo)==INVALID)                        *info = -2;
  else  if(*n<0)                                        *info = -3;
  else  if(*lda<std::max(1,*n))                         *info = -5;
  else  if((!query_size) && *lwork<std::max(1,3**n-1))  *info = -8;

//   if(*info==0)
//   {
//     int nb = ILAENV( 1, 'SSYTRD', UPLO, N, -1, -1, -1 )
//          LWKOPT = MAX( 1, ( NB+2 )*N )
//          WORK( 1 ) = LWKOPT
// *
//          IF( LWORK.LT.MAX( 1, 3*N-1 ) .AND. .NOT.LQUERY )
//      $      INFO = -8
//       END IF
// *
//       IF( INFO.NE.0 ) THEN
//          CALL XERBLA( 'SSYEV ', -INFO )
//          RETURN
//       ELSE IF( LQUERY ) THEN
//          RETURN
//       END IF

  if(*info!=0)
  {
    int e = -*info;
    return xerbla_(SCALAR_SUFFIX_UP"SYEV ", &e, 6);
  }

  if(query_size)
  {
    *lwork = 0;
    return 0;
  }

  if(*n==0)
    return 0;

  PlainMatrixType mat(*n,*n);
  if(UPLO(*uplo)==UP) mat = matrix(a,*n,*n,*lda).adjoint();
  else                mat = matrix(a,*n,*n,*lda);

  bool computeVectors = *jobz=='V' || *jobz=='v';
  SelfAdjointEigenSolver<PlainMatrixType> eig(mat,computeVectors?ComputeEigenvectors:EigenvaluesOnly);

  if(eig.info()==NoConvergence)
  {
    vector(w,*n).setZero();
    if(computeVectors)
      matrix(a,*n,*n,*lda).setIdentity();
    //*info = 1;
    return 0;
  }

  vector(w,*n) = eig.eigenvalues();
  if(computeVectors)
    matrix(a,*n,*n,*lda) = eig.eigenvectors();

  return 0;
}
<|endoftext|>


<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include "ParallelLoop.hpp"

#include <boost/test/unit_test.hpp>

#include "Grappa.hpp"
#include "Message.hpp"
#include "MessagePool.hpp"
#include "CompletionEvent.hpp"
#include "ConditionVariable.hpp"
#include "Delegate.hpp"
#include "Tasking.hpp"
#include "GlobalAllocator.hpp"

BOOST_AUTO_TEST_SUITE( New_loop_tests );

using namespace Grappa;
using Grappa::wait;

static bool touched = false;

void test_on_all_cores() {
  BOOST_MESSAGE("Testing on_all_cores...");

  on_all_cores([] {
    BOOST_MESSAGE("hello world from " << mycore() << "!");
    touched = true;
  });

  BOOST_CHECK_EQUAL(delegate::read(make_global(&touched,1)), true);
  BOOST_CHECK_EQUAL(touched, true);
}

void test_loop_decomposition() {
  int N = 16;

  CompletionEvent ce(N);

  impl::loop_decomposition_private<2>(0, N, [&ce](int64_t start, int64_t iters) {
    VLOG(1) << "loop(" << start << ", " << iters << ")";
    ce.complete(iters);
  });
  ce.wait();
}

void test_loop_decomposition_global() {
  int N = 16;

  CompletionEvent ce(N);
  auto ce_addr = make_global(&ce);

  impl::loop_decomposition_public(0, N, [ce_addr](int64_t start, int64_t iters) {
    VLOG(1) << "loop(" << start << ", " << iters << ")";
    complete(ce_addr,iters);
  });
  ce.wait();
}

CompletionEvent my_ce;

void test_forall_here() {
  BOOST_MESSAGE("Testing forall_here...");
  const int N = 15;

  {
    int x = 0;
    forall_here(0, N, [&x](int64_t start, int64_t iters) {
      CHECK(mycore() == 0);
      for (int64_t i=0; i<iters; i++) {
        x++;
      }
    });
    BOOST_CHECK_EQUAL(x, N);
  }

  {
    int x = 0;
    forall_here<&my_ce,2>(0, N, [&x](int64_t start, int64_t iters) {
      CHECK(mycore() == 0);
      for (int64_t i=0; i<iters; i++) {
        x++;
      }
    });
    BOOST_CHECK_EQUAL(x, N);
  }

}

static int test_global = 0;
CompletionEvent test_global_ce;

void test_forall_global() {
  BOOST_MESSAGE("Testing forall_global...");
  const int64_t N = 1 << 8;

  forall_global_private(0, N, [](int64_t start, int64_t iters) {
    for (int i=0; i<iters; i++) {
      test_global++;
    }
  });

  on_all_cores([]{
    BOOST_CHECK_EQUAL(test_global, N/cores());
    test_global = 0;
  });

  forall_global_private<&test_global_ce>(0, N, [](int64_t start, int64_t iters) {
    for (int i=0; i<iters; i++) {
      test_global++;
    }
  });

}

void test_forall_localized() {
  BOOST_MESSAGE("Testing forall_localized...");
  const int64_t N = 1 << 8;

  auto array = Grappa_typed_malloc<int64_t>(N);

  forall_localized(array, N, [](int64_t i, int64_t& e){
    e = 1;
  });

  forall_here(0, N, [array](int64_t s, int64_t n) {
    for (int i=s; i<s+n; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), 1); }
  });
}

void user_main(void * args) {
  CHECK(Grappa::cores() >= 2); // at least 2 nodes for these tests...

  test_on_all_cores();

  test_loop_decomposition();
  test_loop_decomposition_global();

  test_forall_here();
  test_forall_global();

  test_forall_localized();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
	       &(boost::unit_test::framework::master_test_suite().argv)
	       );

  Grappa_activate();

  Grappa_run_user_main( &user_main, (void*)NULL );

  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Add test for forall_global_public<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include "ParallelLoop.hpp"

#include <boost/test/unit_test.hpp>

#include "Grappa.hpp"
#include "Message.hpp"
#include "MessagePool.hpp"
#include "CompletionEvent.hpp"
#include "ConditionVariable.hpp"
#include "Delegate.hpp"
#include "Tasking.hpp"
#include "GlobalAllocator.hpp"

BOOST_AUTO_TEST_SUITE( New_loop_tests );

using namespace Grappa;
using Grappa::wait;

static bool touched = false;

void test_on_all_cores() {
  BOOST_MESSAGE("Testing on_all_cores...");

  on_all_cores([] {
    BOOST_MESSAGE("hello world from " << mycore() << "!");
    touched = true;
  });

  BOOST_CHECK_EQUAL(delegate::read(make_global(&touched,1)), true);
  BOOST_CHECK_EQUAL(touched, true);
}

void test_loop_decomposition() {
  int N = 16;

  CompletionEvent ce(N);

  impl::loop_decomposition_private<2>(0, N, [&ce](int64_t start, int64_t iters) {
    VLOG(1) << "loop(" << start << ", " << iters << ")";
    ce.complete(iters);
  });
  ce.wait();
}

void test_loop_decomposition_global() {
  int N = 16;

  CompletionEvent ce(N);
  auto ce_addr = make_global(&ce);

  impl::loop_decomposition_public(0, N, [ce_addr](int64_t start, int64_t iters) {
    VLOG(1) << "loop(" << start << ", " << iters << ")";
    complete(ce_addr,iters);
  });
  ce.wait();
}

CompletionEvent my_ce;

void test_forall_here() {
  BOOST_MESSAGE("Testing forall_here...");
  const int N = 15;

  {
    int x = 0;
    forall_here(0, N, [&x](int64_t start, int64_t iters) {
      CHECK(mycore() == 0);
      for (int64_t i=0; i<iters; i++) {
        x++;
      }
    });
    BOOST_CHECK_EQUAL(x, N);
  }

  {
    int x = 0;
    forall_here<&my_ce,2>(0, N, [&x](int64_t start, int64_t iters) {
      CHECK(mycore() == 0);
      for (int64_t i=0; i<iters; i++) {
        x++;
      }
    });
    BOOST_CHECK_EQUAL(x, N);
  }

}

static int test_global = 0;
CompletionEvent test_global_ce;
GlobalCompletionEvent my_gce;

void test_forall_global_private() {
  BOOST_MESSAGE("Testing forall_global...");
  const int64_t N = 1 << 8;

  BOOST_MESSAGE("  private");
  forall_global_private(0, N, [](int64_t start, int64_t iters) {
    for (int i=0; i<iters; i++) {
      test_global++;
    }
  });

  on_all_cores([]{
    BOOST_CHECK_EQUAL(test_global, N/cores());
    test_global = 0;
  });

  forall_global_private<&test_global_ce>(0, N, [](int64_t start, int64_t iters) {
    for (int i=0; i<iters; i++) {
      test_global++;
    }
  });

  on_all_cores([]{
    BOOST_CHECK_EQUAL(test_global, N/cores());
    test_global = 0;
  });

}

void test_forall_global_public() {
  BOOST_MESSAGE("Testing forall_global_public...");
  const int64_t N = 1 << 8;

  on_all_cores([]{ test_global = 0; });

  forall_global_public(0, N, [](int64_t s, int64_t n) {
    test_global += n;
  });

  int total = 0;
  for (Core c = 0; c < cores(); c++) {
    total += delegate::read(make_global(&test_global, c));
  }
  BOOST_CHECK_EQUAL(total, N);
}

void test_forall_localized() {
  BOOST_MESSAGE("Testing forall_localized...");
  const int64_t N = 1 << 8;

  auto array = Grappa_typed_malloc<int64_t>(N);

  forall_localized(array, N, [](int64_t i, int64_t& e){
    e = 1;
  });

  forall_here(0, N, [array](int64_t s, int64_t n) {
    for (int i=s; i<s+n; i++) { BOOST_CHECK_EQUAL(delegate::read(array+i), 1); }
  });
}

void user_main(void * args) {
  CHECK(Grappa::cores() >= 2); // at least 2 nodes for these tests...

  test_on_all_cores();

  test_loop_decomposition();
  test_loop_decomposition_global();

  test_forall_here();
  test_forall_global_private();
  test_forall_global_public();

  test_forall_localized();
}

BOOST_AUTO_TEST_CASE( test1 ) {

  Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
	       &(boost::unit_test::framework::master_test_suite().argv)
	       );

  Grappa_activate();

  Grappa_run_user_main( &user_main, (void*)NULL );

  Grappa_finish( 0 );
}

BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>


<commit_before>LCOLLIS.cpp<commit_msg>Added a new solution.<commit_after>#include "bits/stdc++.h"
using namespace std;

# define MOD 1000000007
# define GETCHAR getchar_unlocked
typedef long long ll;

inline ll  readllInt() {
    ll  n = 0;
    char c;
    while (1){
      c=GETCHAR();
      if(c=='\n'||c==' ') break;
       n = n * 10 + c - '0';
    }
    return n;
}

inline int readInt() {
    int n = 0;
    char c;
    while (1){
      c=GETCHAR();
      if(c=='\n'||c==' ') break;
       n = n * 10 + c - '0';
    }
    return n;
}

int main()
{
  int t=readInt();
  while(t--){
  	int n,m;
  	cin >> n >> m;
  	int a[n][m];
  	for(int i=0;i<n;i++){
  		for(int j=0;j<m;j++){
  			scanf("%1d",&a[i][j]);
  		}
  	}
  /*	for(int i=0;i<n;i++)
  	{
  		for(int j=0;j<m;j++){
  			printf("%d ",a[i][j] );
  		}
  		printf("\n");
  	}*/
  	int count=0,ans=0;
  	for(int j=0;j<m;j++){
  		int count=0;
  		for(int i=0;i<n;i++){
  				if(a[i][j]==1)
  					count++;
  		}
  		if(count>1)
  			ans+=(count*(count-1))/2; // nc2 == n(n-1)/!2!
  	}
  	printf("%d\n", ans);
  }

	return 0;
}
	<|endoftext|>


<commit_before>// Quantum operations
// Source: ./examples/ex4.cpp
#include <qpp.h>
using namespace qpp;

int main()
{
    cmat rho = st.pb00; // projector onto the Bell state (|00>+|11>)/sqrt(2)
    std::cout << "Initial state:\n";
    std::cout << disp(rho) << std::endl;

    // partial transpose of first subsystem
    cmat rhoTA = ptranspose(rho, {0});
    std::cout << "Eigenvalues of the partial transpose of Bell-0 state are:\n";
    std::cout << disp(transpose(hevals(rhoTA))) << std::endl;

    std::cout << "Measurement channel with 2 Kraus operators:\n";
    std::vector<cmat> Ks {st.pz0, st.pz1}; // 2 Kraus operators
    std::cout << disp(Ks[0]) << "\n    and \n" << disp(Ks[1]) << std::endl;

    std::cout << "Superoperator matrix of the channel:\n";
    std::cout << disp(super(Ks)) << std::endl;

    std::cout << "Choi matrix of the channel:\n";
    std::cout << disp(choi(Ks)) << std::endl;

    // apply the channel onto the first subsystem
    cmat rhoOut = apply(rho, Ks, {0});
    std::cout << "After applying the measurement channel on the first qubit:\n";
    std::cout << disp(rhoOut) << std::endl;

    // take the partial trace over the second subsystem
    cmat rhoA = ptrace(rhoOut, {1});
    std::cout << "After partially tracing down the second subsystem:\n";
    std::cout << disp(rhoA) << std::endl;

    // compute the vonNeumann entropy
    double ent = entropy(rhoA);
    std::cout << "Entropy: " << ent << std::endl;
}<commit_msg>commit<commit_after>// Quantum operations
// Source: ./examples/ex4.cpp
#include <qpp.h>
using namespace qpp;

int main()
{
    cmat rho = st.pb00; // projector onto the Bell state (|00>+|11>)/sqrt(2)
    std::cout << "Initial state:\n";
    std::cout << disp(rho) << std::endl;

    // partial transpose of first subsystem
    cmat rhoTA = ptranspose(rho, {0});
    std::cout << "Eigenvalues of the partial transpose of Bell-0 state are:\n";
    std::cout << disp(transpose(hevals(rhoTA))) << std::endl;

    std::cout << "Measurement channel with 2 Kraus operators:\n";
    std::vector<cmat> Ks {st.pz0, st.pz1}; // 2 Kraus operators
    std::cout << disp(Ks[0]) << "\n    and \n" << disp(Ks[1]) << std::endl;

    std::cout << "Superoperator matrix of the channel:\n";
    std::cout << disp(super(Ks)) << std::endl;

    std::cout << "Choi matrix of the channel:\n";
    std::cout << disp(choi(Ks)) << std::endl;

    // apply the channel onto the first subsystem
    cmat rhoOut = apply(rho, Ks, {0});
    std::cout << "After applying the measurement channel on the first qubit:\n";
    std::cout << disp(rhoOut) << std::endl;

    // take the partial trace over the second subsystem
    cmat rhoA = ptrace(rhoOut, {1});
    std::cout << "After partially tracing down the second subsystem:\n";
    std::cout << disp(rhoA) << std::endl;

    // compute the von-Neumann entropy
    double ent = entropy(rhoA);
    std::cout << "Entropy: " << ent << std::endl;
}<|endoftext|>


<commit_before>#include "PPWindow.h"

PPWindow::PPWindow(ParametersContainer pc, Generator g):
	outputLabel(g.getPPConversion(pc.getInput())),
	translateButton("Translate")
{
	gen = g;

	set_title("PP-Converter");
	set_border_width(5);

	add(v_box);
	add(outputLabel);

	v_box.pack_start(entryField);
	v_box.pack_start(translateButton);
	v_box.pack_start(outputLabel);

	translateButton.signal_clicked().connect(sigc::mem_fun(*this,
              &PPWindow::on_button_clicked));

	show_all_children();
}

PPWindow::~PPWindow(){

}

void PPWindow::on_button_clicked(){
	outputLabel.set_text(gen.getPPConversion(entryField.get_text()));
}<commit_msg>removed obsolete statement<commit_after>#include "PPWindow.h"

PPWindow::PPWindow(ParametersContainer pc, Generator g):
	outputLabel(g.getPPConversion(pc.getInput())),
	translateButton("Translate")
{
	gen = g;

	set_title("PP-Converter");
	set_border_width(5);

	add(v_box);

	v_box.pack_start(entryField);
	v_box.pack_start(translateButton);
	v_box.pack_start(outputLabel);

	translateButton.signal_clicked().connect(sigc::mem_fun(*this,
              &PPWindow::on_button_clicked));

	show_all_children();
}

PPWindow::~PPWindow(){

}

void PPWindow::on_button_clicked(){
	outputLabel.set_text(gen.getPPConversion(entryField.get_text()));
}<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gfx/font.h"

#include <windows.h>
#include <math.h>

#include <algorithm>

#include "base/logging.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "gfx/canvas_skia.h"

namespace gfx {

// static
Font::HFontRef* Font::base_font_ref_;

// static
Font::AdjustFontCallback Font::adjust_font_callback = NULL;
Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL;

// If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
// font is bold.
static const int kTextMetricWeightBold = 700;

// Returns either minimum font allowed for a current locale or
// lf_height + size_delta value.
static int AdjustFontSize(int lf_height, int size_delta) {
  if (lf_height < 0) {
    lf_height -= size_delta;
  } else {
    lf_height += size_delta;
  }
  int min_font_size = 0;
  if (Font::get_minimum_font_size_callback)
    min_font_size = Font::get_minimum_font_size_callback();
  // Make sure lf_height is not smaller than allowed min font size for current
  // locale.
  if (abs(lf_height) < min_font_size) {
    return lf_height < 0 ? -min_font_size : min_font_size;
  } else {
    return lf_height;
  }
}

//
// Font
//

Font::Font()
    : font_ref_(GetBaseFontRef()) {
}

int Font::height() const {
  return font_ref_->height();
}

int Font::baseline() const {
  return font_ref_->baseline();
}

int Font::ave_char_width() const {
  return font_ref_->ave_char_width();
}

int Font::GetExpectedTextWidth(int length) const {
  return length * std::min(font_ref_->dlu_base_x(), ave_char_width());
}

int Font::style() const {
  return font_ref_->style();
}

NativeFont Font::nativeFont() const {
  return hfont();
}

// static
Font Font::CreateFont(HFONT font) {
  DCHECK(font);
  LOGFONT font_info;
  GetObject(font, sizeof(LOGFONT), &font_info);
  return Font(CreateHFontRef(CreateFontIndirect(&font_info)));
}

Font Font::CreateFont(const std::wstring& font_name, int font_size) {
  HDC hdc = GetDC(NULL);
  long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72);
  ReleaseDC(NULL, hdc);
  HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    font_name.c_str());
  return Font::CreateFont(hf);
}

// static
Font::HFontRef* Font::GetBaseFontRef() {
  if (base_font_ref_ == NULL) {
    NONCLIENTMETRICS metrics;
    win_util::GetNonClientMetrics(&metrics);

    if (adjust_font_callback)
      adjust_font_callback(&metrics.lfMessageFont);
    metrics.lfMessageFont.lfHeight =
        AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
    HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
    DLOG_ASSERT(font);
    base_font_ref_ = Font::CreateHFontRef(font);
    // base_font_ref_ is global, up the ref count so it's never deleted.
    base_font_ref_->AddRef();
  }
  return base_font_ref_;
}

const std::wstring& Font::FontName() const {
  return font_ref_->font_name();
}

int Font::FontSize() {
  LOGFONT font_info;
  GetObject(hfont(), sizeof(LOGFONT), &font_info);
  long lf_height = font_info.lfHeight;
  HDC hdc = GetDC(NULL);
  int device_caps = GetDeviceCaps(hdc, LOGPIXELSY);
  int font_size = 0;
  if (device_caps != 0) {
    float font_size_float = -static_cast<float>(lf_height)*72/device_caps;
    font_size = static_cast<int>(::ceil(font_size_float - 0.5));
  }
  ReleaseDC(NULL, hdc);
  return font_size;
}

Font::HFontRef::HFontRef(HFONT hfont,
         int height,
         int baseline,
         int ave_char_width,
         int style,
         int dlu_base_x)
    : hfont_(hfont),
      height_(height),
      baseline_(baseline),
      ave_char_width_(ave_char_width),
      style_(style),
      dlu_base_x_(dlu_base_x) {
  DLOG_ASSERT(hfont);

  LOGFONT font_info;
  GetObject(hfont_, sizeof(LOGFONT), &font_info);
  font_name_ = std::wstring(font_info.lfFaceName);
}

Font::HFontRef::~HFontRef() {
  DeleteObject(hfont_);
}

Font Font::DeriveFont(int size_delta, int style) const {
  LOGFONT font_info;
  GetObject(hfont(), sizeof(LOGFONT), &font_info);
  font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta);
  font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED);
  font_info.lfItalic = ((style & ITALIC) == ITALIC);
  font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL;

  HFONT hfont = CreateFontIndirect(&font_info);
  return Font(CreateHFontRef(hfont));
}

int Font::GetStringWidth(const std::wstring& text) const {
  int width = 0;
  HDC dc = GetDC(NULL);
  HFONT previous_font = static_cast<HFONT>(SelectObject(dc, hfont()));
  SIZE size;
  if (GetTextExtentPoint32(dc, text.c_str(), static_cast<int>(text.size()),
                           &size)) {
    width = size.cx;
  } else {
    width = 0;
  }
  SelectObject(dc, previous_font);
  ReleaseDC(NULL, dc);
  return width;
}

Font::HFontRef* Font::CreateHFontRef(HFONT font) {
  TEXTMETRIC font_metrics;
  HDC screen_dc = GetDC(NULL);
  HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font));
  int last_map_mode = SetMapMode(screen_dc, MM_TEXT);
  GetTextMetrics(screen_dc, &font_metrics);
  // Yes, this is how Microsoft recommends calculating the dialog unit
  // conversions.
  SIZE ave_text_size;
  GetTextExtentPoint32(screen_dc,
                       L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
                       52, &ave_text_size);
  const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
  // To avoid the DC referencing font_handle_, select the previous font.
  SelectObject(screen_dc, previous_font);
  SetMapMode(screen_dc, last_map_mode);
  ReleaseDC(NULL, screen_dc);

  const int height = std::max(1, static_cast<int>(font_metrics.tmHeight));
  const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent));
  const int ave_char_width =
      std::max(1, static_cast<int>(font_metrics.tmAveCharWidth));
  int style = 0;
  if (font_metrics.tmItalic) {
    style |= Font::ITALIC;
  }
  if (font_metrics.tmUnderlined) {
    style |= Font::UNDERLINED;
  }
  if (font_metrics.tmWeight >= kTextMetricWeightBold) {
    style |= Font::BOLD;
  }

  return new HFontRef(font, height, baseline, ave_char_width, style,
                      dlu_base_x);
}

}  // namespace gfx
<commit_msg>Revert 52441 - Revert Win specific elements of 46492 to look for perf impact<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gfx/font.h"

#include <windows.h>
#include <math.h>

#include <algorithm>

#include "base/logging.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "gfx/canvas_skia.h"

namespace gfx {

// static
Font::HFontRef* Font::base_font_ref_;

// static
Font::AdjustFontCallback Font::adjust_font_callback = NULL;
Font::GetMinimumFontSizeCallback Font::get_minimum_font_size_callback = NULL;

// If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
// font is bold.
static const int kTextMetricWeightBold = 700;

// Returns either minimum font allowed for a current locale or
// lf_height + size_delta value.
static int AdjustFontSize(int lf_height, int size_delta) {
  if (lf_height < 0) {
    lf_height -= size_delta;
  } else {
    lf_height += size_delta;
  }
  int min_font_size = 0;
  if (Font::get_minimum_font_size_callback)
    min_font_size = Font::get_minimum_font_size_callback();
  // Make sure lf_height is not smaller than allowed min font size for current
  // locale.
  if (abs(lf_height) < min_font_size) {
    return lf_height < 0 ? -min_font_size : min_font_size;
  } else {
    return lf_height;
  }
}

//
// Font
//

Font::Font()
    : font_ref_(GetBaseFontRef()) {
}

int Font::height() const {
  return font_ref_->height();
}

int Font::baseline() const {
  return font_ref_->baseline();
}

int Font::ave_char_width() const {
  return font_ref_->ave_char_width();
}

int Font::GetExpectedTextWidth(int length) const {
  return length * std::min(font_ref_->dlu_base_x(), ave_char_width());
}

int Font::style() const {
  return font_ref_->style();
}

NativeFont Font::nativeFont() const {
  return hfont();
}

// static
Font Font::CreateFont(HFONT font) {
  DCHECK(font);
  LOGFONT font_info;
  GetObject(font, sizeof(LOGFONT), &font_info);
  return Font(CreateHFontRef(CreateFontIndirect(&font_info)));
}

Font Font::CreateFont(const std::wstring& font_name, int font_size) {
  HDC hdc = GetDC(NULL);
  long lf_height = -MulDiv(font_size, GetDeviceCaps(hdc, LOGPIXELSY), 72);
  ReleaseDC(NULL, hdc);
  HFONT hf = ::CreateFont(lf_height, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    font_name.c_str());
  return Font::CreateFont(hf);
}

// static
Font::HFontRef* Font::GetBaseFontRef() {
  if (base_font_ref_ == NULL) {
    NONCLIENTMETRICS metrics;
    win_util::GetNonClientMetrics(&metrics);

    if (adjust_font_callback)
      adjust_font_callback(&metrics.lfMessageFont);
    metrics.lfMessageFont.lfHeight =
        AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
    HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
    DLOG_ASSERT(font);
    base_font_ref_ = Font::CreateHFontRef(font);
    // base_font_ref_ is global, up the ref count so it's never deleted.
    base_font_ref_->AddRef();
  }
  return base_font_ref_;
}

const std::wstring& Font::FontName() const {
  return font_ref_->font_name();
}

int Font::FontSize() {
  LOGFONT font_info;
  GetObject(hfont(), sizeof(LOGFONT), &font_info);
  long lf_height = font_info.lfHeight;
  HDC hdc = GetDC(NULL);
  int device_caps = GetDeviceCaps(hdc, LOGPIXELSY);
  int font_size = 0;
  if (device_caps != 0) {
    float font_size_float = -static_cast<float>(lf_height)*72/device_caps;
    font_size = static_cast<int>(::ceil(font_size_float - 0.5));
  }
  ReleaseDC(NULL, hdc);
  return font_size;
}

Font::HFontRef::HFontRef(HFONT hfont,
         int height,
         int baseline,
         int ave_char_width,
         int style,
         int dlu_base_x)
    : hfont_(hfont),
      height_(height),
      baseline_(baseline),
      ave_char_width_(ave_char_width),
      style_(style),
      dlu_base_x_(dlu_base_x) {
  DLOG_ASSERT(hfont);

  LOGFONT font_info;
  GetObject(hfont_, sizeof(LOGFONT), &font_info);
  font_name_ = std::wstring(font_info.lfFaceName);
}

Font::HFontRef::~HFontRef() {
  DeleteObject(hfont_);
}

Font Font::DeriveFont(int size_delta, int style) const {
  LOGFONT font_info;
  GetObject(hfont(), sizeof(LOGFONT), &font_info);
  font_info.lfHeight = AdjustFontSize(font_info.lfHeight, size_delta);
  font_info.lfUnderline = ((style & UNDERLINED) == UNDERLINED);
  font_info.lfItalic = ((style & ITALIC) == ITALIC);
  font_info.lfWeight = (style & BOLD) ? FW_BOLD : FW_NORMAL;

  HFONT hfont = CreateFontIndirect(&font_info);
  return Font(CreateHFontRef(hfont));
}

int Font::GetStringWidth(const std::wstring& text) const {
  int width = 0, height = 0;
  CanvasSkia::SizeStringInt(text, *this, &width, &height,
                            gfx::Canvas::NO_ELLIPSIS);
  return width;
}

Font::HFontRef* Font::CreateHFontRef(HFONT font) {
  TEXTMETRIC font_metrics;
  HDC screen_dc = GetDC(NULL);
  HFONT previous_font = static_cast<HFONT>(SelectObject(screen_dc, font));
  int last_map_mode = SetMapMode(screen_dc, MM_TEXT);
  GetTextMetrics(screen_dc, &font_metrics);
  // Yes, this is how Microsoft recommends calculating the dialog unit
  // conversions.
  SIZE ave_text_size;
  GetTextExtentPoint32(screen_dc,
                       L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
                       52, &ave_text_size);
  const int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
  // To avoid the DC referencing font_handle_, select the previous font.
  SelectObject(screen_dc, previous_font);
  SetMapMode(screen_dc, last_map_mode);
  ReleaseDC(NULL, screen_dc);

  const int height = std::max(1, static_cast<int>(font_metrics.tmHeight));
  const int baseline = std::max(1, static_cast<int>(font_metrics.tmAscent));
  const int ave_char_width =
      std::max(1, static_cast<int>(font_metrics.tmAveCharWidth));
  int style = 0;
  if (font_metrics.tmItalic) {
    style |= Font::ITALIC;
  }
  if (font_metrics.tmUnderlined) {
    style |= Font::UNDERLINED;
  }
  if (font_metrics.tmWeight >= kTextMetricWeightBold) {
    style |= Font::BOLD;
  }

  return new HFontRef(font, height, baseline, ave_char_width, style,
                      dlu_base_x);
}

}  // namespace gfx
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <string>
#include <set>
#include <vector>

#include "mock_facility.h"
#include "request.h"
#include "request_portfolio.h"
#include "bid.h"
#include "bid_portfolio.h"
#include "resource.h"
#include "test_context.h"
#include "trader.h"

#include "exchange_context.h"

using std::string;
using std::set;
using std::vector;

using cyclus::ExchangeContext;
using cyclus::Request;
using cyclus::RequestPortfolio;
using cyclus::Bid;
using cyclus::BidPortfolio;
using cyclus::PrefMap;
using cyclus::Resource;
using cyclus::TestContext;
using cyclus::Trader;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ExchangeContextTests: public ::testing::Test {
 protected:
  TestContext tc;
  MockFacility* fac1;
  MockFacility* fac2;
  Request<Resource>::Ptr req1, req2;
  RequestPortfolio<Resource> rp1, rp2;
  string commod1, commod2;

  virtual void SetUp() {
    fac1 = new MockFacility(tc.get());
    fac2 = new MockFacility(tc.get());

    commod1 = "commod1";
    req1 = Request<Resource>::Ptr(new Request<Resource>());
    req1->commodity = commod1;
    req1->requester = fac1;

    req2 = Request<Resource>::Ptr(new Request<Resource>());
    req2->commodity = commod1;
    req2->requester = fac2;

    rp1.AddRequest(req1);
    rp2.AddRequest(req2);
  };

  virtual void TearDown() {
    rp1.Clear();
    rp2.Clear();
    delete fac1;
    delete fac2;
  };
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, Empty) {
  ExchangeContext<Resource> context;
  EXPECT_TRUE(context.requests().empty());
  EXPECT_TRUE(context.RequestsForCommod(commod2).empty());
  EXPECT_TRUE(context.RequestsForCommod(commod2).empty());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest1) {
  // 1 request for 1 commod
  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);

  std::vector<RequestPortfolio<Resource> > vp;
  vp.push_back(rp1);
  EXPECT_EQ(vp, context.requests());

  EXPECT_EQ(1, context.RequestsForCommod(commod1).size());
  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));

  EXPECT_EQ(1, context.requesters().size());
  std::set<const Trader*> requesters;
  requesters.insert(fac1);
  EXPECT_EQ(requesters, context.requesters());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest2) {
  // 2 requests for 1 commod
  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);
  context.AddRequestPortfolio(rp2);

  std::vector<RequestPortfolio<Resource> > vp;
  vp.push_back(rp1);
  vp.push_back(rp2);
  EXPECT_EQ(vp, context.requests());

  EXPECT_EQ(2, context.RequestsForCommod(commod1).size());
  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  vr.push_back(req2);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest3) {
  // 2 requests for 2 commod
  Request<Resource>::Ptr req = Request<Resource>::Ptr(new Request<Resource>());
  req->commodity = commod2;
  req->requester = fac1;
  rp1.AddRequest(req);

  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);

  EXPECT_EQ(1, context.RequestsForCommod(commod1).size());
  EXPECT_EQ(1, context.RequestsForCommod(commod2).size());

  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));

  vr.clear();
  vr.push_back(req);
  EXPECT_EQ(vr, context.RequestsForCommod(commod2));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddBid1) {
  // bid bid for a request
  ExchangeContext<Resource> context;
  context.AddRequestPortfolio(rp1);

  EXPECT_TRUE(context.BidsForRequest(req1).empty());

  Bid<Resource>::Ptr bid = Bid<Resource>::Ptr(new Bid<Resource>());
  bid->request = req1;
  bid->bidder = fac1;
  BidPortfolio<Resource> bp1;
  bp1.AddBid(bid);

  context.AddBidPortfolio(bp1);

  std::vector<BidPortfolio<Resource> > vp;
  vp.push_back(bp1);
  EXPECT_EQ(vp, context.bids());

  EXPECT_EQ(1, context.BidsForRequest(req1).size());

  std::vector<Bid<Resource>::Ptr> vr;
  vr.push_back(bid);
  EXPECT_EQ(vr, context.BidsForRequest(req1));

  EXPECT_EQ(1, context.bidders().size());
  std::set<const Trader*> bidders;
  bidders.insert(fac1);
  EXPECT_EQ(bidders, context.bidders());

  PrefMap<Resource>::type obs;
  obs[req1].push_back(std::make_pair(bid, req1->preference));
  EXPECT_EQ(context.Prefs(req1->requester), obs);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddBid2) {
  // multiple bids for multiple requests
  ExchangeContext<Resource> context;
  context.AddRequestPortfolio(rp1);
  context.AddRequestPortfolio(rp2);

  EXPECT_TRUE(context.BidsForRequest(req1).empty());
  EXPECT_TRUE(context.BidsForRequest(req2).empty());

  // bid1 and bid2 are from one bidder (fac1)
  BidPortfolio<Resource> bp1;
  Bid<Resource>::Ptr bid1 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid1->request = req1;
  bid1->bidder = fac1;
  bp1.AddBid(bid1);
  Bid<Resource>::Ptr bid2 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid2->request = req2;
  bid2->bidder = fac1;
  bp1.AddBid(bid2);

  // bid3 and bid4 are from one bidder (fac2)
  BidPortfolio<Resource> bp2;
  Bid<Resource>::Ptr bid3 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid3->request = req1;
  bid3->bidder = fac2;
  bp2.AddBid(bid3);
  Bid<Resource>::Ptr bid4 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid4->request = req2;
  bid4->bidder = fac2;
  bp2.AddBid(bid4);

  std::vector<BidPortfolio<Resource> > vp;
  std::vector<Bid<Resource>::Ptr> vreq1;
  std::vector<Bid<Resource>::Ptr> vreq2;

  // add bids from first bidder
  context.AddBidPortfolio(bp1);

  vp.push_back(bp1);
  EXPECT_EQ(vp, context.bids());

  vreq1.push_back(bid1);
  vreq2.push_back(bid2);
  EXPECT_EQ(1, context.BidsForRequest(req1).size());
  EXPECT_EQ(1, context.BidsForRequest(req2).size());
  EXPECT_EQ(vreq1, context.BidsForRequest(req1));
  EXPECT_EQ(vreq2, context.BidsForRequest(req2));

  // add bids from second bidder
  context.AddBidPortfolio(bp2);

  vp.push_back(bp2);
  EXPECT_EQ(vp, context.bids());

  vreq1.push_back(bid3);
  vreq2.push_back(bid4);
  EXPECT_EQ(2, context.BidsForRequest(req1).size());
  EXPECT_EQ(2, context.BidsForRequest(req2).size());
  EXPECT_EQ(vreq1, context.BidsForRequest(req1));
  EXPECT_EQ(vreq2, context.BidsForRequest(req2));

  EXPECT_EQ(2, context.bidders().size());
  std::set<const Trader*> bidders;
  bidders.insert(fac1);
  bidders.insert(fac2);
  EXPECT_EQ(bidders, context.bidders());
}
<commit_msg>added a test for non equality of pref maps<commit_after>#include <gtest/gtest.h>

#include <string>
#include <set>
#include <vector>

#include "mock_facility.h"
#include "request.h"
#include "request_portfolio.h"
#include "bid.h"
#include "bid_portfolio.h"
#include "resource.h"
#include "test_context.h"
#include "trader.h"

#include "exchange_context.h"

using std::string;
using std::set;
using std::vector;

using cyclus::ExchangeContext;
using cyclus::Request;
using cyclus::RequestPortfolio;
using cyclus::Bid;
using cyclus::BidPortfolio;
using cyclus::PrefMap;
using cyclus::Resource;
using cyclus::TestContext;
using cyclus::Trader;

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ExchangeContextTests: public ::testing::Test {
 protected:
  TestContext tc;
  MockFacility* fac1;
  MockFacility* fac2;
  Request<Resource>::Ptr req1, req2;
  RequestPortfolio<Resource> rp1, rp2;
  string commod1, commod2;
  double pref;

  virtual void SetUp() {
    fac1 = new MockFacility(tc.get());
    fac2 = new MockFacility(tc.get());

    pref = 0.5;
    commod1 = "commod1";
    req1 = Request<Resource>::Ptr(new Request<Resource>());
    req1->commodity = commod1;
    req1->requester = fac1;
    req1->preference = pref;

    req2 = Request<Resource>::Ptr(new Request<Resource>());
    req2->commodity = commod1;
    req2->requester = fac2;
    req2->preference = pref;

    rp1.AddRequest(req1);
    rp2.AddRequest(req2);
  };

  virtual void TearDown() {
    rp1.Clear();
    rp2.Clear();
    delete fac1;
    delete fac2;
  };
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, Empty) {
  ExchangeContext<Resource> context;
  EXPECT_TRUE(context.requests().empty());
  EXPECT_TRUE(context.RequestsForCommod(commod2).empty());
  EXPECT_TRUE(context.RequestsForCommod(commod2).empty());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest1) {
  // 1 request for 1 commod
  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);

  std::vector<RequestPortfolio<Resource> > vp;
  vp.push_back(rp1);
  EXPECT_EQ(vp, context.requests());

  EXPECT_EQ(1, context.RequestsForCommod(commod1).size());
  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));

  EXPECT_EQ(1, context.requesters().size());
  std::set<const Trader*> requesters;
  requesters.insert(fac1);
  EXPECT_EQ(requesters, context.requesters());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest2) {
  // 2 requests for 1 commod
  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);
  context.AddRequestPortfolio(rp2);

  std::vector<RequestPortfolio<Resource> > vp;
  vp.push_back(rp1);
  vp.push_back(rp2);
  EXPECT_EQ(vp, context.requests());

  EXPECT_EQ(2, context.RequestsForCommod(commod1).size());
  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  vr.push_back(req2);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddRequest3) {
  // 2 requests for 2 commod
  Request<Resource>::Ptr req = Request<Resource>::Ptr(new Request<Resource>());
  req->commodity = commod2;
  req->requester = fac1;
  rp1.AddRequest(req);

  ExchangeContext<Resource> context;

  context.AddRequestPortfolio(rp1);

  EXPECT_EQ(1, context.RequestsForCommod(commod1).size());
  EXPECT_EQ(1, context.RequestsForCommod(commod2).size());

  std::vector<Request<Resource>::Ptr> vr;
  vr.push_back(req1);
  EXPECT_EQ(vr, context.RequestsForCommod(commod1));

  vr.clear();
  vr.push_back(req);
  EXPECT_EQ(vr, context.RequestsForCommod(commod2));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddBid1) {
  // bid bid for a request
  ExchangeContext<Resource> context;
  context.AddRequestPortfolio(rp1);

  EXPECT_TRUE(context.BidsForRequest(req1).empty());

  Bid<Resource>::Ptr bid = Bid<Resource>::Ptr(new Bid<Resource>());
  bid->request = req1;
  bid->bidder = fac1;
  BidPortfolio<Resource> bp1;
  bp1.AddBid(bid);

  context.AddBidPortfolio(bp1);

  std::vector<BidPortfolio<Resource> > vp;
  vp.push_back(bp1);
  EXPECT_EQ(vp, context.bids());

  EXPECT_EQ(1, context.BidsForRequest(req1).size());

  std::vector<Bid<Resource>::Ptr> vr;
  vr.push_back(bid);
  EXPECT_EQ(vr, context.BidsForRequest(req1));

  EXPECT_EQ(1, context.bidders().size());
  std::set<const Trader*> bidders;
  bidders.insert(fac1);
  EXPECT_EQ(bidders, context.bidders());

  PrefMap<Resource>::type obs;
  obs[req1].push_back(std::make_pair(bid, req1->preference));
  EXPECT_EQ(context.Prefs(req1->requester), obs);
  obs.clear();
  obs[req1].push_back(std::make_pair(bid, req1->preference * 0.1));
  EXPECT_NE(context.Prefs(req1->requester), obs);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(ExchangeContextTests, AddBid2) {
  // multiple bids for multiple requests
  ExchangeContext<Resource> context;
  context.AddRequestPortfolio(rp1);
  context.AddRequestPortfolio(rp2);

  EXPECT_TRUE(context.BidsForRequest(req1).empty());
  EXPECT_TRUE(context.BidsForRequest(req2).empty());

  // bid1 and bid2 are from one bidder (fac1)
  BidPortfolio<Resource> bp1;
  Bid<Resource>::Ptr bid1 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid1->request = req1;
  bid1->bidder = fac1;
  bp1.AddBid(bid1);
  Bid<Resource>::Ptr bid2 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid2->request = req2;
  bid2->bidder = fac1;
  bp1.AddBid(bid2);

  // bid3 and bid4 are from one bidder (fac2)
  BidPortfolio<Resource> bp2;
  Bid<Resource>::Ptr bid3 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid3->request = req1;
  bid3->bidder = fac2;
  bp2.AddBid(bid3);
  Bid<Resource>::Ptr bid4 = Bid<Resource>::Ptr(new Bid<Resource>());
  bid4->request = req2;
  bid4->bidder = fac2;
  bp2.AddBid(bid4);

  std::vector<BidPortfolio<Resource> > vp;
  std::vector<Bid<Resource>::Ptr> vreq1;
  std::vector<Bid<Resource>::Ptr> vreq2;

  // add bids from first bidder
  context.AddBidPortfolio(bp1);

  vp.push_back(bp1);
  EXPECT_EQ(vp, context.bids());

  vreq1.push_back(bid1);
  vreq2.push_back(bid2);
  EXPECT_EQ(1, context.BidsForRequest(req1).size());
  EXPECT_EQ(1, context.BidsForRequest(req2).size());
  EXPECT_EQ(vreq1, context.BidsForRequest(req1));
  EXPECT_EQ(vreq2, context.BidsForRequest(req2));

  // add bids from second bidder
  context.AddBidPortfolio(bp2);

  vp.push_back(bp2);
  EXPECT_EQ(vp, context.bids());

  vreq1.push_back(bid3);
  vreq2.push_back(bid4);
  EXPECT_EQ(2, context.BidsForRequest(req1).size());
  EXPECT_EQ(2, context.BidsForRequest(req2).size());
  EXPECT_EQ(vreq1, context.BidsForRequest(req1));
  EXPECT_EQ(vreq2, context.BidsForRequest(req2));

  EXPECT_EQ(2, context.bidders().size());
  std::set<const Trader*> bidders;
  bidders.insert(fac1);
  bidders.insert(fac2);
  EXPECT_EQ(bidders, context.bidders());
}
<|endoftext|>


<commit_before>// $Id$
// Category: plane
//
// Class AliMpPlaneSegmentation
// ----------------------------
// Class describing the segmentation of the plane.
//
// Transformation of pad characteristics according to sectors:
//
//   I.  ( posId,  Guassi ), ( i, j), ( x, y)         II. |  I.
//  II.  ( posId', Guassi'), (-i, j), (-x, y)       _____ | ____
// III.  (-posId,  Guassi),  (-i,-j), (-x,-y)             |
//  IV.  (-posId', Guassi'), ( i,-j), ( x,-y)        III. |  IV.
//
// Where (posId', Guassi') is the location of the pad
// in the clipped sector.
//
// Authors: David Guez, Ivana Hrivnacova; IPN Orsay

#include <Riostream.h>
#include <TMath.h>

#include "AliMpPlaneSegmentation.h"
#include "AliMpPlaneAreaPadIterator.h"
#include "AliMpPlane.h"
#include "AliMpSectorPosition.h"
#include "AliMpSectorSegmentation.h"

ClassImp(AliMpPlaneSegmentation)

//_____________________________________________________________________________
AliMpPlaneSegmentation::AliMpPlaneSegmentation(const AliMpPlane* plane)
  : AliMpVSegmentation(),
    fkPlane(plane),
    fFrontSectorSegmentation(0),
    fBackSectorSegmentation(0)
{
//
  fFrontSectorSegmentation = new AliMpSectorSegmentation(plane->GetFrontSector());
  fBackSectorSegmentation = new AliMpSectorSegmentation(plane->GetBackSector());

  for (Int_t i=0; i<fkPlane->GetNofSectorPositions(); i++) {
    fTransformers.push_back(
      new AliMpTransformer(fkPlane->GetSectorPosition(i)->GetOffset(),
                           fkPlane->GetSectorPosition(i)->GetScale()));
  }
}

///_____________________________________________________________________________
AliMpPlaneSegmentation::AliMpPlaneSegmentation()
  : AliMpVSegmentation(),
    fkPlane(0),
    fFrontSectorSegmentation(0),
    fBackSectorSegmentation(0)
{
//
}

//_____________________________________________________________________________
AliMpPlaneSegmentation::~AliMpPlaneSegmentation() {
//
  delete fFrontSectorSegmentation;
  delete fBackSectorSegmentation;

  for (Int_t i=0; i<GetNofTransformers(); i++)
    delete GetTransformer(i);
}

//
// private methods
//

//_____________________________________________________________________________
const AliMpTransformer*
AliMpPlaneSegmentation::GetTransformer(const AliMpIntPair& scale) const
{
// Returns the sector position specified by scale.
// ---

  for (UInt_t i=0; i<fTransformers.size(); i++)
    if (fTransformers[i]->GetScale() == scale) return fTransformers[i];

  Fatal("GetTransformer", "Wrong scale");
  return 0;
}

//_____________________________________________________________________________
AliMpIntPair AliMpPlaneSegmentation::GetScale(const AliMpIntPair& pair) const
{
// Returns pair of the signs of the values of the given pair.
// ---

  AliMpIntPair scale(1, 1);

  if (pair.GetFirst() < 0)  scale.SetFirst(-1);
  if (pair.GetSecond() < 0) scale.SetSecond(-1);

  return scale;
}

//_____________________________________________________________________________
AliMpIntPair AliMpPlaneSegmentation::GetScale(const TVector2& vector) const
{
// Returns pair of the signs of the values of the given vector.
// ---

  AliMpIntPair scale(1, 1);

  if (vector.X() < 0) scale.SetFirst(-1);
  if (vector.Y() < 0) scale.SetSecond(-1);

  return scale;
}

//_____________________________________________________________________________
AliMpIntPair
AliMpPlaneSegmentation::GetLocationScale(const AliMpIntPair& location) const
{
// Returns the scale transformation of the specified location.
// ---

  // Find the sector
  Bool_t inFront;
  if (fFrontSectorSegmentation
        ->HasMotifPosition(TMath::Abs(location.GetFirst())))
    inFront = true;
  else if (fBackSectorSegmentation
             ->HasMotifPosition(TMath::Abs(location.GetFirst())))
    inFront = false;
  else {
    Fatal("GetLocationScale", "Motif position not found.");
    return AliMpIntPair();
  }

  if      (inFront  && location.GetFirst() > 0) return  AliMpIntPair(1, 1);
  else if (inFront  && location.GetFirst() < 0) return  AliMpIntPair(-1, -1);
  else if (!inFront && location.GetFirst() > 0) return  AliMpIntPair(-1, 1);
  else if (!inFront && location.GetFirst() < 0) return  AliMpIntPair( 1,-1);

  // cannot get there
  Fatal("GetLocationScale", "Condition failed.");
  return AliMpIntPair();
}

//_____________________________________________________________________________
AliMpSectorSegmentation*
AliMpPlaneSegmentation::GetSectorSegmentation(const AliMpIntPair& scale) const
{
// Returns front sector or back sector segmentation
// according to quadrant specified by scale.
// ---

  if (scale.GetFirst()*scale.GetSecond() > 0) {
    // quadrant I or III
    return fFrontSectorSegmentation;
  }
  else  {
    // quadrant II or IV
    return fBackSectorSegmentation;
  }
}

//_____________________________________________________________________________
AliMpSectorSegmentation*
AliMpPlaneSegmentation::GetSectorSegmentation(Int_t motifPositionId) const
{
// Returns front sector or back sector segmentation
// according to specified motifPositionId
// ---

  if (fFrontSectorSegmentation->HasMotifPosition(motifPositionId))
    return fFrontSectorSegmentation;
  else if (fBackSectorSegmentation->HasMotifPosition(motifPositionId))
    return fBackSectorSegmentation;
  else {
    Fatal("GetSectorSegmentation", "Motif position not found.");
    return 0;
  }
}

//
// public methods
//

//_____________________________________________________________________________
AliMpVPadIterator*
AliMpPlaneSegmentation::CreateIterator(const AliMpArea& area) const
{
// Creates the are iterator.
// (The inherited method cannot be used)
// ---

  return new AliMpPlaneAreaPadIterator(this, area);
}

//______________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByLocation(const AliMpIntPair& location,
                                       Bool_t warning) const
{
// Find the pad which corresponds to the given location
// ---

  // Get segmentation
  AliMpSectorSegmentation* segmentation
    = GetSectorSegmentation(TMath::Abs(location.GetFirst()));

  // Get pad in the segmentation
  AliMpPad pad
     = segmentation
       ->PadByLocation(
           AliMpIntPair(TMath::Abs(location.GetFirst()),location.GetSecond()));

  // Get transformation
  AliMpIntPair scale  = GetLocationScale(location);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  // Transform pad characteristics
  return kTransformer->Transform(pad);
}

//______________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByIndices (const AliMpIntPair& indices,
                                               Bool_t warning ) const
{
// Find the pad which corresponds to the given indices
//

  AliMpIntPair scale = GetScale(indices);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpIntPair scaledIndices = kTransformer->Scale(indices);
  AliMpPad pad
    = GetSectorSegmentation(scale)->PadByIndices(scaledIndices, warning);

  return kTransformer->Transform(pad);
}

//_____________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByPosition(const TVector2& position,
                                               Bool_t warning) const
{
// Find the pad which corresponds to the given position
// ---

  AliMpIntPair scale = GetScale(position);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  TVector2 scaledPosition = kTransformer->ITransform(position);
  AliMpPad pad
    = GetSectorSegmentation(scale)->PadByPosition(scaledPosition, warning);

  return kTransformer->Transform(pad);
}

//_____________________________________________________________________________
Bool_t AliMpPlaneSegmentation::HasPad(const AliMpIntPair& indices) const
{
// Does the pad located by <indices> exists ?
// ---

  AliMpIntPair scale = GetScale(indices);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpIntPair scaledIndices = kTransformer->Scale(indices);

  return GetSectorSegmentation(scale)->HasPad(scaledIndices);
}

//_____________________________________________________________________________
Int_t AliMpPlaneSegmentation::Zone(const AliMpPad& pad, Bool_t warning) const
{
// Returns the zone index of the zone containing the specified pad.
// This zone index is different from the zone ID,
// as it is unique for each pad dimensions.
// It is composed in this way:
//   sectorID*100 + zoneID*10 + specific index
// Where sectorID = 0,1 for front/back sector.
// Specific index is present only for zones containing special motifs.
// ---

  if (!pad.IsValid()) {
    if (warning) Warning("Zone(AliMpPad)", "Invalid pad");
    return 0;
  }

  AliMpIntPair scale = GetScale(pad.GetIndices());
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpPad scaledPad = kTransformer->ITransform(pad);

  AliMpSectorSegmentation* segmentation = GetSectorSegmentation(scale);
  Int_t zoneID = segmentation->Zone(scaledPad, warning);

  // Distinguish zones from front/back sector
  // For back sector - add 10
  if (segmentation == fBackSectorSegmentation) zoneID += 100;

  return zoneID;
}

//_____________________________________________________________________________
TVector2
AliMpPlaneSegmentation::PadDimensions(Int_t zone, Bool_t warning) const
{
// Returns the pad dimensions for the zone with the specified zone index.
// ---

  if (zone < 100)
    return fFrontSectorSegmentation->PadDimensions(zone, warning);
  else
    return fBackSectorSegmentation->PadDimensions(zone - 100, warning);
}

//_____________________________________________________________________________
Bool_t AliMpPlaneSegmentation::CircleTest(const AliMpIntPair& indices) const
{
// Verifies that all methods for retrieving pads are consistents between them.
// Returns true if the pad with specified indices was found and verified,
// false otherwise.
// ---

  if (!HasPad(indices)) return false;

  // Verify the indice->location->position->indice way
  AliMpIntPair location = PadByIndices(indices).GetLocation();
  TVector2 position = PadByLocation(location).Position();
  AliMpIntPair retIndices = PadByPosition(position).GetIndices();

  if (retIndices != indices) {
    cout << "Pad " << indices << " lead to inconsistency" << endl;
    cout << "in indice->location->position->indice way..." << endl;
    cout << "starting from " << indices << "-->" << location << "-->"
         << '(' << position.X() << ',' << position.Y() << ')'
         << " and retIndices: " << retIndices << endl;
  }

  // Verify the indice->position->location->indice way
  position = PadByIndices(indices).Position();
  location = PadByPosition(position).GetLocation();
  retIndices = PadByLocation(location).GetIndices();

  if (retIndices != indices) {
    cout << "Pad " << indices << " lead to inconsistency" << endl;
    cout << "in indice->position->location->indice way..." <<endl;
    cout << "starting from " << indices
         << " and retIndices: " << retIndices << endl;
  }

  return true;

}

//_____________________________________________________________________________
Int_t AliMpPlaneSegmentation::GetNofTransformers() const
{
// Returns number of transformers.
// ---

  return fTransformers.size();
}

//_____________________________________________________________________________
AliMpTransformer* AliMpPlaneSegmentation::GetTransformer(Int_t i) const
{
// Returns i-th transformer.
// ---

  return  fTransformers[i];
}

<commit_msg>PadByLocation() - pass warning parameter to sector segmentation (I.Hrivnacova)<commit_after>// $Id$
// Category: plane
//
// Class AliMpPlaneSegmentation
// ----------------------------
// Class describing the segmentation of the plane.
//
// Transformation of pad characteristics according to sectors:
//
//   I.  ( posId,  Guassi ), ( i, j), ( x, y)         II. |  I.
//  II.  ( posId', Guassi'), (-i, j), (-x, y)       _____ | ____
// III.  (-posId,  Guassi),  (-i,-j), (-x,-y)             |
//  IV.  (-posId', Guassi'), ( i,-j), ( x,-y)        III. |  IV.
//
// Where (posId', Guassi') is the location of the pad
// in the clipped sector.
//
// Authors: David Guez, Ivana Hrivnacova; IPN Orsay

#include <Riostream.h>
#include <TMath.h>

#include "AliMpPlaneSegmentation.h"
#include "AliMpPlaneAreaPadIterator.h"
#include "AliMpPlane.h"
#include "AliMpSectorPosition.h"
#include "AliMpSectorSegmentation.h"

ClassImp(AliMpPlaneSegmentation)

//_____________________________________________________________________________
AliMpPlaneSegmentation::AliMpPlaneSegmentation(const AliMpPlane* plane)
  : AliMpVSegmentation(),
    fkPlane(plane),
    fFrontSectorSegmentation(0),
    fBackSectorSegmentation(0)
{
//
  fFrontSectorSegmentation = new AliMpSectorSegmentation(plane->GetFrontSector());
  fBackSectorSegmentation = new AliMpSectorSegmentation(plane->GetBackSector());

  for (Int_t i=0; i<fkPlane->GetNofSectorPositions(); i++) {
    fTransformers.push_back(
      new AliMpTransformer(fkPlane->GetSectorPosition(i)->GetOffset(),
                           fkPlane->GetSectorPosition(i)->GetScale()));
  }
}

///_____________________________________________________________________________
AliMpPlaneSegmentation::AliMpPlaneSegmentation()
  : AliMpVSegmentation(),
    fkPlane(0),
    fFrontSectorSegmentation(0),
    fBackSectorSegmentation(0)
{
//
}

//_____________________________________________________________________________
AliMpPlaneSegmentation::~AliMpPlaneSegmentation() {
//
  delete fFrontSectorSegmentation;
  delete fBackSectorSegmentation;

  for (Int_t i=0; i<GetNofTransformers(); i++)
    delete GetTransformer(i);
}

//
// private methods
//

//_____________________________________________________________________________
const AliMpTransformer*
AliMpPlaneSegmentation::GetTransformer(const AliMpIntPair& scale) const
{
// Returns the sector position specified by scale.
// ---

  for (UInt_t i=0; i<fTransformers.size(); i++)
    if (fTransformers[i]->GetScale() == scale) return fTransformers[i];

  Fatal("GetTransformer", "Wrong scale");
  return 0;
}

//_____________________________________________________________________________
AliMpIntPair AliMpPlaneSegmentation::GetScale(const AliMpIntPair& pair) const
{
// Returns pair of the signs of the values of the given pair.
// ---

  AliMpIntPair scale(1, 1);

  if (pair.GetFirst() < 0)  scale.SetFirst(-1);
  if (pair.GetSecond() < 0) scale.SetSecond(-1);

  return scale;
}

//_____________________________________________________________________________
AliMpIntPair AliMpPlaneSegmentation::GetScale(const TVector2& vector) const
{
// Returns pair of the signs of the values of the given vector.
// ---

  AliMpIntPair scale(1, 1);

  if (vector.X() < 0) scale.SetFirst(-1);
  if (vector.Y() < 0) scale.SetSecond(-1);

  return scale;
}

//_____________________________________________________________________________
AliMpIntPair
AliMpPlaneSegmentation::GetLocationScale(const AliMpIntPair& location) const
{
// Returns the scale transformation of the specified location.
// ---

  // Find the sector
  Bool_t inFront;
  if (fFrontSectorSegmentation
        ->HasMotifPosition(TMath::Abs(location.GetFirst())))
    inFront = true;
  else if (fBackSectorSegmentation
             ->HasMotifPosition(TMath::Abs(location.GetFirst())))
    inFront = false;
  else {
    Fatal("GetLocationScale", "Motif position not found.");
    return AliMpIntPair();
  }

  if      (inFront  && location.GetFirst() > 0) return  AliMpIntPair(1, 1);
  else if (inFront  && location.GetFirst() < 0) return  AliMpIntPair(-1, -1);
  else if (!inFront && location.GetFirst() > 0) return  AliMpIntPair(-1, 1);
  else if (!inFront && location.GetFirst() < 0) return  AliMpIntPair( 1,-1);

  // cannot get there
  Fatal("GetLocationScale", "Condition failed.");
  return AliMpIntPair();
}

//_____________________________________________________________________________
AliMpSectorSegmentation*
AliMpPlaneSegmentation::GetSectorSegmentation(const AliMpIntPair& scale) const
{
// Returns front sector or back sector segmentation
// according to quadrant specified by scale.
// ---

  if (scale.GetFirst()*scale.GetSecond() > 0) {
    // quadrant I or III
    return fFrontSectorSegmentation;
  }
  else  {
    // quadrant II or IV
    return fBackSectorSegmentation;
  }
}

//_____________________________________________________________________________
AliMpSectorSegmentation*
AliMpPlaneSegmentation::GetSectorSegmentation(Int_t motifPositionId) const
{
// Returns front sector or back sector segmentation
// according to specified motifPositionId
// ---

  if (fFrontSectorSegmentation->HasMotifPosition(motifPositionId))
    return fFrontSectorSegmentation;
  else if (fBackSectorSegmentation->HasMotifPosition(motifPositionId))
    return fBackSectorSegmentation;
  else {
    Fatal("GetSectorSegmentation", "Motif position not found.");
    return 0;
  }
}

//
// public methods
//

//_____________________________________________________________________________
AliMpVPadIterator*
AliMpPlaneSegmentation::CreateIterator(const AliMpArea& area) const
{
// Creates the are iterator.
// (The inherited method cannot be used)
// ---

  return new AliMpPlaneAreaPadIterator(this, area);
}

//______________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByLocation(const AliMpIntPair& location,
                                       Bool_t warning) const
{
// Find the pad which corresponds to the given location
// ---

  // Get segmentation
  AliMpSectorSegmentation* segmentation
    = GetSectorSegmentation(TMath::Abs(location.GetFirst()));

  // Get pad in the segmentation
  AliMpPad pad
     = segmentation
       ->PadByLocation(
           AliMpIntPair(TMath::Abs(location.GetFirst()),location.GetSecond()),
	                warning);

  // Get transformation
  AliMpIntPair scale  = GetLocationScale(location);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  // Transform pad characteristics
  return kTransformer->Transform(pad);
}

//______________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByIndices (const AliMpIntPair& indices,
                                               Bool_t warning ) const
{
// Find the pad which corresponds to the given indices
//

  AliMpIntPair scale = GetScale(indices);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpIntPair scaledIndices = kTransformer->Scale(indices);
  AliMpPad pad
    = GetSectorSegmentation(scale)->PadByIndices(scaledIndices, warning);

  return kTransformer->Transform(pad);
}

//_____________________________________________________________________________
AliMpPad AliMpPlaneSegmentation::PadByPosition(const TVector2& position,
                                               Bool_t warning) const
{
// Find the pad which corresponds to the given position
// ---

  AliMpIntPair scale = GetScale(position);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  TVector2 scaledPosition = kTransformer->ITransform(position);
  AliMpPad pad
    = GetSectorSegmentation(scale)->PadByPosition(scaledPosition, warning);

  return kTransformer->Transform(pad);
}

//_____________________________________________________________________________
Bool_t AliMpPlaneSegmentation::HasPad(const AliMpIntPair& indices) const
{
// Does the pad located by <indices> exists ?
// ---

  AliMpIntPair scale = GetScale(indices);
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpIntPair scaledIndices = kTransformer->Scale(indices);

  return GetSectorSegmentation(scale)->HasPad(scaledIndices);
}

//_____________________________________________________________________________
Int_t AliMpPlaneSegmentation::Zone(const AliMpPad& pad, Bool_t warning) const
{
// Returns the zone index of the zone containing the specified pad.
// This zone index is different from the zone ID,
// as it is unique for each pad dimensions.
// It is composed in this way:
//   sectorID*100 + zoneID*10 + specific index
// Where sectorID = 0,1 for front/back sector.
// Specific index is present only for zones containing special motifs.
// ---

  if (!pad.IsValid()) {
    if (warning) Warning("Zone(AliMpPad)", "Invalid pad");
    return 0;
  }

  AliMpIntPair scale = GetScale(pad.GetIndices());
  const AliMpTransformer* kTransformer = GetTransformer(scale);

  AliMpPad scaledPad = kTransformer->ITransform(pad);

  AliMpSectorSegmentation* segmentation = GetSectorSegmentation(scale);
  Int_t zoneID = segmentation->Zone(scaledPad, warning);

  // Distinguish zones from front/back sector
  // For back sector - add 10
  if (segmentation == fBackSectorSegmentation) zoneID += 100;

  return zoneID;
}

//_____________________________________________________________________________
TVector2
AliMpPlaneSegmentation::PadDimensions(Int_t zone, Bool_t warning) const
{
// Returns the pad dimensions for the zone with the specified zone index.
// ---

  if (zone < 100)
    return fFrontSectorSegmentation->PadDimensions(zone, warning);
  else
    return fBackSectorSegmentation->PadDimensions(zone - 100, warning);
}

//_____________________________________________________________________________
Bool_t AliMpPlaneSegmentation::CircleTest(const AliMpIntPair& indices) const
{
// Verifies that all methods for retrieving pads are consistents between them.
// Returns true if the pad with specified indices was found and verified,
// false otherwise.
// ---

  if (!HasPad(indices)) return false;

  // Verify the indice->location->position->indice way
  AliMpIntPair location = PadByIndices(indices).GetLocation();
  TVector2 position = PadByLocation(location).Position();
  AliMpIntPair retIndices = PadByPosition(position).GetIndices();

  if (retIndices != indices) {
    cout << "Pad " << indices << " lead to inconsistency" << endl;
    cout << "in indice->location->position->indice way..." << endl;
    cout << "starting from " << indices << "-->" << location << "-->"
         << '(' << position.X() << ',' << position.Y() << ')'
         << " and retIndices: " << retIndices << endl;
  }

  // Verify the indice->position->location->indice way
  position = PadByIndices(indices).Position();
  location = PadByPosition(position).GetLocation();
  retIndices = PadByLocation(location).GetIndices();

  if (retIndices != indices) {
    cout << "Pad " << indices << " lead to inconsistency" << endl;
    cout << "in indice->position->location->indice way..." <<endl;
    cout << "starting from " << indices
         << " and retIndices: " << retIndices << endl;
  }

  return true;

}

//_____________________________________________________________________________
Int_t AliMpPlaneSegmentation::GetNofTransformers() const
{
// Returns number of transformers.
// ---

  return fTransformers.size();
}

//_____________________________________________________________________________
AliMpTransformer* AliMpPlaneSegmentation::GetTransformer(Int_t i) const
{
// Returns i-th transformer.
// ---

  return  fTransformers[i];
}

<|endoftext|>


<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <boost/python/def.hpp>
#include <boost/python/module.hpp>

#include <vil/vil_image_view.h>

/**
 * \file test_image.cxx
 *
 * \brief Python bindings for image testing pipelines.
 */

using namespace boost::python;

template <typename T>
static vil_image_view<T> make_image(size_t width, size_t height, size_t planes);
template <typename T>
static size_t take_image(vil_image_view<T> const& img);

BOOST_PYTHON_MODULE(test_image)
{
#define DEFINE_FUNCTIONS(type)                       \
  do                                                 \
  {                                                  \
    def("make_image_" #type, &make_image<type>       \
      , (arg("width"), arg("height"), arg("planes")) \
      , "Create a " #type " image.");                \
    def("take_image_" #type, &take_image<type>       \
      , (arg("image")) \
      , "Take a " #type " image and return its size.");                \
  } while (false)

  DEFINE_FUNCTIONS(bool);
  DEFINE_FUNCTIONS(uint8_t);
  DEFINE_FUNCTIONS(float);
  DEFINE_FUNCTIONS(double);

#undef DEFINE_FUNCTIONS
}

template <typename T>
vil_image_view<T>
make_image(size_t width, size_t height, size_t planes)
{
  return vil_image_view<T>(width, height, planes);
}

template <typename T>
size_t
take_image(vil_image_view<T> const& img)
{
  size_t const ni = img.ni();
  size_t const nj = img.nj();
  size_t const np = img.nplanes();

  return (ni * nj * np);
}
<commit_msg>Add a wrapper for saving images<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include <boost/python/def.hpp>
#include <boost/python/module.hpp>

#include <vil/vil_image_view.h>
#include <vil/vil_save.h>

/**
 * \file test_image.cxx
 *
 * \brief Python bindings for image testing pipelines.
 */

using namespace boost::python;

template <typename T>
static vil_image_view<T> make_image(size_t width, size_t height, size_t planes);
template <typename T>
static size_t take_image(vil_image_view<T> const& img);
template <typename T>
static bool save_image(vil_image_view<T> const& img, std::string const& path);

BOOST_PYTHON_MODULE(test_image)
{
#define DEFINE_FUNCTIONS(type)                             \
  do                                                       \
  {                                                        \
    def("make_image_" #type, &make_image<type>             \
      , (arg("width"), arg("height"), arg("planes"))       \
      , "Create a " #type " image.");                      \
    def("take_image_" #type, &take_image<type>             \
      , (arg("image"))                                     \
      , "Take a " #type " image and return its size.");    \
    def("save_image_" #type, &save_image<type>             \
      , (arg("image"), arg("path"))                        \
      , "Take a " #type " image and write it to a file."); \
  } while (false)

  DEFINE_FUNCTIONS(bool);
  DEFINE_FUNCTIONS(uint8_t);
  DEFINE_FUNCTIONS(float);
  DEFINE_FUNCTIONS(double);

#undef DEFINE_FUNCTIONS
}

template <typename T>
vil_image_view<T>
make_image(size_t width, size_t height, size_t planes)
{
  return vil_image_view<T>(width, height, planes);
}

template <typename T>
size_t
take_image(vil_image_view<T> const& img)
{
  size_t const ni = img.ni();
  size_t const nj = img.nj();
  size_t const np = img.nplanes();

  return (ni * nj * np);
}

template <typename T>
bool
save_image(vil_image_view<T> const& img, std::string const& path)
{
  return vil_save(img, path.c_str());
}
<|endoftext|>


<commit_before>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"

#include "guiconstants.h"
#include "walletmodel.h"

#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>

extern bool fWalletUnlockStakingOnly;

AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AskPassphraseDialog),
    mode(mode),
    model(0),
    fCapsLock(false)
{
    ui->setupUi(this);
    ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);

    // Setup Caps Lock detection.
    ui->passEdit1->installEventFilter(this);
    ui->passEdit2->installEventFilter(this);
    ui->passEdit3->installEventFilter(this);

    ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);

    switch(mode)
    {
        case Encrypt: // Ask passphrase x2
            ui->passLabel1->hide();
            ui->passEdit1->hide();
            ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.
Please use a passphrase of 10 or more random characters, or eight or more words."));
            setWindowTitle(tr("Encrypt wallet"));
            break;
        case UnlockStaking:
            ui->stakingCheckBox->setChecked(true);
            ui->stakingCheckBox->show();
            // fallthru
        case Unlock: // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Unlock wallet"));
            break;
        case Decrypt:   // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Decrypt wallet"));
            break;
        case ChangePass: // Ask old passphrase + new passphrase x2
            setWindowTitle(tr("Change passphrase"));
            ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
            break;
    }

    textChanged();
    connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
    connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
    connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}

AskPassphraseDialog::~AskPassphraseDialog()
{
    secureClearPassFields();
    delete ui;
}

void AskPassphraseDialog::setModel(WalletModel *model)
{
    this->model = model;
}

void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if(!model)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    secureClearPassFields();

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR COINS!") + "

" + tr("Are you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                if(model->setWalletEncrypted(true, newpass1))
                {
                    QMessageBox::warning(this, tr("Wallet encrypted"),
                                         "<qt>" +
                                         tr("Munne will close now to finish the encryption process. "
                                         "Remember that encrypting your wallet cannot fully protect "
                                         "your coins from being stolen by malware infecting your computer.") +
                                         "

" +
                                         tr("IMPORTANT: Any previous backups you have made of your wallet file "
                                         "should be replaced with the newly generated, encrypted wallet file. "
                                         "For security reasons, previous backups of the unencrypted wallet file "
                                         "will become useless as soon as you start using the new, encrypted wallet.") +
                                         "</qt>");
                    QApplication::quit();
                }
                else
                {
                    QMessageBox::critical(this, tr("Wallet encryption failed"),
                                         tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case UnlockStaking:
    case Unlock:
        if(!model->setWalletLocked(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet unlock failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
            QDialog::accept(); // Success
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}

void AskPassphraseDialog::textChanged()
{
    // Validate input, set Ok button to enabled when acceptable
    bool acceptable = false;
    switch(mode)
    {
    case Encrypt: // New passphrase x2
        acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    case UnlockStaking:
    case Unlock: // Old passphrase x1
    case Decrypt:
        acceptable = !ui->passEdit1->text().isEmpty();
        break;
    case ChangePass: // Old passphrase x1, new passphrase x2
        acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}

bool AskPassphraseDialog::event(QEvent *event)
{
    // Detect Caps Lock key press.
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_CapsLock) {
            fCapsLock = !fCapsLock;
        }
        if (fCapsLock) {
            ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
        } else {
            ui->capsLabel->clear();
        }
    }
    return QWidget::event(event);
}

bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
    /* Detect Caps Lock.
     * There is no good OS-independent way to check a key state in Qt, but we
     * can detect Caps Lock by checking for the following condition:
     * Shift key is down and the result is a lower case character, or
     * Shift key is not down and the result is an upper case character.
     */
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        QString str = ke->text();
        if (str.length() != 0) {
            const QChar *psz = str.unicode();
            bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
            if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
                fCapsLock = true;
                ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
            } else if (psz->isLetter()) {
                fCapsLock = false;
                ui->capsLabel->clear();
            }
        }
    }
    return QDialog::eventFilter(object, event);
}

void AskPassphraseDialog::secureClearPassFields()
{
    // Attempt to overwrite text so that they do not linger around in memory
    ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
    ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
    ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));

    ui->passEdit1->clear();
    ui->passEdit2->clear();
    ui->passEdit3->clear();
}
<commit_msg>Consistent lettering<commit_after>#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"

#include "guiconstants.h"
#include "walletmodel.h"

#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>

extern bool fWalletUnlockStakingOnly;

AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AskPassphraseDialog),
    mode(mode),
    model(0),
    fCapsLock(false)
{
    ui->setupUi(this);
    ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
    ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);

    // Setup Caps Lock detection.
    ui->passEdit1->installEventFilter(this);
    ui->passEdit2->installEventFilter(this);
    ui->passEdit3->installEventFilter(this);

    ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);

    switch(mode)
    {
        case Encrypt: // Ask passphrase x2
            ui->passLabel1->hide();
            ui->passEdit1->hide();
            ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.
Please use a passphrase of ten or more random characters, or eight or more words."));
            setWindowTitle(tr("Encrypt wallet"));
            break;
        case UnlockStaking:
            ui->stakingCheckBox->setChecked(true);
            ui->stakingCheckBox->show();
            // fallthru
        case Unlock: // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Unlock wallet"));
            break;
        case Decrypt:   // Ask passphrase
            ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
            ui->passLabel2->hide();
            ui->passEdit2->hide();
            ui->passLabel3->hide();
            ui->passEdit3->hide();
            setWindowTitle(tr("Decrypt wallet"));
            break;
        case ChangePass: // Ask old passphrase + new passphrase x2
            setWindowTitle(tr("Change passphrase"));
            ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
            break;
    }

    textChanged();
    connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
    connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
    connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}

AskPassphraseDialog::~AskPassphraseDialog()
{
    secureClearPassFields();
    delete ui;
}

void AskPassphraseDialog::setModel(WalletModel *model)
{
    this->model = model;
}

void AskPassphraseDialog::accept()
{
    SecureString oldpass, newpass1, newpass2;
    if(!model)
        return;
    oldpass.reserve(MAX_PASSPHRASE_SIZE);
    newpass1.reserve(MAX_PASSPHRASE_SIZE);
    newpass2.reserve(MAX_PASSPHRASE_SIZE);
    // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
    // Alternately, find a way to make this input mlock()'d to begin with.
    oldpass.assign(ui->passEdit1->text().toStdString().c_str());
    newpass1.assign(ui->passEdit2->text().toStdString().c_str());
    newpass2.assign(ui->passEdit3->text().toStdString().c_str());

    secureClearPassFields();

    switch(mode)
    {
    case Encrypt: {
        if(newpass1.empty() || newpass2.empty())
        {
            // Cannot encrypt with empty passphrase
            break;
        }
        QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
                 tr("Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR COINS!") + "

" + tr("Are you sure you wish to encrypt your wallet?"),
                 QMessageBox::Yes|QMessageBox::Cancel,
                 QMessageBox::Cancel);
        if(retval == QMessageBox::Yes)
        {
            if(newpass1 == newpass2)
            {
                if(model->setWalletEncrypted(true, newpass1))
                {
                    QMessageBox::warning(this, tr("Wallet encrypted"),
                                         "<qt>" +
                                         tr("Munne will close now to finish the encryption process. "
                                         "Remember that encrypting your wallet cannot fully protect "
                                         "your coins from being stolen by malware infecting your computer.") +
                                         "

" +
                                         tr("IMPORTANT: Any previous backups you have made of your wallet file "
                                         "should be replaced with the newly generated, encrypted wallet file. "
                                         "For security reasons, previous backups of the unencrypted wallet file "
                                         "will become useless as soon as you start using the new, encrypted wallet.") +
                                         "</qt>");
                    QApplication::quit();
                }
                else
                {
                    QMessageBox::critical(this, tr("Wallet encryption failed"),
                                         tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
                }
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The supplied passphrases do not match."));
            }
        }
        else
        {
            QDialog::reject(); // Cancelled
        }
        } break;
    case UnlockStaking:
    case Unlock:
        if(!model->setWalletLocked(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet unlock failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
            QDialog::accept(); // Success
        }
        break;
    case Decrypt:
        if(!model->setWalletEncrypted(false, oldpass))
        {
            QMessageBox::critical(this, tr("Wallet decryption failed"),
                                  tr("The passphrase entered for the wallet decryption was incorrect."));
        }
        else
        {
            QDialog::accept(); // Success
        }
        break;
    case ChangePass:
        if(newpass1 == newpass2)
        {
            if(model->changePassphrase(oldpass, newpass1))
            {
                QMessageBox::information(this, tr("Wallet encrypted"),
                                     tr("Wallet passphrase was successfully changed."));
                QDialog::accept(); // Success
            }
            else
            {
                QMessageBox::critical(this, tr("Wallet encryption failed"),
                                     tr("The passphrase entered for the wallet decryption was incorrect."));
            }
        }
        else
        {
            QMessageBox::critical(this, tr("Wallet encryption failed"),
                                 tr("The supplied passphrases do not match."));
        }
        break;
    }
}

void AskPassphraseDialog::textChanged()
{
    // Validate input, set Ok button to enabled when acceptable
    bool acceptable = false;
    switch(mode)
    {
    case Encrypt: // New passphrase x2
        acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    case UnlockStaking:
    case Unlock: // Old passphrase x1
    case Decrypt:
        acceptable = !ui->passEdit1->text().isEmpty();
        break;
    case ChangePass: // Old passphrase x1, new passphrase x2
        acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
        break;
    }
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}

bool AskPassphraseDialog::event(QEvent *event)
{
    // Detect Caps Lock key press.
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        if (ke->key() == Qt::Key_CapsLock) {
            fCapsLock = !fCapsLock;
        }
        if (fCapsLock) {
            ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
        } else {
            ui->capsLabel->clear();
        }
    }
    return QWidget::event(event);
}

bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
    /* Detect Caps Lock.
     * There is no good OS-independent way to check a key state in Qt, but we
     * can detect Caps Lock by checking for the following condition:
     * Shift key is down and the result is a lower case character, or
     * Shift key is not down and the result is an upper case character.
     */
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        QString str = ke->text();
        if (str.length() != 0) {
            const QChar *psz = str.unicode();
            bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
            if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
                fCapsLock = true;
                ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
            } else if (psz->isLetter()) {
                fCapsLock = false;
                ui->capsLabel->clear();
            }
        }
    }
    return QDialog::eventFilter(object, event);
}

void AskPassphraseDialog::secureClearPassFields()
{
    // Attempt to overwrite text so that they do not linger around in memory
    ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
    ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
    ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));

    ui->passEdit1->clear();
    ui->passEdit2->clear();
    ui->passEdit3->clear();
}
<|endoftext|>