<commit_before>#include <tests/Base.hh>

#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/algorithms/Standard.hh>
#include <aleph/persistentHomology/algorithms/Twist.hh>

#include <aleph/topology/BoundaryMatrix.hh>

#include <aleph/topology/representations/Set.hh>
#include <aleph/topology/representations/Vector.hh>

#include <vector>

template <class T> void testNonSquare()
{
  ALEPH_TEST_BEGIN( "Boundary matrix reduction for non-square matrices" );

  using namespace aleph;
  using namespace topology;
  using namespace representations;

  using Representation = Vector<T>;
  using Matrix         = BoundaryMatrix<Representation>;
  using Index          = typename Matrix::Index;

  // Rectangular matrix reduction --------------------------------------

  Matrix M;
  M.setNumColumns( Index(4) );

  std::vector<T> columnA = { 1+4, 3+4, 4+4      };
  std::vector<T> columnB = { 2+4, 7+4, 8+4      };
  std::vector<T> columnC = { 5+4, 4+4, 7+4      };
  std::vector<T> columnE = { 1+4, 2+4, 5+4, 6+4 };

  M.setColumn( 0, columnA.begin(), columnA.end() );
  M.setColumn( 1, columnB.begin(), columnB.end() );
  M.setColumn( 2, columnC.begin(), columnC.end() );
  M.setColumn( 3, columnE.begin(), columnE.end() );

  using StandardAlgorithm = aleph::persistentHomology::algorithms::StandardRectangular;
  StandardAlgorithm algorithm;

  algorithm( M );

  Index i;
  bool valid;

  std::tie( i, valid ) = M.getMaximumIndex( 3 );

  ALEPH_ASSERT_EQUAL( valid, true  );
  ALEPH_ASSERT_EQUAL( i    ,   6+4 );

  // Quadratic matrix reduction w/ constraints -------------------------

  Matrix N;
  N.setNumColumns( Index(12) );

  columnA = { 1+3, 3+3, 4+3      };
  columnB = { 2+3, 7+3, 8+3      };
  columnC = { 5+3, 4+3, 7+3      };
  columnE = { 1+3, 2+3, 5+3, 6+3 };

  N.setColumn( 0, columnA.begin(), columnA.end() );
  N.setColumn( 1, columnB.begin(), columnB.end() );
  N.setColumn( 2, columnC.begin(), columnC.end() );
  N.setColumn( 3, columnE.begin(), columnE.end() );

  auto N1 = N;

  algorithm( N1 );

  std::tie( i, valid ) = N1.getMaximumIndex( 3 );

  ALEPH_ASSERT_EQUAL( valid, true  );
  ALEPH_ASSERT_EQUAL( i    ,   6+3 );

  {
    auto pairing = calculatePersistencePairing( N, false );
    std::cerr << "Pairing (quadratic, original):\n"
              << pairing << "\n";
  }

  std::cerr << std::string( 72, '-' ) << "\n"
            << "Original space:\n"
            << std::string( 72, '-' ) << "\n\n";

  for( Index j = 0; j < N1.getNumColumns(); j++ )
  {
    std::tie( i, valid ) = N1.getMaximumIndex( j );

    if( valid )
      std::cerr << j << ": " << i << "\n";
    else
      std::cerr << j << ": -" << "\n";
  }

  auto N2 = N.dualize();

  algorithm( N2 );

  std::cerr << N2 << "\n";

  std::cerr << std::string( 72, '-' ) << "\n"
            << "Dual space:\n"
            << std::string( 72, '-' ) << "\n\n";

  for( Index j = 0; j < N2.getNumColumns(); j++ )
  {
    std::tie( i, valid ) = N2.getMaximumIndex( j );

    if( valid )
      std::cerr << 12 - 1 - i << ": " << 12 - 1 - j << "\n";
    else
      std::cerr << 12 - 1 - j << ": -" << "\n";
  }

  auto N3      = N.dualize();
  auto pairing = calculatePersistencePairing( N3, false );

  // Quadratic matrix with re-ordering ---------------------------------

  Matrix O;
  O.setNumColumns( Index(12) );

  columnA = { 1-1, 5-1, 6-1 };
  columnB = { 2-1, 7-1, 8-1 };
  columnC = { 3-1, 6-1, 7-1 };
  columnE = { 4-1, 5-1, 8-1 };

  O.setColumn( 8, columnA.begin(), columnA.end() );
  O.setColumn( 9, columnB.begin(), columnB.end() );
  O.setColumn(10, columnC.begin(), columnC.end() );
  O.setColumn(11, columnE.begin(), columnE.end() );

  pairing = calculatePersistencePairing( O, false );

  std::cerr << "Pairing (quadratic, with re-ordering):\n";

  for( auto&& pair : pairing )
    if( pair.first <= 4 )
      std::cerr << pair.first << ": " << pair.second << "\n";

  // Quadratic matrix with partition -----------------------------------

  Matrix P;
  P.setNumColumns( Index(12) );

  columnA = { 1-1, 5-1+4, 6-1+4 };
  columnB = { 2-1, 7-1+4, 8-1+4 };
  columnC = { 3-1, 6-1+4, 7-1+4 };
  columnE = { 4-1, 5-1+4, 8-1+4 };

  P.setColumn( 4, columnA.begin(), columnA.end() );
  P.setColumn( 5, columnB.begin(), columnB.end() );
  P.setColumn( 6, columnC.begin(), columnC.end() );
  P.setColumn( 7, columnE.begin(), columnE.end() );

  pairing = calculatePersistencePairing( P, false );

  std::cerr << "Pairing (quadratic, with partion-based re-ordering [singular]):\n";

  for( auto&& pair : pairing )
    if( pair.first <= 7 )
      std::cerr << pair.first << ": " << pair.second << "\n";

  pairing = calculatePersistencePairing( P.dualize(), false );

  std::cerr << "Pairing (quadratic, with partion-based re-ordering):\n";

  for( auto&& pair : pairing )
    if( pair.first <= 7 )
      std::cerr << pair.first << ": " << pair.second << "\n";

  pairing = calculatePersistencePairing( P.dualize(), false, 8 );

  std::cerr << "Pairing (quadratic, with partion-based re-ordering and cut-off):\n"
            << pairing << "\n";

  ALEPH_TEST_END();
}

template <class M> void reduceBoundaryMatrix( const M& m )
{
  ALEPH_TEST_BEGIN( "Boundary matrix reduction" );

  ALEPH_ASSERT_THROW( m.getNumColumns() > 0 );

  using StandardAlgorithm = aleph::persistentHomology::algorithms::Standard;
  using TwistAlgorithm    = aleph::persistentHomology::algorithms::Twist;

  using Index   = typename M::Index;
  using Pairing = aleph::PersistencePairing<Index>;

  std::vector<Pairing> pairings;
  pairings.reserve( 4 );

  pairings.push_back( aleph::calculatePersistencePairing<StandardAlgorithm>( m ) );
  pairings.push_back( aleph::calculatePersistencePairing<StandardAlgorithm>( m.dualize() ) );

  pairings.push_back( aleph::calculatePersistencePairing<TwistAlgorithm>( m ) );
  pairings.push_back( aleph::calculatePersistencePairing<TwistAlgorithm>( m.dualize() ) );

  ALEPH_ASSERT_THROW( m != m.dualize() );
  ALEPH_ASSERT_THROW( m == m.dualize().dualize() );

  for( auto&& pairing : pairings )
  {
    ALEPH_ASSERT_THROW( pairing.empty() == false );
    ALEPH_ASSERT_THROW( pairing.size()  == 4 );
  }

  for( auto&& pairing1 : pairings )
    for( auto&& pairing2 : pairings )
      ALEPH_ASSERT_THROW( pairing1 == pairing2 );

  ALEPH_ASSERT_THROW( pairings.front().contains( Index(0) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(1), Index(3) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(2), Index(4) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(5), Index(6) ) );

  ALEPH_TEST_END();
}

template <class T> void setupBoundaryMatrix()
{
  using namespace aleph;
  using namespace topology;
  using namespace representations;

  ALEPH_TEST_BEGIN( "Boundary matrix setup & loading" );

  using Set    = Set<T>;
  using Vector = Vector<T>;

  auto m1 = BoundaryMatrix<Set>::load( CMAKE_SOURCE_DIR + std::string( "/tests/input/Triangle.txt" ) );
  auto m2 = BoundaryMatrix<Vector>::load( CMAKE_SOURCE_DIR + std::string( "/tests/input/Triangle.txt" ) );

  reduceBoundaryMatrix( m1 );
  reduceBoundaryMatrix( m2 );

  ALEPH_TEST_END();
}

int main()
{
  setupBoundaryMatrix<unsigned int> ();
  setupBoundaryMatrix<unsigned long>();
  setupBoundaryMatrix<int>();
  setupBoundaryMatrix<long>();

  testNonSquare<int>          ();
  testNonSquare<long>         ();
  testNonSquare<unsigned int> ();
  testNonSquare<unsigned long>();
}
<commit_msg>Extended test case for dualized boundary matrices<commit_after>#include <tests/Base.hh>

#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/algorithms/Standard.hh>
#include <aleph/persistentHomology/algorithms/Twist.hh>

#include <aleph/topology/BoundaryMatrix.hh>

#include <aleph/topology/representations/Set.hh>
#include <aleph/topology/representations/Vector.hh>

#include <algorithm>
#include <vector>

template <class T> void testNonSquare()
{
  ALEPH_TEST_BEGIN( "Boundary matrix reduction for non-square matrices" );

  using namespace aleph;
  using namespace topology;
  using namespace representations;

  using Representation = Vector<T>;
  using Matrix         = BoundaryMatrix<Representation>;
  using Index          = typename Matrix::Index;

  // Rectangular matrix reduction --------------------------------------

  Matrix M;
  M.setNumColumns( Index(4) );

  std::vector<T> columnA = { 1+4, 3+4, 4+4      };
  std::vector<T> columnB = { 2+4, 7+4, 8+4      };
  std::vector<T> columnC = { 5+4, 4+4, 7+4      };
  std::vector<T> columnE = { 1+4, 2+4, 5+4, 6+4 };

  M.setColumn( 0, columnA.begin(), columnA.end() );
  M.setColumn( 1, columnB.begin(), columnB.end() );
  M.setColumn( 2, columnC.begin(), columnC.end() );
  M.setColumn( 3, columnE.begin(), columnE.end() );

  using StandardAlgorithm = aleph::persistentHomology::algorithms::StandardRectangular;
  StandardAlgorithm algorithm;

  algorithm( M );

  Index i;
  bool valid;

  std::tie( i, valid ) = M.getMaximumIndex( 3 );

  ALEPH_ASSERT_EQUAL( valid, true  );
  ALEPH_ASSERT_EQUAL( i    ,   6+4 );

  // Quadratic matrix reduction w/ constraints -------------------------

  Matrix N;
  N.setNumColumns( Index(12) );

  columnA = { 1+3, 3+3, 4+3      };
  columnB = { 2+3, 7+3, 8+3      };
  columnC = { 5+3, 4+3, 7+3      };
  columnE = { 1+3, 2+3, 5+3, 6+3 };

  N.setColumn( 0, columnA.begin(), columnA.end() );
  N.setColumn( 1, columnB.begin(), columnB.end() );
  N.setColumn( 2, columnC.begin(), columnC.end() );
  N.setColumn( 3, columnE.begin(), columnE.end() );

  auto N1 = N;

  algorithm( N1 );

  std::tie( i, valid ) = N1.getMaximumIndex( 3 );

  ALEPH_ASSERT_EQUAL( valid, true  );
  ALEPH_ASSERT_EQUAL( i    ,   6+3 );

  {
    auto pairing = calculatePersistencePairing( N, false );
    std::cerr << "Pairing (quadratic, original):\n"
              << pairing << "\n";
  }

  std::cerr << std::string( 72, '-' ) << "\n"
            << "Original space:\n"
            << std::string( 72, '-' ) << "\n\n";

  for( Index j = 0; j < N1.getNumColumns(); j++ )
  {
    std::tie( i, valid ) = N1.getMaximumIndex( j );

    if( valid )
      std::cerr << j << ": " << i << "\n";
    else
      std::cerr << j << ": -" << "\n";
  }

  auto N2 = N.dualize();

  algorithm( N2 );

  std::cerr << N2 << "\n";

  std::cerr << std::string( 72, '-' ) << "\n"
            << "Dual space:\n"
            << std::string( 72, '-' ) << "\n\n";

  for( Index j = 0; j < N2.getNumColumns(); j++ )
  {
    std::tie( i, valid ) = N2.getMaximumIndex( j );

    if( valid )
      std::cerr << 12 - 1 - i << ": " << 12 - 1 - j << "\n";
    else
      std::cerr << 12 - 1 - j << ": -" << "\n";
  }

  auto N3      = N.dualize();
  auto pairing = calculatePersistencePairing( N3, false );

  // Quadratic matrix with re-ordering ---------------------------------

  Matrix O;
  O.setNumColumns( Index(12) );

  columnA = { 1-1, 5-1, 6-1 };
  columnB = { 2-1, 7-1, 8-1 };
  columnC = { 3-1, 6-1, 7-1 };
  columnE = { 4-1, 5-1, 8-1 };

  O.setColumn( 8, columnA.begin(), columnA.end() );
  O.setColumn( 9, columnB.begin(), columnB.end() );
  O.setColumn(10, columnC.begin(), columnC.end() );
  O.setColumn(11, columnE.begin(), columnE.end() );

  pairing = calculatePersistencePairing( O, false );

  std::cerr << "Pairing (quadratic, with re-ordering):\n";

  for( auto&& pair : pairing )
    if( pair.first <= 4 )
      std::cerr << pair.first << ": " << pair.second << "\n";

  // Quadratic matrix with partition -----------------------------------

  Matrix P;
  P.setNumColumns( Index(12) );

  columnA = { 1-1, 5-1+4, 6-1+4 };
  columnB = { 2-1, 7-1+4, 8-1+4 };
  columnC = { 3-1, 6-1+4, 7-1+4 };
  columnE = { 4-1, 5-1+4, 8-1+4 };

  P.setDimension( 0, 1 );
  P.setDimension( 1, 1 );
  P.setDimension( 2, 1 );
  P.setDimension( 3, 1 );

  P.setColumn( 4, columnA.begin(), columnA.end() );
  P.setColumn( 5, columnB.begin(), columnB.end() );
  P.setColumn( 6, columnC.begin(), columnC.end() );
  P.setColumn( 7, columnE.begin(), columnE.end() );

  P.setDimension( 8, 1 );
  P.setDimension( 9, 1 );
  P.setDimension(10, 1 );
  P.setDimension(11, 1 );

  using Pairing = decltype(pairing);
  using Pair    = typename Pairing::ValueType;

  auto RemoveNeutral = [] ( const Pair& pair )
  {
    return pair.first >= 8;
  };

  {
    auto pairing1 = calculatePersistencePairing<aleph::persistentHomology::algorithms::Standard>( P, false );
    pairing1.erase( std::remove_if( pairing1.begin(), pairing1.end(), RemoveNeutral ), pairing1.end() );

    auto pairing2 = calculatePersistencePairing( P, true );
    pairing2.erase( std::remove_if( pairing2.begin(), pairing2.end(), RemoveNeutral ), pairing2.end() );

    auto pairing3 = calculatePersistencePairing( P, true, 8 );

    ALEPH_ASSERT_THROW( pairing1 == pairing2 );
    ALEPH_ASSERT_THROW( pairing2 == pairing3 );
  }

  ALEPH_TEST_END();
}

template <class M> void reduceBoundaryMatrix( const M& m )
{
  ALEPH_TEST_BEGIN( "Boundary matrix reduction" );

  ALEPH_ASSERT_THROW( m.getNumColumns() > 0 );

  using StandardAlgorithm = aleph::persistentHomology::algorithms::Standard;
  using TwistAlgorithm    = aleph::persistentHomology::algorithms::Twist;

  using Index   = typename M::Index;
  using Pairing = aleph::PersistencePairing<Index>;

  std::vector<Pairing> pairings;
  pairings.reserve( 4 );

  pairings.push_back( aleph::calculatePersistencePairing<StandardAlgorithm>( m ) );
  pairings.push_back( aleph::calculatePersistencePairing<StandardAlgorithm>( m.dualize() ) );

  pairings.push_back( aleph::calculatePersistencePairing<TwistAlgorithm>( m ) );
  pairings.push_back( aleph::calculatePersistencePairing<TwistAlgorithm>( m.dualize() ) );

  ALEPH_ASSERT_THROW( m != m.dualize() );
  ALEPH_ASSERT_THROW( m == m.dualize().dualize() );

  for( auto&& pairing : pairings )
  {
    ALEPH_ASSERT_THROW( pairing.empty() == false );
    ALEPH_ASSERT_THROW( pairing.size()  == 4 );
  }

  for( auto&& pairing1 : pairings )
    for( auto&& pairing2 : pairings )
      ALEPH_ASSERT_THROW( pairing1 == pairing2 );

  ALEPH_ASSERT_THROW( pairings.front().contains( Index(0) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(1), Index(3) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(2), Index(4) ) );
  ALEPH_ASSERT_THROW( pairings.front().contains( Index(5), Index(6) ) );

  ALEPH_TEST_END();
}

template <class T> void setupBoundaryMatrix()
{
  using namespace aleph;
  using namespace topology;
  using namespace representations;

  ALEPH_TEST_BEGIN( "Boundary matrix setup & loading" );

  using Set    = Set<T>;
  using Vector = Vector<T>;

  auto m1 = BoundaryMatrix<Set>::load( CMAKE_SOURCE_DIR + std::string( "/tests/input/Triangle.txt" ) );
  auto m2 = BoundaryMatrix<Vector>::load( CMAKE_SOURCE_DIR + std::string( "/tests/input/Triangle.txt" ) );

  reduceBoundaryMatrix( m1 );
  reduceBoundaryMatrix( m2 );

  ALEPH_TEST_END();
}

int main()
{
  setupBoundaryMatrix<unsigned int> ();
  setupBoundaryMatrix<unsigned long>();
  setupBoundaryMatrix<int>();
  setupBoundaryMatrix<long>();

  testNonSquare<int>          ();
  testNonSquare<long>         ();
  testNonSquare<unsigned int> ();
  testNonSquare<unsigned long>();
}
<|endoftext|>


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

#ifndef _TOOLKIT_HELPER_TKRESMGR_HXX_
#define _TOOLKIT_HELPER_TKRESMGR_HXX_

#ifndef  _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef   _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif

class SimpleResMgr;
class ResMgr;

#define TK_RES_STRING(id)   TkResMgr::loadString(id)
#define TK_RES_IMAGE(id)    TkResMgr::loadImage(id)

// -----------------------------------------------------------------------------
// TkResMgr
// -----------------------------------------------------------------------------

class TkResMgr
{
    static SimpleResMgr* m_pSimpleResMgr;
    static ResMgr* m_pResMgr;

private:
    // no instantiation allowed
    TkResMgr() { }
    ~TkResMgr() { }

    // we'll instantiate one static member of the following class,
    // which in it's dtor ensures that m_pSimpleResMgr will be deleted
    class EnsureDelete
    {
    public:
        EnsureDelete() { }
        ~EnsureDelete();
    };
    friend class EnsureDelete;

protected:
    static void ensureImplExists();

public:
    // loads the string with the specified resource id
    static ::rtl::OUString loadString( sal_uInt16 nResId );

    // loads the image with the specified resource id
    static Image loadImage( sal_uInt16 nResId );
};

#endif // _TOOLKIT_HELPER_TKRESMGR_HXX_

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

#ifndef _TOOLKIT_HELPER_TKRESMGR_HXX_
#define _TOOLKIT_HELPER_TKRESMGR_HXX_

#include <rtl/ustring.hxx>
#include <vcl/image.hxx>

class SimpleResMgr;
class ResMgr;

#define TK_RES_STRING(id)   TkResMgr::loadString(id)
#define TK_RES_IMAGE(id)    TkResMgr::loadImage(id)

// -----------------------------------------------------------------------------
// TkResMgr
// -----------------------------------------------------------------------------

class TkResMgr
{
    static SimpleResMgr* m_pSimpleResMgr;
    static ResMgr* m_pResMgr;

private:
    // no instantiation allowed
    TkResMgr() { }
    ~TkResMgr() { }

    // we'll instantiate one static member of the following class,
    // which in it's dtor ensures that m_pSimpleResMgr will be deleted
    class EnsureDelete
    {
    public:
        EnsureDelete() { }
        ~EnsureDelete();
    };
    friend class EnsureDelete;

protected:
    static void ensureImplExists();

public:
    // loads the string with the specified resource id
    static ::rtl::OUString loadString( sal_uInt16 nResId );

    // loads the image with the specified resource id
    static Image loadImage( sal_uInt16 nResId );
};

#endif // _TOOLKIT_HELPER_TKRESMGR_HXX_

<|endoftext|>


<commit_before>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define  MAXSTRLEN  255                   // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1];	// 0号单元存放串的长度

void get_next(SString T,int next[]){
// 算法4.7
// 求模式串T的next函数值并存入数组next
   // 请补全代码
	int i,j;
	next[1]=0;
	j=0;
	while(i<T[0]){
		printf("%d\n",j);

		if(j == 0 || T[i]==T[j]){
			++i;
			++j;
			next[i]=j;}
		else{
			j=next[j];
		}
	}
}
int  main(){
	int next[MAXSTRLEN];
	SString S;
	int n,i,j;
	char ch;
	scanf("%d",&n);    // 指定要验证NEXT值的字符串个数
	ch=getchar();
	for(i=1;i<=n;i++)
	{
		ch=getchar();
		for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++)    // 录入字符串
		{
			S[j]=ch;
			ch=getchar();
		}
		S[0]=j-1;    // S[0]用于存储字符串中字符个数
		//printf("%s",S+1);
		get_next(S,next);
		printf("NEXT J is:");
		for(j=1;j<=S[0];j++)
			printf("%d",next[j]);
		printf("\n");
	}
}

<commit_msg>update uoj8591<commit_after>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define  MAXSTRLEN  255                   // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1];	// 0号单元存放串的长度

void get_next(SString T,int next[]){

	int i,j;
	next[1]=0;
	j=0;
	while(i<T[0]){
		printf("%d\n",j);

		if(j == 0 || T[i]==T[j]){
			++i;
			++j;
			next[i]=j;}
		else{
			j=next[j];
		}
	}
}
int  main(){
	int next[MAXSTRLEN];
	SString S;
	int n,i,j;
	char ch;
	scanf("%d",&n);    // 指定要验证NEXT值的字符串个数
	ch=getchar();
	for(i=1;i<=n;i++)
	{
		ch=getchar();
		for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++)    // 录入字符串
		{
			S[j]=ch;
			ch=getchar();
		}
		S[0]=j-1;    // S[0]用于存储字符串中字符个数
		//printf("%s",S+1);
		get_next(S,next);
		printf("NEXT J is:");
		for(j=1;j<=S[0];j++)
			printf("%d",next[j]);
		printf("\n");
	}
}

<|endoftext|>


<commit_before>#pragma once
#include <cmath>

struct vec3s {
    float r, theta, phi;
    float operator*( const vec3s & v );
    void rotate( float dtheta, float dphi );
    friend vec3s & operator += ( vec3s & lhs, const vec3s & rhs );
    friend vec3s & operator -= ( vec3s & lhs, const vec3s & rhs );
};

struct vec3d {
    float x, y, z;
    vec3d( const vec3s & v);
    float operator*( const vec3d & v );
};

inline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); }
<commit_msg>[add] types.hpp<commit_after>#pragma once
#include <cmath>
#include "types.hpp"

struct vec3s {
    float r, theta, phi;
    float operator*( const vec3s & v );
    void rotate( float dtheta, float dphi );
    friend vec3s & operator += ( vec3s & lhs, const vec3s & rhs );
    friend vec3s & operator -= ( vec3s & lhs, const vec3s & rhs );
};

struct vec3d {
    float x, y, z;
    vec3d( const vec3s & v);
    float operator*( const vec3d & v );
};

inline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); }
<|endoftext|>


<commit_before>//
// Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
#include "version.h"
#include <stdio.h>
#include <sstream>

void PrintMTConnectAgentVersion()
{
	printf("%s - built on " __TIMESTAMP__ "\n",
		GetAgentVersion().c_str());
}

std::string GetAgentVersion()
{
	std::stringstream verStream;
	verStream << "MTConnect Agent Version "
		<< AGENT_VERSION_MAJOR << "."
		<< AGENT_VERSION_MINOR << "."
		<< AGENT_VERSION_PATCH << "."
		<< AGENT_VERSION_BUILD;
	if(strlen(AGENT_VERSION_RC))
		verStream << " (" << AGENT_VERSION_RC << ")";
	return verStream.str();
}<commit_msg>Moved GetAgentVersion to precede use. <commit_after>//
// Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
#include "version.h"
#include <stdio.h>
#include <sstream>

std::string GetAgentVersion()
{
  std::stringstream verStream;
  verStream << "MTConnect Agent Version "
    << AGENT_VERSION_MAJOR << "."
    << AGENT_VERSION_MINOR << "."
    << AGENT_VERSION_PATCH << "."
    << AGENT_VERSION_BUILD;
  if(strlen(AGENT_VERSION_RC))
    verStream << " (" << AGENT_VERSION_RC << ")";
  return verStream.str();
}

void PrintMTConnectAgentVersion()
{
	printf("%s - built on " __TIMESTAMP__ "\n",
		GetAgentVersion().c_str());
}

<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <deque>
#include <map>
#include <utility>
#include <functional>
#include <algorithm>

namespace MotionPlanning
{
    template<class T>
    class TabuSearch
    {
        int short_memory_size;
        std::deque<T> short_memory;
        std::function<float(T)> fitness;
        std::function<T()> random;
        std::function<std::vector<T>(T)> neighbours;
    public:
        TabuSearch(int short_memory_size, std::function<float(T)> fitness, std::function<T()> random, std::function<std::vector<T>(T)> neighbours)
            : short_memory_size(short_memory_size),  short_memory(short_memory_size, random()), fitness(fitness), random(random), neighbours(neighbours) { };

        T explore(int max_attempts)
        {
            T current = short_memory.front();
            T best = current;
            float best_fitness = fitness(best);
            for (int i = 0; i < max_attempts; i++)
            {
                auto possibles = neighbours(current);

                for (auto& sm : short_memory)
                {
                    auto it = std::find(possibles.begin(), possibles.end(), sm);
                    if (it != possibles.end())
                    {
                        possibles.erase(it);
                    }
                }
                if (possibles.size() == 0)
                {
                    break;
                }

                std::vector<std::pair<float, T>> scores;
                std::transform(possibles.begin(), possibles.end(), std::inserter(scores, scores.begin()), [&](T p) { return std::pair<float, T>(fitness(p), p); });
                std::sort(scores.begin(), scores.end(), std::greater<std::pair<float, T>>());

                for (auto& kvp : scores)
                {
                    short_memory.pop_back();
                    short_memory.push_front(kvp.second);
                    if (kvp.first > best_fitness)
                    {
                        best = kvp.second;
                        best_fitness = kvp.first;
                    }
                    current = kvp.second;
                }
            }

            return best;
        }
    };
}<commit_msg>change class to be free function<commit_after>#pragma once

#include <vector>
#include <deque>
#include <map>
#include <utility>
#include <functional>
#include <algorithm>

namespace tabu
{
    template<class T>
    T search(int max_attempts,
             int short_memory_size,
             std::function<float(T)> fitness,
             std::function<T()> random,
             std::function<std::vector<T>(T)> neighbours)
    {
        std::deque<T> short_memory(short_memory_size, random());
        T current = short_memory.front();
        T best = current;
        float best_fitness = fitness(best);
        for (int i = 0; i < max_attempts; i++)
        {
            auto possibles = neighbours(current);

            for (auto& sm : short_memory)
            {
                auto it = std::find(possibles.begin(), possibles.end(), sm);
                if (it != possibles.end())
                {
                    possibles.erase(it);
                }
            }
            if (possibles.size() == 0)
            {
                break;
            }

            std::vector<std::pair<float, T>> scores;
            std::transform(possibles.begin(), possibles.end(), std::inserter(scores, scores.begin()), [&](T p) { return std::pair<float, T>(fitness(p), p); });
            std::sort(scores.begin(), scores.end(), std::greater<std::pair<float, T>>());

            for (auto& kvp : scores)
            {
                short_memory.pop_back();
                short_memory.push_front(kvp.second);
                if (kvp.first > best_fitness)
                {
                    best = kvp.second;
                    best_fitness = kvp.first;
                }
                current = kvp.second;
            }
        }

        return best;
    }
}<|endoftext|>


<commit_before>
#include "../interface/DrawTree.h"
#include "../src/UserFunctions.cc"

//
// Example function to show how the package works
// There are four objects: Color, ToPlot, Dataset, and DrawTree
//   - Color is simply a holder for custom colors
//     - This statement will show them: Color::plotTheColors();
//   - ToPlot holds the plotted variable, selection, plot dimensions at its core
//   - Dataset holds an individual physics dataset with
//   - DrawTree is the driver of it all, incorporating the above three
//
//

void Example() {

  //The object that draws it all
  DrawTree * dt = new DrawTree("tree",vError);

  //Set some various options
  dt->setLogy(true);
  dt->setDrawmcerr(true);
  dt->setDostack(true);
  dt->setLumi(1000);
  dt->setInframe(false);
  dt->setHasdata(true);
  dt->setDrawratio(true);

  //Custom function to add all datasets you want
  //See function to see how to add datasets to the DrawTree object by hand
  dt->autoAddDatasets("path/to/the/root/files","fullqcd ttbar wjets singlet zinv data","*.root");

  //Add (one or more) 'ToPlot' which sets the selection, plotted variable, plot dimensions
  //This will plot HT and MHT variables
  dt->addVar(ToPlot("MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0","HT","","","",50,500,2500));
  dt->addVar(ToPlot("MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0","MHT","","","",50,200,2200));

  //Function plots N-1 style in first argument - see function for full details
  //dt->Nminus1plots(ToPlot("HT>500$$MHT>200$$(Leptons==0)$$BTags>=0$$NJets>3$$MinDeltaPhi>0.5","HT","","","(isoPionTracks+isoElectronTracks+isoMuonTracks==0)&&(JetID>0)",40,0,4000),"$$");

  //Makes cutflow table with various options - see function for full details
  //dt->cutflow("1$$HT>500$$MHT>200$$(Leptons==0)$$NJets>3","BTags==0$$BTags==1$$BTags>=2","","No Cut$$HT>500$$MHT>200$$Lepton veto$$NJet>3$$NBjet==0$$NBjet==1$$NBjet>=2","");

  //Plot two sets of plots, with and without log y-scale
  dt->plot();
  dt->setLogy(false);
  dt->plot();

  //Delete the object, always
  delete dt;

  exit(0);

}

<commit_msg>add more descriptions to example<commit_after>
#include "../interface/DrawTree.h"
#include "../src/UserFunctions.cc"

//
// Example function to show how the package works
// There are four objects: Color, ToPlot, Dataset, and DrawTree
//   - Color is simply a holder for custom colors
//     - This statement will show them: Color::plotTheColors();
//   - ToPlot holds the plotted variable, selection, plot dimensions at its core
//   - Dataset holds an individual physics dataset as well as a Color
//   - DrawTree is the driver of it all, incorporating the above three
//     - Use ToPlot to graph variable from Dataset(s)
//
// The style used is the 2015 RunII CMS style
//

void Example() {

  //The object that draws it all
  DrawTree * dt = new DrawTree("tree",vError);

  //Set some various options
  //Many other options are available
  dt->setLogy(true);
  dt->setDrawmcerr(true);
  dt->setDostack(true);
  dt->setLumi(1000);
  dt->setInframe(false);
  dt->setHasdata(true);
  dt->setDrawratio(true);

  //Custom function to add all datasets you want
  //See function to see how to add datasets to the DrawTree object by hand
  dt->autoAddDatasets("path/to/the/root/files","fullqcd ttbar wjets singlet zinv data","*.root");

  //Add (one or more) 'ToPlot' which sets the selection, plotted variable, plot dimensions
  //Has some more options as well, including ability to use pre-defined options for variables
  //
  //This will plot HT and MHT variables
  dt->addVar(ToPlot("MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0","HT","","","",50,500,2500));
  dt->addVar(ToPlot("MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0","MHT","","","",50,200,2200));

  //Function plots N-1 style in first argument - see function for full details
  //dt->Nminus1plots(ToPlot("HT>500$$MHT>200$$(Leptons==0)$$BTags>=0$$NJets>3$$MinDeltaPhi>0.5","HT","","","(isoPionTracks+isoElectronTracks+isoMuonTracks==0)&&(JetID>0)",40,0,4000),"$$");

  //Makes cutflow table with various options - see function for full details
  //dt->cutflow("1$$HT>500$$MHT>200$$(Leptons==0)$$NJets>3","BTags==0$$BTags==1$$BTags>=2","","No Cut$$HT>500$$MHT>200$$Lepton veto$$NJet>3$$NBjet==0$$NBjet==1$$NBjet>=2","");

  //Plot two sets of plots, with and without log y-scale
  dt->plot();
  dt->setLogy(false);
  dt->plot();

  //Delete the object, always
  delete dt;

  exit(0);

}

<|endoftext|>


<commit_before>#include "ModuleImporter.h"
#include "Application.h"
#include "ImportMesh.h"
#include "ImportMaterial.h"
#include "CompTransform.h"

ModuleImporter::ModuleImporter(bool start_enabled) : Module(start_enabled)
{
	//char ownPth[MAX_PATH];

	//// Will contain exe path
	//HMODULE hModule = GetModuleHandle(NULL);
	//if (hModule != NULL)
	//{
	//	// When passing NULL to GetModuleHandle, it returns handle of exe itself
	//	GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
	//}
	name = "Importer";
}

ModuleImporter::~ModuleImporter()
{
}

bool ModuleImporter::Init(JSON_Object* node)
{
	// Will contain exe path
	HMODULE hModule = GetModuleHandle(NULL);
	if (hModule != NULL)
	{
		// When passing NULL to GetModuleHandle, it returns handle of exe itself
		GetModuleFileName(hModule, directoryExe, (sizeof(directoryExe)));
	}
	iMesh = new ImportMesh();
	iMaterial = new ImportMaterial();

	return true;
}

bool ModuleImporter::Start()
{
	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);
	aiAttachLogStream(&stream);

	return true;
}

update_status ModuleImporter::PreUpdate(float dt)
{
	perf_timer.Start();

	if (App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
	{
		//ImportMesh* imp = new ImportMesh();
		//imp->Load("Baker_house.rin");
	}

	if (App->input->dropped)
	{
		dropped_File_type = CheckFileType(App->input->dropped_filedir);

		//App->fs->CopyFileToAssets(App->input->dropped_filedir, ((Project*)App->gui->winManager[PROJECT])->GetFolderSee().c_str());
		//((Project*)App->gui->winManager[PROJECT])->AddFile(((Project*)App->gui->winManager[PROJECT])->GetFilesSee(), App->input->dropped_filedir);

		switch (dropped_File_type)
		{
		case F_MODEL_i:
		{
			LOG("IMPORTING MODEL, File Path: %s", App->input->dropped_filedir);
			std::string file;

			const aiScene* scene = aiImportFile(App->input->dropped_filedir, aiProcessPreset_TargetRealtime_MaxQuality);
			GameObject* obj = new GameObject();
			CompTransform* trans = (CompTransform*)obj->AddComponent(C_TRANSFORM);
			trans->SetZero();
			ProcessNode(scene->mRootNode, scene, obj);
			aiReleaseImport(scene);
			App->scene->gameobjects.push_back(obj);
			//Now Save Serialitzate OBJ -> Prefab

			break;
		}
		case F_TEXTURE_i:
		{
			LOG("IMPORTING TEXTURE, File Path: %s", App->input->dropped_filedir);
			iMaterial->Import(App->input->dropped_filedir);

			break;
		}
		case F_UNKNOWN_i:
		{
			SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "UNKNOWN file type dropped on window",
				App->input->dropped_filedir, App->window->window);
			LOG("UNKNOWN FILE TYPE, File Path: %s", App->input->dropped_filedir);

			break;
		}

		default:
			break;

		}

		App->input->dropped = false;
	}

	Update_t = perf_timer.ReadMs();

	return UPDATE_CONTINUE;
}

void ModuleImporter::ProcessNode(aiNode* node, const aiScene* scene, GameObject* obj)
{
	// Process all the Node's MESHES
	for (uint i = 0; i < node->mNumMeshes; i++)
	{
		GameObject* objChild = new GameObject();
		CompTransform* trans = (CompTransform*)objChild->AddComponent(C_TRANSFORM);
		trans->SetTransformation(node->mTransformation);
		aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
		iMesh->Import(scene, mesh, objChild, node->mName.C_Str());
		obj->AddChildGameObject_Copy(objChild);
	}

	// Process children
	for (uint i = 0; i < node->mNumChildren; i++)
	{
		ProcessNode(node->mChildren[i], scene, obj);
	}
}

update_status ModuleImporter::Update(float dt)
{
	return UPDATE_CONTINUE;
}

update_status ModuleImporter::PostUpdate(float dt)
{
	return UPDATE_CONTINUE;
}

update_status ModuleImporter::UpdateConfig(float dt)
{
	return UPDATE_CONTINUE;
}

bool ModuleImporter::CleanUp()
{
	aiDetachAllLogStreams();
	return true;
}

FileTypeImport ModuleImporter::CheckFileType(char * filedir)
{
	if (filedir != nullptr)
	{
		std::string file_type;
		std::string path(filedir);

		size_t extension_pos = path.find_last_of(".");

		file_type = path.substr(extension_pos + 1);

		//Set lowercase the extension to normalize it
		for (std::string::iterator it = file_type.begin(); it != file_type.end(); it++)
		{
			*it = tolower(*it);
		}

		if (file_type == "png" || file_type == "jpg" || file_type == "dds")
		{
			return F_TEXTURE_i;
		}
		else if (file_type == "fbx" || file_type == "obj")
		{
			return F_MODEL_i;
		}
		else
		{
			return F_UNKNOWN_i;
		}
	}
}
<commit_msg>Fix Name Importer<commit_after>#include "ModuleImporter.h"
#include "Application.h"
#include "ImportMesh.h"
#include "ImportMaterial.h"
#include "CompTransform.h"

ModuleImporter::ModuleImporter(bool start_enabled) : Module(start_enabled)
{
	//char ownPth[MAX_PATH];

	//// Will contain exe path
	//HMODULE hModule = GetModuleHandle(NULL);
	//if (hModule != NULL)
	//{
	//	// When passing NULL to GetModuleHandle, it returns handle of exe itself
	//	GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
	//}
	name = "Importer";
}

ModuleImporter::~ModuleImporter()
{
}

bool ModuleImporter::Init(JSON_Object* node)
{
	// Will contain exe path
	HMODULE hModule = GetModuleHandle(NULL);
	if (hModule != NULL)
	{
		// When passing NULL to GetModuleHandle, it returns handle of exe itself
		GetModuleFileName(hModule, directoryExe, (sizeof(directoryExe)));
	}
	iMesh = new ImportMesh();
	iMaterial = new ImportMaterial();

	return true;
}

bool ModuleImporter::Start()
{
	struct aiLogStream stream;
	stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);
	aiAttachLogStream(&stream);

	return true;
}

update_status ModuleImporter::PreUpdate(float dt)
{
	perf_timer.Start();

	if (App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)
	{
		//ImportMesh* imp = new ImportMesh();
		//imp->Load("Baker_house.rin");
	}

	if (App->input->dropped)
	{
		dropped_File_type = CheckFileType(App->input->dropped_filedir);

		//App->fs->CopyFileToAssets(App->input->dropped_filedir, ((Project*)App->gui->winManager[PROJECT])->GetFolderSee().c_str());
		//((Project*)App->gui->winManager[PROJECT])->AddFile(((Project*)App->gui->winManager[PROJECT])->GetFilesSee(), App->input->dropped_filedir);

		switch (dropped_File_type)
		{
		case F_MODEL_i:
		{
			LOG("IMPORTING MODEL, File Path: %s", App->input->dropped_filedir);
			std::string file;

			const aiScene* scene = aiImportFile(App->input->dropped_filedir, aiProcessPreset_TargetRealtime_MaxQuality);
			GameObject* obj = new GameObject();
			obj->SetName(App->GetCharfromConstChar(App->fs->FixName_directory(App->input->dropped_filedir).c_str()));
			CompTransform* trans = (CompTransform*)obj->AddComponent(C_TRANSFORM);
			trans->SetZero();
			ProcessNode(scene->mRootNode, scene, obj);
			aiReleaseImport(scene);
			App->scene->gameobjects.push_back(obj);
			//Now Save Serialitzate OBJ -> Prefab

			break;
		}
		case F_TEXTURE_i:
		{
			LOG("IMPORTING TEXTURE, File Path: %s", App->input->dropped_filedir);
			iMaterial->Import(App->input->dropped_filedir);

			break;
		}
		case F_UNKNOWN_i:
		{
			SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "UNKNOWN file type dropped on window",
				App->input->dropped_filedir, App->window->window);
			LOG("UNKNOWN FILE TYPE, File Path: %s", App->input->dropped_filedir);

			break;
		}

		default:
			break;

		}

		App->input->dropped = false;
	}

	Update_t = perf_timer.ReadMs();

	return UPDATE_CONTINUE;
}

void ModuleImporter::ProcessNode(aiNode* node, const aiScene* scene, GameObject* obj)
{
	// Process all the Node's MESHES
	for (uint i = 0; i < node->mNumMeshes; i++)
	{
		GameObject* objChild = new GameObject();
		objChild->SetName(App->GetCharfromConstChar(node->mName.C_Str()));
		CompTransform* trans = (CompTransform*)objChild->AddComponent(C_TRANSFORM);
		trans->SetTransformation(node->mTransformation);
		aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
		iMesh->Import(scene, mesh, objChild, node->mName.C_Str());
		obj->AddChildGameObject_Copy(objChild);
	}

	// Process children
	for (uint i = 0; i < node->mNumChildren; i++)
	{
		ProcessNode(node->mChildren[i], scene, obj);
	}
}

update_status ModuleImporter::Update(float dt)
{
	return UPDATE_CONTINUE;
}

update_status ModuleImporter::PostUpdate(float dt)
{
	return UPDATE_CONTINUE;
}

update_status ModuleImporter::UpdateConfig(float dt)
{
	return UPDATE_CONTINUE;
}

bool ModuleImporter::CleanUp()
{
	aiDetachAllLogStreams();
	return true;
}

FileTypeImport ModuleImporter::CheckFileType(char * filedir)
{
	if (filedir != nullptr)
	{
		std::string file_type;
		std::string path(filedir);

		size_t extension_pos = path.find_last_of(".");

		file_type = path.substr(extension_pos + 1);

		//Set lowercase the extension to normalize it
		for (std::string::iterator it = file_type.begin(); it != file_type.end(); it++)
		{
			*it = tolower(*it);
		}

		if (file_type == "png" || file_type == "jpg" || file_type == "dds")
		{
			return F_TEXTURE_i;
		}
		else if (file_type == "fbx" || file_type == "obj")
		{
			return F_MODEL_i;
		}
		else
		{
			return F_UNKNOWN_i;
		}
	}
}
<|endoftext|>


<commit_before>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTUInt16			numChannels = 2;
	TTUInt16			numSamples = 50000;
	TTFloat32			duration = 1500;
	TTUInt32			test9Index = 10;
	TTUInt32			test10Index = 11;
	TTUInt32			test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;
	TTSampleValue		test9Return, test10Return, test11Return, test12return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue("numChannels", numChannels);

	this->getAttributeValue("numChannels", test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue(TT("lengthInSamples"), numSamples);

	this->getAttributeValue(TT("lengthInSamples"), test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue(TT("length"), test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue(TT("length"), duration);

	this->getAttributeValue(TT("length"), test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue(TT("lengthInSamples"), test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	// TEST 9 & 10: set the value of two consecutive samples
	TTSampleValue pokeValue9 = TTRandom64();
	TTSampleValue pokeValue10 = TTRandom64();

	this->poke(test9Index, 1, pokeValue9);
	this->poke(test10Index, 1, pokeValue10);

	this->peek(test9Index, 1, test9Return);
	this->peek(test10Index, 1, test10Return);

	TTBoolean result9 = { pokeValue9 == test9Return };

	TTTestAssertion("set value one of two consecutive samples",
								result9,
								testAssertionCount,
								errorCount);

	if(!result9)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return);
	}

	TTBoolean result10 = { pokeValue10 == test10Return };

	TTTestAssertion("set value two of two consecutive samples",
								result10,
								testAssertionCount,
								errorCount);

	if(!result10)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return);
	}

	// TEST 11: test for interpolation between two consecutive samples
	TTFloat64 computedInterpFraction = TTRandom64();
	TTFloat64 computedInterpIndex = test9Index + computedInterpFraction;
	TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);

	this->peeki(computedInterpIndex, 1, test11Return);

	TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);

	TTTestAssertion("interpolate between two consecutive samples",
								result11,
								testAssertionCount,
								errorCount);

	if(!result11)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return);
	}

	/*
	// TODO: inbounds testing on hold until sorted out at TTMatrix parent class

	// TEST 12: test the new inBounds method

	TTUInt32 computedSampleAfterTail12 = -10; //test7Return + 5;
	TTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);

	TTTestAssertion("retrieving sample out of bounds produces an error",
								test12Err == kTTErrInvalidValue,
								testAssertionCount,
								errorCount);

	if(test12Err != kTTErrInvalidValue)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", kTTErrInvalidValue, test12Err);
	}

	TTUInt32 computedDistanceFromHead12 = test7Return * test1Return

	computedDistanceFromHead12 -= 50; // 50 before tail
	TTBoolean result12 = this->inBounds(computedDistanceFromHead12);

	if(result12)
	{
		TTTestLog("Testing in bounds 12 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 50; // at tail
	TTBoolean result13 = this->inBounds(computedDistanceFromHead12);

	if(result13)
	{
		TTTestLog("Testing in bounds 13 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 1; // 1 after tail
	TTBoolean result14 = this->inBounds(computedDistanceFromHead12);

	if(!result14)
	{
		TTTestLog("Testing in bounds 14 returned false, %i", computedDistanceFromHead12);
	}

	TTBoolean result15 = this->inBounds(-1);

	if(!result15)
	{
		TTTestLog("Negative values return false: %i", -1);
	}

	TTBoolean result16 = this->inBounds(0);

	if(!result16)
	{
		TTTestLog("Zero returns false: %i", 0);
	}
	*/

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<commit_msg>SampleMatrix: changing datatypes in test()<commit_after>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTInt16				numChannels = 2;
	TTInt32				numSamples = 50000;
	TTFloat32			duration = 1500;
	TTInt32				test9Index = 10;
	TTInt32				test10Index = 11;
	TTInt32				test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;
	TTSampleValue		test9Return, test10Return, test11Return, test12return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue("numChannels", numChannels);

	this->getAttributeValue("numChannels", test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue(TT("lengthInSamples"), numSamples);

	this->getAttributeValue(TT("lengthInSamples"), test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue(TT("length"), test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue(TT("length"), duration);

	this->getAttributeValue(TT("length"), test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue(TT("lengthInSamples"), test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	// TEST 9 & 10: set the value of two consecutive samples
	TTSampleValue pokeValue9 = TTRandom64();
	TTSampleValue pokeValue10 = TTRandom64();

	this->poke(test9Index, 1, pokeValue9);
	this->poke(test10Index, 1, pokeValue10);

	this->peek(test9Index, 1, test9Return);
	this->peek(test10Index, 1, test10Return);

	TTBoolean result9 = { pokeValue9 == test9Return };

	TTTestAssertion("set value one of two consecutive samples",
								result9,
								testAssertionCount,
								errorCount);

	if(!result9)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return);
	}

	TTBoolean result10 = { pokeValue10 == test10Return };

	TTTestAssertion("set value two of two consecutive samples",
								result10,
								testAssertionCount,
								errorCount);

	if(!result10)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return);
	}

	// TEST 11: test for interpolation between two consecutive samples
	TTFloat64 computedInterpFraction = TTRandom64();
	TTFloat64 computedInterpIndex = test9Index + computedInterpFraction;
	TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);

	this->peeki(computedInterpIndex, 1, test11Return);

	TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);

	TTTestAssertion("interpolate between two consecutive samples",
								result11,
								testAssertionCount,
								errorCount);

	if(!result11)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return);
	}

	/*
	// TODO: inbounds testing on hold until sorted out at TTMatrix parent class

	// TEST 12: test the new inBounds method

	TTUInt32 computedSampleAfterTail12 = -10; //test7Return + 5;
	TTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);

	TTTestAssertion("retrieving sample out of bounds produces an error",
								test12Err == kTTErrInvalidValue,
								testAssertionCount,
								errorCount);

	if(test12Err != kTTErrInvalidValue)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", kTTErrInvalidValue, test12Err);
	}

	TTUInt32 computedDistanceFromHead12 = test7Return * test1Return

	computedDistanceFromHead12 -= 50; // 50 before tail
	TTBoolean result12 = this->inBounds(computedDistanceFromHead12);

	if(result12)
	{
		TTTestLog("Testing in bounds 12 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 50; // at tail
	TTBoolean result13 = this->inBounds(computedDistanceFromHead12);

	if(result13)
	{
		TTTestLog("Testing in bounds 13 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 1; // 1 after tail
	TTBoolean result14 = this->inBounds(computedDistanceFromHead12);

	if(!result14)
	{
		TTTestLog("Testing in bounds 14 returned false, %i", computedDistanceFromHead12);
	}

	TTBoolean result15 = this->inBounds(-1);

	if(!result15)
	{
		TTTestLog("Negative values return false: %i", -1);
	}

	TTBoolean result16 = this->inBounds(0);

	if(!result16)
	{
		TTTestLog("Zero returns false: %i", 0);
	}
	*/

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<|endoftext|>


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

#include "chrome/common/resource_bundle.h"

#include <atlbase.h>

#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"

using namespace std;

ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;

// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
    return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;

  return 0;
}

/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
  DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
  g_shared_instance_ = new ResourceBundle();

  g_shared_instance_->LoadLocaleResources(pref_locale);
}

/* static */
void ResourceBundle::CleanupSharedInstance() {
  if (g_shared_instance_) {
    delete g_shared_instance_;
    g_shared_instance_ = NULL;
  }
}

/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
  // Must call InitSharedInstance before this function.
  CHECK(g_shared_instance_ != NULL);
  return *g_shared_instance_;
}

ResourceBundle::ResourceBundle()
    : locale_resources_dll_(NULL),
      theme_dll_(NULL) {
}

ResourceBundle::~ResourceBundle() {
  for (SkImageMap::iterator i = skia_images_.begin();
	   i != skia_images_.end(); i++) {
    delete i->second;
  }
  skia_images_.clear();

  if (locale_resources_dll_) {
    BOOL rv = FreeLibrary(locale_resources_dll_);
    DCHECK(rv);
  }
  if (theme_dll_) {
    BOOL rv = FreeLibrary(theme_dll_);
    DCHECK(rv);
  }
}

void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
  DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
  const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
  if (locale_path.empty()) {
    // It's possible that there are no locale dlls found, in which case we just
    // return.
    NOTREACHED();
    return;
  }

  // The dll should only have resources, not executable code.
  locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
                                        GetDataDllLoadFlags());
  DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}

std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
  std::wstring locale_path;
  PathService::Get(chrome::DIR_LOCALES, &locale_path);

  const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
  if (app_locale.empty())
    return app_locale;

  file_util::AppendToPath(&locale_path, app_locale + L".dll");
  return locale_path;
}

void ResourceBundle::LoadThemeResources() {
  DCHECK(NULL == theme_dll_) << "theme dll already loaded";
  std::wstring theme_dll_path;
  PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
  file_util::AppendToPath(&theme_dll_path, L"default.dll");

  // The dll should only have resources, not executable code.
  theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
                             GetDataDllLoadFlags());
  DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}

/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
  void* data_ptr = NULL;
  size_t data_size;
  bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
                                                 &data_ptr, &data_size);
  if (!success)
    return NULL;

  unsigned char* data = static_cast<unsigned char*>(data_ptr);

  // Decode the PNG.
  vector<unsigned char> png_data;
  int image_width;
  int image_height;
  if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
                          &png_data, &image_width, &image_height)) {
    NOTREACHED() << "Unable to decode theme resource " << resource_id;
    return NULL;
  }

  return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
                                                  image_width,
                                                  image_height);
}

SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
  AutoLock lock_scope(lock_);

  SkImageMap::const_iterator found = skia_images_.find(resource_id);
  SkBitmap* bitmap = NULL;

  // If not found load and store the image
  if (found == skia_images_.end()) {
    // Load the image
    bitmap = LoadBitmap(theme_dll_, resource_id);
    // We did not find the bitmap in the theme DLL, try the current one.
    if (!bitmap)
      bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
    skia_images_[resource_id] = bitmap;
  } else {
    bitmap = found->second;
  }

  // This bitmap will be returned when a bitmap is requested that can not be
  // found. The data inside is lazily initialized, so users must lock and
  static SkBitmap* empty_bitmap = NULL;

  // Handle the case where loading the bitmap failed.
  if (!bitmap) {
    LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
    if (!empty_bitmap) {
      empty_bitmap = new SkBitmap();
    }
    return empty_bitmap;
  }
  return bitmap;
}

bool ResourceBundle::LoadImageResourceBytes(int resource_id,
                                            vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}

bool ResourceBundle::LoadDataResourceBytes(int resource_id,
                                           vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
                                 resource_id, bytes);
}

bool ResourceBundle::LoadModuleResourceBytes(
    HINSTANCE module,
    int resource_id,
    std::vector<unsigned char>* bytes) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
                                      &data_size)) {
    bytes->resize(data_size);
    memcpy(&(bytes->front()), data_ptr, data_size);
    return true;
  } else {
    return false;
  }
}

HICON ResourceBundle::LoadThemeIcon(int icon_id) {
  return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  return GetRawDataResource(resource_id).as_string();
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(
        _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
    return StringPiece(static_cast<const char*>(data_ptr), data_size);
  return StringPiece();
}

// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
  return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
                            MAKEINTRESOURCE(IDR_MAINFRAME));
}

// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
  return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
                      MAKEINTRESOURCE(cursor_id));
}

std::wstring ResourceBundle::GetLocalizedString(int message_id) {
  // If for some reason we were unable to load a resource dll, return an empty
  // string (better than crashing).
  if (!locale_resources_dll_)
    return std::wstring();

  DCHECK(IS_INTRESOURCE(message_id));

  // Get a reference directly to the string resource.
  HINSTANCE hinstance = locale_resources_dll_;
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
                                                                  message_id);
  if (!image) {
    // Fall back on the current module (shouldn't be any strings here except
    // in unittests).
    image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
                                      message_id);
    if (!image) {
      NOTREACHED() << "unable to find resource: " << message_id;
      return std::wstring();
    }
  }
  // Copy into a wstring and return.
  return std::wstring(image->achString, image->nLength);
}

void ResourceBundle::LoadFontsIfNecessary() {
  AutoLock lock_scope(lock_);
  if (!base_font_.get()) {
    base_font_.reset(new ChromeFont());

    small_font_.reset(new ChromeFont());
    *small_font_ = base_font_->DeriveFont(-2);

    medium_font_.reset(new ChromeFont());
    *medium_font_ = base_font_->DeriveFont(3);

    medium_bold_font_.reset(new ChromeFont());
    *medium_bold_font_ =
        base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);

    large_font_.reset(new ChromeFont());
    *large_font_ = base_font_->DeriveFont(8);

    web_font_.reset(new ChromeFont());
    *web_font_ = base_font_->DeriveFont(1,
        base_font_->style() | ChromeFont::WEB);
  }
}

ChromeFont ResourceBundle::GetFont(FontStyle style) {
  LoadFontsIfNecessary();
  switch(style) {
    case SmallFont:
      return *small_font_;
    case MediumFont:
      return *medium_font_;
    case MediumBoldFont:
      return *medium_bold_font_;
    case LargeFont:
      return *large_font_;
    case WebFont:
      return *web_font_;
    default:
      return *base_font_;
  }
}

<commit_msg>Second try to make the theme dll no-executable.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/resource_bundle.h"

#include <atlbase.h>

#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"

using namespace std;

ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;

// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
    return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;

  return DONT_RESOLVE_DLL_REFERENCES;
}

/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
  DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
  g_shared_instance_ = new ResourceBundle();

  g_shared_instance_->LoadLocaleResources(pref_locale);
}

/* static */
void ResourceBundle::CleanupSharedInstance() {
  if (g_shared_instance_) {
    delete g_shared_instance_;
    g_shared_instance_ = NULL;
  }
}

/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
  // Must call InitSharedInstance before this function.
  CHECK(g_shared_instance_ != NULL);
  return *g_shared_instance_;
}

ResourceBundle::ResourceBundle()
    : locale_resources_dll_(NULL),
      theme_dll_(NULL) {
}

ResourceBundle::~ResourceBundle() {
  for (SkImageMap::iterator i = skia_images_.begin();
	   i != skia_images_.end(); i++) {
    delete i->second;
  }
  skia_images_.clear();

  if (locale_resources_dll_) {
    BOOL rv = FreeLibrary(locale_resources_dll_);
    DCHECK(rv);
  }
  if (theme_dll_) {
    BOOL rv = FreeLibrary(theme_dll_);
    DCHECK(rv);
  }
}

void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
  DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
  const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
  if (locale_path.empty()) {
    // It's possible that there are no locale dlls found, in which case we just
    // return.
    NOTREACHED();
    return;
  }

  // The dll should only have resources, not executable code.
  locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
                                        GetDataDllLoadFlags());
  DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}

std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
  std::wstring locale_path;
  PathService::Get(chrome::DIR_LOCALES, &locale_path);

  const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
  if (app_locale.empty())
    return app_locale;

  file_util::AppendToPath(&locale_path, app_locale + L".dll");
  return locale_path;
}

void ResourceBundle::LoadThemeResources() {
  DCHECK(NULL == theme_dll_) << "theme dll already loaded";
  std::wstring theme_dll_path;
  PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
  file_util::AppendToPath(&theme_dll_path, L"default.dll");

  // The dll should only have resources, not executable code.
  theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
                             GetDataDllLoadFlags());
  DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}

/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
  void* data_ptr = NULL;
  size_t data_size;
  bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
                                                 &data_ptr, &data_size);
  if (!success)
    return NULL;

  unsigned char* data = static_cast<unsigned char*>(data_ptr);

  // Decode the PNG.
  vector<unsigned char> png_data;
  int image_width;
  int image_height;
  if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
                          &png_data, &image_width, &image_height)) {
    NOTREACHED() << "Unable to decode theme resource " << resource_id;
    return NULL;
  }

  return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
                                                  image_width,
                                                  image_height);
}

SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
  AutoLock lock_scope(lock_);

  SkImageMap::const_iterator found = skia_images_.find(resource_id);
  SkBitmap* bitmap = NULL;

  // If not found load and store the image
  if (found == skia_images_.end()) {
    // Load the image
    bitmap = LoadBitmap(theme_dll_, resource_id);
    // We did not find the bitmap in the theme DLL, try the current one.
    if (!bitmap)
      bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
    skia_images_[resource_id] = bitmap;
  } else {
    bitmap = found->second;
  }

  // This bitmap will be returned when a bitmap is requested that can not be
  // found. The data inside is lazily initialized, so users must lock and
  static SkBitmap* empty_bitmap = NULL;

  // Handle the case where loading the bitmap failed.
  if (!bitmap) {
    LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
    if (!empty_bitmap) {
      empty_bitmap = new SkBitmap();
    }
    return empty_bitmap;
  }
  return bitmap;
}

bool ResourceBundle::LoadImageResourceBytes(int resource_id,
                                            vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}

bool ResourceBundle::LoadDataResourceBytes(int resource_id,
                                           vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
                                 resource_id, bytes);
}

bool ResourceBundle::LoadModuleResourceBytes(
    HINSTANCE module,
    int resource_id,
    std::vector<unsigned char>* bytes) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
                                      &data_size)) {
    bytes->resize(data_size);
    memcpy(&(bytes->front()), data_ptr, data_size);
    return true;
  } else {
    return false;
  }
}

HICON ResourceBundle::LoadThemeIcon(int icon_id) {
  return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  return GetRawDataResource(resource_id).as_string();
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(
        _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
    return StringPiece(static_cast<const char*>(data_ptr), data_size);
  return StringPiece();
}

// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
  return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
                            MAKEINTRESOURCE(IDR_MAINFRAME));
}

// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
  return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
                      MAKEINTRESOURCE(cursor_id));
}

std::wstring ResourceBundle::GetLocalizedString(int message_id) {
  // If for some reason we were unable to load a resource dll, return an empty
  // string (better than crashing).
  if (!locale_resources_dll_)
    return std::wstring();

  DCHECK(IS_INTRESOURCE(message_id));

  // Get a reference directly to the string resource.
  HINSTANCE hinstance = locale_resources_dll_;
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
                                                                  message_id);
  if (!image) {
    // Fall back on the current module (shouldn't be any strings here except
    // in unittests).
    image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
                                      message_id);
    if (!image) {
      NOTREACHED() << "unable to find resource: " << message_id;
      return std::wstring();
    }
  }
  // Copy into a wstring and return.
  return std::wstring(image->achString, image->nLength);
}

void ResourceBundle::LoadFontsIfNecessary() {
  AutoLock lock_scope(lock_);
  if (!base_font_.get()) {
    base_font_.reset(new ChromeFont());

    small_font_.reset(new ChromeFont());
    *small_font_ = base_font_->DeriveFont(-2);

    medium_font_.reset(new ChromeFont());
    *medium_font_ = base_font_->DeriveFont(3);

    medium_bold_font_.reset(new ChromeFont());
    *medium_bold_font_ =
        base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);

    large_font_.reset(new ChromeFont());
    *large_font_ = base_font_->DeriveFont(8);

    web_font_.reset(new ChromeFont());
    *web_font_ = base_font_->DeriveFont(1,
        base_font_->style() | ChromeFont::WEB);
  }
}

ChromeFont ResourceBundle::GetFont(FontStyle style) {
  LoadFontsIfNecessary();
  switch(style) {
    case SmallFont:
      return *small_font_;
    case MediumFont:
      return *medium_font_;
    case MediumBoldFont:
      return *medium_bold_font_;
    case LargeFont:
      return *large_font_;
    case WebFont:
      return *web_font_;
    default:
      return *base_font_;
  }
}

<|endoftext|>


<commit_before><commit_msg>Add CreateMemoryObject function to pass to NaClChromeMainStart()<commit_after><|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>
#include <QMimeData>
#include <QFileDialog>
#include <QBitmap>
#include <QIcon>
#include <QThreadPool>

#include <stdexcept>
#include <functional>

MainWindow::MainWindow(QWidget* parent)
        :  QMainWindow{parent}, _ui{new Ui::MainWindow},
          _portTimer{}, _image{}, _ezGraver{}, _connected{false} {
    _ui->setupUi(this);
    setAcceptDrops(true);

    connect(&_portTimer, &QTimer::timeout, this, &MainWindow::updatePorts);
    _portTimer.start(1000);

    initBindings();
    initConversionFlags();
    setConnected(false);
}

MainWindow::~MainWindow() {
    delete _ui;
}

void MainWindow::initBindings() {
    connect(_ui->burnTime, &QSlider::valueChanged, [this](int const& v) { _ui->burnTimeLabel->setText(QString::number(v)); });

    connect(this, &MainWindow::connectedChanged, _ui->ports, &QComboBox::setDisabled);
    connect(this, &MainWindow::connectedChanged, _ui->connect, &QPushButton::setDisabled);
    connect(this, &MainWindow::connectedChanged, _ui->disconnect, &QPushButton::setEnabled);

    connect(this, &MainWindow::connectedChanged, _ui->home, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->up, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->left, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->center, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->right, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->down, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->preview, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->start, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->pause, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->reset, &QPushButton::setEnabled);
    connect(_ui->conversionFlags, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [this](int index) {
        _ui->image->setConversionFlags(static_cast<Qt::ImageConversionFlags>(_ui->conversionFlags->itemData(index).toInt()));
    });

    auto uploadEnabled = [this]() { _ui->upload->setEnabled(_ui->image->imageLoaded() && _connected); };
    connect(this, &MainWindow::connectedChanged, uploadEnabled);
    connect(_ui->image, &ImageLabel::imageLoadedChanged, uploadEnabled);
}

void MainWindow::initConversionFlags() {
    _ui->conversionFlags->addItem("DiffuseDither", Qt::DiffuseDither);
    _ui->conversionFlags->addItem("OrderedDither", Qt::OrderedDither);
    _ui->conversionFlags->addItem("ThresholdDither", Qt::ThresholdDither);
    _ui->conversionFlags->setCurrentIndex(0);
}

void MainWindow::printVerbose(QString const& verbose) {
    _ui->verbose->appendPlainText(verbose);
}

void MainWindow::updatePorts() {
    QStringList ports{EzGraver::availablePorts()};
    ports.insert(0, "");

    QString original{_ui->ports->currentText()};
    _ui->ports->clear();
    _ui->ports->addItems(ports);

    if(ports.contains(original)) {
        _ui->ports->setCurrentText(original);
    }
}

void MainWindow::loadImage(QString const& fileName) {
    printVerbose(QString("loading image: %1").arg(fileName));

    QImage image{};
    if(!image.load(fileName)) {
        printVerbose("failed to load image");
        return;
    }

    _ui->image->setImage(image);
}

bool MainWindow::connected() const {
    return _connected;
}

void MainWindow::setConnected(bool connected) {
    _connected = connected;
    emit connectedChanged(connected);
}

void MainWindow::on_connect_clicked() {
    try {
        printVerbose(QString("connecting to port %1").arg(_ui->ports->currentText()));
        _ezGraver = EzGraver::create(_ui->ports->currentText());
        printVerbose("connection established successfully");
        setConnected(true);
    } catch(std::runtime_error const& e) {
        printVerbose(QString("Error: %1").arg(e.what()));
    }
}

void MainWindow::on_home_clicked() {
    printVerbose("moving to home");
    _ezGraver->home();
}

void MainWindow::on_up_clicked() {
    _ezGraver->up();
}

void MainWindow::on_left_clicked() {
    _ezGraver->left();
}

void MainWindow::on_center_clicked() {
    printVerbose("moving to center");
    _ezGraver->center();
}

void MainWindow::on_right_clicked() {
    _ezGraver->right();
}

void MainWindow::on_down_clicked() {
    _ezGraver->down();
}

void MainWindow::on_upload_clicked() {
    QImage image{_ui->image->pixmap()->toImage()};

    printVerbose("erasing EEPROM");
    _ezGraver->erase();

    QTimer::singleShot(6000, [this, image]() {
        printVerbose("uploading image to EEPROM");
        _ezGraver->uploadImage(image);
        printVerbose("upload completed");
    });
}

void MainWindow::on_preview_clicked() {
    printVerbose("drawing preview");
    _ezGraver->preview();
}

void MainWindow::on_start_clicked() {
    printVerbose(QString("starting engrave process with burn time %1").arg(_ui->burnTime->value()));
    _ezGraver->start(_ui->burnTime->value());
}

void MainWindow::on_pause_clicked() {
    printVerbose("pausing engrave process");
    _ezGraver->pause();
}

void MainWindow::on_reset_clicked() {
    printVerbose("resetting engraver");
    _ezGraver->reset();
}

void MainWindow::on_disconnect_clicked() {
    printVerbose("disconnecting");
    setConnected(false);
    _ezGraver.reset();
    printVerbose("disconnected");
}

void MainWindow::on_image_clicked() {
    auto fileName = QFileDialog::getOpenFileName(this, "Open Image", "", "Image Files (*.png *.jpeg *.jpg *.bmp)");
    loadImage(fileName);
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
    if(event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent* event) {
    QString fileName{event->mimeData()->urls()[0].toLocalFile()};
    loadImage(fileName);
}

<commit_msg>Added check if a file was actually selected before trying to load it.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>
#include <QMimeData>
#include <QFileDialog>
#include <QBitmap>
#include <QIcon>
#include <QThreadPool>

#include <stdexcept>
#include <functional>

MainWindow::MainWindow(QWidget* parent)
        :  QMainWindow{parent}, _ui{new Ui::MainWindow},
          _portTimer{}, _image{}, _ezGraver{}, _connected{false} {
    _ui->setupUi(this);
    setAcceptDrops(true);

    connect(&_portTimer, &QTimer::timeout, this, &MainWindow::updatePorts);
    _portTimer.start(1000);

    initBindings();
    initConversionFlags();
    setConnected(false);
}

MainWindow::~MainWindow() {
    delete _ui;
}

void MainWindow::initBindings() {
    connect(_ui->burnTime, &QSlider::valueChanged, [this](int const& v) { _ui->burnTimeLabel->setText(QString::number(v)); });

    connect(this, &MainWindow::connectedChanged, _ui->ports, &QComboBox::setDisabled);
    connect(this, &MainWindow::connectedChanged, _ui->connect, &QPushButton::setDisabled);
    connect(this, &MainWindow::connectedChanged, _ui->disconnect, &QPushButton::setEnabled);

    connect(this, &MainWindow::connectedChanged, _ui->home, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->up, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->left, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->center, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->right, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->down, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->preview, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->start, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->pause, &QPushButton::setEnabled);
    connect(this, &MainWindow::connectedChanged, _ui->reset, &QPushButton::setEnabled);
    connect(_ui->conversionFlags, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [this](int index) {
        _ui->image->setConversionFlags(static_cast<Qt::ImageConversionFlags>(_ui->conversionFlags->itemData(index).toInt()));
    });

    auto uploadEnabled = [this]() { _ui->upload->setEnabled(_ui->image->imageLoaded() && _connected); };
    connect(this, &MainWindow::connectedChanged, uploadEnabled);
    connect(_ui->image, &ImageLabel::imageLoadedChanged, uploadEnabled);
}

void MainWindow::initConversionFlags() {
    _ui->conversionFlags->addItem("DiffuseDither", Qt::DiffuseDither);
    _ui->conversionFlags->addItem("OrderedDither", Qt::OrderedDither);
    _ui->conversionFlags->addItem("ThresholdDither", Qt::ThresholdDither);
    _ui->conversionFlags->setCurrentIndex(0);
}

void MainWindow::printVerbose(QString const& verbose) {
    _ui->verbose->appendPlainText(verbose);
}

void MainWindow::updatePorts() {
    QStringList ports{EzGraver::availablePorts()};
    ports.insert(0, "");

    QString original{_ui->ports->currentText()};
    _ui->ports->clear();
    _ui->ports->addItems(ports);

    if(ports.contains(original)) {
        _ui->ports->setCurrentText(original);
    }
}

void MainWindow::loadImage(QString const& fileName) {
    printVerbose(QString("loading image: %1").arg(fileName));

    QImage image{};
    if(!image.load(fileName)) {
        printVerbose("failed to load image");
        return;
    }

    _ui->image->setImage(image);
}

bool MainWindow::connected() const {
    return _connected;
}

void MainWindow::setConnected(bool connected) {
    _connected = connected;
    emit connectedChanged(connected);
}

void MainWindow::on_connect_clicked() {
    try {
        printVerbose(QString("connecting to port %1").arg(_ui->ports->currentText()));
        _ezGraver = EzGraver::create(_ui->ports->currentText());
        printVerbose("connection established successfully");
        setConnected(true);
    } catch(std::runtime_error const& e) {
        printVerbose(QString("Error: %1").arg(e.what()));
    }
}

void MainWindow::on_home_clicked() {
    printVerbose("moving to home");
    _ezGraver->home();
}

void MainWindow::on_up_clicked() {
    _ezGraver->up();
}

void MainWindow::on_left_clicked() {
    _ezGraver->left();
}

void MainWindow::on_center_clicked() {
    printVerbose("moving to center");
    _ezGraver->center();
}

void MainWindow::on_right_clicked() {
    _ezGraver->right();
}

void MainWindow::on_down_clicked() {
    _ezGraver->down();
}

void MainWindow::on_upload_clicked() {
    QImage image{_ui->image->pixmap()->toImage()};

    printVerbose("erasing EEPROM");
    _ezGraver->erase();

    QTimer::singleShot(6000, [this, image]() {
        printVerbose("uploading image to EEPROM");
        _ezGraver->uploadImage(image);
        printVerbose("upload completed");
    });
}

void MainWindow::on_preview_clicked() {
    printVerbose("drawing preview");
    _ezGraver->preview();
}

void MainWindow::on_start_clicked() {
    printVerbose(QString("starting engrave process with burn time %1").arg(_ui->burnTime->value()));
    _ezGraver->start(_ui->burnTime->value());
}

void MainWindow::on_pause_clicked() {
    printVerbose("pausing engrave process");
    _ezGraver->pause();
}

void MainWindow::on_reset_clicked() {
    printVerbose("resetting engraver");
    _ezGraver->reset();
}

void MainWindow::on_disconnect_clicked() {
    printVerbose("disconnecting");
    setConnected(false);
    _ezGraver.reset();
    printVerbose("disconnected");
}

void MainWindow::on_image_clicked() {
    auto fileName = QFileDialog::getOpenFileName(this, "Open Image", "", "Images (*.png *.jpeg *.jpg *.bmp)");
    if(!fileName.isNull()) {
        loadImage(fileName);
    }
}

void MainWindow::dragEnterEvent(QDragEnterEvent* event) {
    if(event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent* event) {
    QString fileName{event->mimeData()->urls()[0].toLocalFile()};
    loadImage(fileName);
}

<|endoftext|>


<commit_before>#include "Frame.h"
#include "SettingsDialog.h"
#include "SettingCfg.h"
#include "config.h"
#include "ToolBar.h"

#include "preview/MainDialog.h"
#include "view/StagePanel.h"

namespace lr
{

BEGIN_EVENT_TABLE(Frame, d2d::Frame)
	EVT_MENU(ID_PREVIEW, Frame::OnPreview)
	EVT_MENU(ID_SETING_EXTEND, Frame::OnExtendSetting)
	EVT_MENU_RANGE(ID_TOOLBAR+1, ID_TOOLBAR+8, Frame::OnToolBarClick)
END_EVENT_TABLE()

Frame::Frame(const wxString& title, const wxString& filetag)
	: d2d::Frame(title, filetag)
{
	m_view_menu->Append(ID_PREVIEW, wxT("&Preview\tCtrl+Enter"), wxT("Play"));
	m_setting_menu->Append(ID_SETING_EXTEND, wxT("Extend"), wxT("Extend"));

	m_toolbar = new ToolBar(this, ID_TOOLBAR);
}

void Frame::onSaveAs(wxCommandEvent& event)
{
	if (!m_task) return;

	try {
		wxString filter = GetFileFilter() + "|PNG files (*.png)|*.png";
		wxFileDialog dlg(this, wxT("Save"), wxEmptyString, wxEmptyString, filter, wxFD_SAVE);
		if (dlg.ShowModal() == wxID_OK)
		{
			wxString filename = dlg.GetPath();
			wxString ext = d2d::FilenameTools::getExtension(filename);
			if (ext == "png") {
				SaveAsPNG(filename.ToStdString());
			} else {
				SaveAsJson(filename.ToStdString());
			}
		}
	} catch (d2d::Exception& e) {
		d2d::ExceptionDlg dlg(this, e);
		dlg.ShowModal();
	}
}

void Frame::OnToolBarClick(wxCommandEvent& event)
{
	int idx = event.GetId() - ID_TOOLBAR - 1;
	m_toolbar->OnClick(idx);
}

void Frame::OnPreview(wxCommandEvent& event)
{
	SettingCfg* cfg = SettingCfg::Instance();

	std::vector<const d2d::ISprite*> sprites;
	m_task->getAllSprite(sprites);

	preview::MainDialog dlg(this, cfg->m_view_width * PREVIEW_SCALE, cfg->m_view_height * PREVIEW_SCALE, sprites);
	dlg.ShowModal();

	d2d::EditPanel* stage = const_cast<d2d::EditPanel*>(m_task->getEditPanel());
	stage->resetCanvas();
}

void Frame::OnExtendSetting(wxCommandEvent& event)
{
	SettingDialog dlg(this, (StagePanel*)(m_task->getEditPanel()));
	dlg.ShowModal();
}

void Frame::SaveAsPNG(const std::string& filepath) const
{
	SettingCfg* cfg = SettingCfg::Instance();
	d2d::Snapshoot ss(cfg->m_map_width, cfg->m_map_height);
	StagePanel* stage = (StagePanel*)(m_task->getEditPanel());
	std::vector<d2d::ISprite*> sprites;
	stage->traverseSprites(d2d::FetchAllVisitor<d2d::ISprite>(sprites));
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ss.DrawSprite(sprites[i]);
	}
	ss.SaveToFile(filepath);

	stage->getCanvas()->resetInitState();
}

void Frame::SaveAsJson(const std::string& filepath) const
{
	wxString fixed = d2d::FilenameTools::getFilenameAddTag(filepath, m_filetag, "json");
	m_currFilename = fixed;
	m_task->store(fixed);
}

}<commit_msg>[FIXED] lr存成图片没有考虑visible<commit_after>#include "Frame.h"
#include "SettingsDialog.h"
#include "SettingCfg.h"
#include "config.h"
#include "ToolBar.h"

#include "preview/MainDialog.h"
#include "view/StagePanel.h"

namespace lr
{

BEGIN_EVENT_TABLE(Frame, d2d::Frame)
	EVT_MENU(ID_PREVIEW, Frame::OnPreview)
	EVT_MENU(ID_SETING_EXTEND, Frame::OnExtendSetting)
	EVT_MENU_RANGE(ID_TOOLBAR+1, ID_TOOLBAR+8, Frame::OnToolBarClick)
END_EVENT_TABLE()

Frame::Frame(const wxString& title, const wxString& filetag)
	: d2d::Frame(title, filetag)
{
	m_view_menu->Append(ID_PREVIEW, wxT("&Preview\tCtrl+Enter"), wxT("Play"));
	m_setting_menu->Append(ID_SETING_EXTEND, wxT("Extend"), wxT("Extend"));

	m_toolbar = new ToolBar(this, ID_TOOLBAR);
}

void Frame::onSaveAs(wxCommandEvent& event)
{
	if (!m_task) return;

	try {
		wxString filter = GetFileFilter() + "|PNG files (*.png)|*.png";
		wxFileDialog dlg(this, wxT("Save"), wxEmptyString, wxEmptyString, filter, wxFD_SAVE);
		if (dlg.ShowModal() == wxID_OK)
		{
			wxString filename = dlg.GetPath();
			wxString ext = d2d::FilenameTools::getExtension(filename);
			if (ext == "png") {
				SaveAsPNG(filename.ToStdString());
			} else {
				SaveAsJson(filename.ToStdString());
			}
		}
	} catch (d2d::Exception& e) {
		d2d::ExceptionDlg dlg(this, e);
		dlg.ShowModal();
	}
}

void Frame::OnToolBarClick(wxCommandEvent& event)
{
	int idx = event.GetId() - ID_TOOLBAR - 1;
	m_toolbar->OnClick(idx);
}

void Frame::OnPreview(wxCommandEvent& event)
{
	SettingCfg* cfg = SettingCfg::Instance();

	std::vector<const d2d::ISprite*> sprites;
	m_task->getAllSprite(sprites);

	preview::MainDialog dlg(this, cfg->m_view_width * PREVIEW_SCALE, cfg->m_view_height * PREVIEW_SCALE, sprites);
	dlg.ShowModal();

	d2d::EditPanel* stage = const_cast<d2d::EditPanel*>(m_task->getEditPanel());
	stage->resetCanvas();
}

void Frame::OnExtendSetting(wxCommandEvent& event)
{
	SettingDialog dlg(this, (StagePanel*)(m_task->getEditPanel()));
	dlg.ShowModal();
}

void Frame::SaveAsPNG(const std::string& filepath) const
{
	SettingCfg* cfg = SettingCfg::Instance();
	d2d::Snapshoot ss(cfg->m_map_width, cfg->m_map_height);
	StagePanel* stage = (StagePanel*)(m_task->getEditPanel());
	std::vector<d2d::ISprite*> sprites;
	stage->traverseSprites(d2d::FetchAllVisitor<d2d::ISprite>(sprites), d2d::DT_VISIBLE);
	for (int i = 0, n = sprites.size(); i < n; ++i) {
		ss.DrawSprite(sprites[i]);
	}
	ss.SaveToFile(filepath);

	stage->getCanvas()->resetInitState();
}

void Frame::SaveAsJson(const std::string& filepath) const
{
	wxString fixed = d2d::FilenameTools::getFilenameAddTag(filepath, m_filetag, "json");
	m_currFilename = fixed;
	m_task->store(fixed);
}

}<|endoftext|>


<commit_before>#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define PB push_back
#define MP make_pair
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
#define fst first
#define snd second

int main() {

  return 0;
}
<commit_msg>edit template of C++<commit_after>#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define MP make_pair
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
#define fst first
#define snd second

int main() {

  return 0;
}
<|endoftext|>