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

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx> // helper for implementations
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XPSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _HASH_MAPS_HXX
#include <HashMaps.hxx>
#endif

class ZipPackageFolderEnumeration : public cppu::WeakImplHelper2
<
    com::sun::star::container::XEnumeration,
    com::sun::star::lang::XServiceInfo
>
{
protected:
    ContentHash &rContents;
    ContentHash::const_iterator aIterator;
public:
    //ZipPackageFolderEnumeration (std::hash_map < rtl::OUString, com::sun::star::uno::Reference < com::sun::star::container::XNamed >, hashFunc, eqFunc > &rInput);
    ZipPackageFolderEnumeration (ContentHash &rInput);
    virtual ~ZipPackageFolderEnumeration( void );

    // XEnumeration
    virtual sal_Bool SAL_CALL hasMoreElements(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL nextElement(  )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);

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

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx> // helper for implementations
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XPSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _HASH_MAPS_HXX
#include <HashMaps.hxx>
#endif

class ZipPackageFolderEnumeration : public cppu::WeakImplHelper2
<
    com::sun::star::container::XEnumeration,
    com::sun::star::lang::XServiceInfo
>
{
protected:
    ContentHash rContents;
    ContentHash::const_iterator aIterator;
public:
    //ZipPackageFolderEnumeration (std::hash_map < rtl::OUString, com::sun::star::uno::Reference < com::sun::star::container::XNamed >, hashFunc, eqFunc > &rInput);
    ZipPackageFolderEnumeration (ContentHash &rInput);
    virtual ~ZipPackageFolderEnumeration( void );

    // XEnumeration
    virtual sal_Bool SAL_CALL hasMoreElements(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL nextElement(  )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);

};
#endif
<|endoftext|>


<commit_before>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Test that _LIBCPP_ALIGNOF acts the same as the C++11 keyword `alignof`, and
// not as the GNU extension `__alignof`. The former returns the minimal required
// alignment for a type, whereas the latter returns the preferred alignment.
//
// See llvm.org/PR39713

#include <type_traits>
#include "test_macros.h"

template <class T>
void test() {
  static_assert(_LIBCPP_ALIGNOF(T) == std::alignment_of<T>::value, "");
  static_assert(_LIBCPP_ALIGNOF(T) == TEST_ALIGNOF(T), "");
  static_assert(alignof(T) == __alignof(T), "");
#if TEST_STD_VER >= 11
  static_assert(_LIBCPP_ALIGNOF(T) == alignof(T), "");
#endif
#ifdef TEST_COMPILER_CLANG
  static_assert(_LIBCPP_ALIGNOF(T) == _Alignof(T), "");
#endif
}

int main() {
  test<int>();
  test<long long>();
  test<double>();
  test<long double>();
}
<commit_msg>Fix bad _LIBCPP_ALIGNOF test<commit_after>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Test that _LIBCPP_ALIGNOF acts the same as the C++11 keyword `alignof`, and
// not as the GNU extension `__alignof`. The former returns the minimal required
// alignment for a type, whereas the latter returns the preferred alignment.
//
// See llvm.org/PR39713

#include <type_traits>
#include "test_macros.h"

template <class T>
void test() {
  static_assert(_LIBCPP_ALIGNOF(T) == std::alignment_of<T>::value, "");
  static_assert(_LIBCPP_ALIGNOF(T) == TEST_ALIGNOF(T), "");
#if TEST_STD_VER >= 11
  static_assert(_LIBCPP_ALIGNOF(T) == alignof(T), "");
#endif
#ifdef TEST_COMPILER_CLANG
  static_assert(_LIBCPP_ALIGNOF(T) == _Alignof(T), "");
#endif
}

int main() {
  test<int>();
  test<long long>();
  test<double>();
  test<long double>();
}
<|endoftext|>


<commit_before>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH
#define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>

#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/gdt/playground/products/elliptic.hh>

#include <dune/hdd/playground/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>

#include "linearelliptic.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Tests {
namespace internal {

template< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >
class DiscretizationBlockSWIPDG
{
  typedef typename TestCaseType::GridType GridType;
  typedef typename TestCaseType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange = TestCaseType::dimRange;
public:
  typedef Discretizations::BlockSWIPDG< GridType, RangeFieldType, dimRange, polOrder, la_backend > Type;
}; // class DiscretizationBlockSWIPDG

} // namespace internal

template< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >
class EocStudyBlockSWIPDG
  : public MultiscaleEocStudyBase< TestCaseType,
                                   typename internal::DiscretizationBlockSWIPDG< TestCaseType,
                                                                                polOrder,
                                                                                la_backend >::Type >
{
  typedef EocStudyBlockSWIPDG< TestCaseType, polOrder, la_backend > ThisType;
  typedef MultiscaleEocStudyBase
      < TestCaseType,
        typename internal::DiscretizationBlockSWIPDG< TestCaseType, polOrder, la_backend >::Type > BaseType;

  typedef typename BaseType::DiscretizationType DiscretizationType;
  typedef typename DiscretizationType::GridViewType GridViewType;
  typedef typename BaseType::FunctionType FunctionType;
  typedef typename BaseType::VectorType   VectorType;

public:
  EocStudyBlockSWIPDG(const TestCaseType& test_case,
                      const std::vector< std::string > only_these_norms = std::vector< std::string >())
    : BaseType(test_case, only_these_norms)
  {}

  virtual ~EocStudyBlockSWIPDG() {}

  virtual std::string identifier() const DS_OVERRIDE DS_FINAL
  {
    return DiscretizationType::static_id()
        + " (polorder " + Stuff::Common::toString(polOrder)
        + ", " + this->test_case_.partitioning() + " partitioning)";
  } // ... identifier(...)

  virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "L2")
      return polOrder + 1;
    else if (type == "H1_semi")
      return polOrder;
    else if (type == "energy")
      return polOrder;
    else if (type == "eta_NC_OS2014")
      return polOrder;
    else if (type == "eta_R_OS2014")
      return polOrder + 1;
    else if (type == "eta_DF_OS2014")
      return polOrder;
    else if (type == "eta_OS2014")
      return polOrder;
    else if (type == "eff_OS2014")
      return 0;
    else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... expected_rate(...)

  virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUConformGrid< 2, 2 > > >::value
        || std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (this->test_case_.partitioning() == "[1 1 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {5.80e-01, 2.91e-01, 1.46e-01, 7.28e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {3.36, 3.38, 3.39, 3.40};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[2 2 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {2.90e-01, 1.46e-01, 7.28e-02, 3.64e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {2.48, 2.48, 2.49, 2.49};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[4 4 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {1.46e-01, 7.27e-02, 3.64e-02, 1.82e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {2.04, 2.03, 2.03, 2.04};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[8 8 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {7.24e-02, 3.64e-02, 1.83e-02, 9.10e-03};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {1.82, 1.81, 1.81, 1.81};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else
        DUNE_THROW(Stuff::Exceptions::test_results_missing, this->test_case_.partitioning());
    } else
      DUNE_THROW(Stuff::Exceptions::test_results_missing, Stuff::Common::Typename< TestCaseType >::value());
  } // ... expected_results(...)

private:
  virtual std::vector< std::string > available_norms() const DS_OVERRIDE DS_FINAL
  {
    return {"L2", "H1_semi", "energy"};
  }

  virtual double compute_norm(const GridViewType& grid_view,
                              const FunctionType& function,
                              const std::string type) const DS_OVERRIDE DS_FINAL
  {
    using namespace GDT;
    typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;
    typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;
    if (type == "L2") {
      return Products::L2< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "H1_semi") {
      return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "energy") {
      const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());
      assert(!diffusion_factor.parametric());
      assert(diffusion_factor.has_affine_part());
      const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());
      assert(!diffusion_tensor.parametric());
      assert(diffusion_tensor.has_affine_part());
      Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >
          elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);
      return elliptic_product.induced_norm(function);
    } else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  }

  virtual std::vector< std::string > available_estimators() const DS_OVERRIDE DS_FINAL
  {
    auto ret = DiscretizationType::available_estimators();
    if (std::find(ret.begin(), ret.end(), "eta_OS2014") != ret.end())
      ret.push_back("eff_OS2014");
    if (std::find(ret.begin(), ret.end(), "eta_OS2014_alt") != ret.end())
      ret.push_back("eff_OS2014_alt");
    return ret;
  } // ... available_estimators(..)

  virtual double estimate(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "eff_OS2014")
      return estimate(vector, "eta_OS2014") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else if (type == "eff_OS2014_alt")
      return estimate(vector, "eta_OS2014_alt") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else {
      assert(this->current_discretization_);
      return this->current_discretization_->estimate(vector, type);
    }
  } // ... estimate(...)
}; // class EocStudyBlockSWIPDG

} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH
<commit_msg>[test.linearelliptic-block-swipdg] use new estimator<commit_after>// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH
#define DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH

#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>

#include <dune/gdt/products/l2.hh>
#include <dune/gdt/products/h1.hh>
#include <dune/gdt/playground/products/elliptic.hh>

#include <dune/hdd/playground/linearelliptic/discretizations/block-swipdg.hh>
#include <dune/hdd/playground/linearelliptic/testcases/ESV2007.hh>

#include "linearelliptic.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Tests {
namespace internal {

template< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >
class DiscretizationBlockSWIPDG
{
  typedef typename TestCaseType::GridType GridType;
  typedef typename TestCaseType::RangeFieldType RangeFieldType;
  static const unsigned int dimRange = TestCaseType::dimRange;
public:
  typedef Discretizations::BlockSWIPDG< GridType, RangeFieldType, dimRange, polOrder, la_backend > Type;
}; // class DiscretizationBlockSWIPDG

} // namespace internal

template< class TestCaseType, int polOrder, Stuff::LA::ChooseBackend la_backend >
class EocStudyBlockSWIPDG
  : public MultiscaleEocStudyBase< TestCaseType,
                                   typename internal::DiscretizationBlockSWIPDG< TestCaseType,
                                                                                polOrder,
                                                                                la_backend >::Type >
{
  typedef EocStudyBlockSWIPDG< TestCaseType, polOrder, la_backend > ThisType;
  typedef MultiscaleEocStudyBase
      < TestCaseType,
        typename internal::DiscretizationBlockSWIPDG< TestCaseType, polOrder, la_backend >::Type > BaseType;

  typedef typename BaseType::DiscretizationType      DiscretizationType;
  typedef typename DiscretizationType::EstimatorType EstimatorType;
  typedef typename DiscretizationType::GridViewType GridViewType;
  typedef typename BaseType::FunctionType FunctionType;
  typedef typename BaseType::VectorType   VectorType;

public:
  EocStudyBlockSWIPDG(const TestCaseType& test_case,
                      const std::vector< std::string > only_these_norms = std::vector< std::string >())
    : BaseType(test_case, only_these_norms)
  {}

  virtual ~EocStudyBlockSWIPDG() {}

  virtual std::string identifier() const DS_OVERRIDE DS_FINAL
  {
    return DiscretizationType::static_id()
        + " (polorder " + Stuff::Common::toString(polOrder)
        + ", " + this->test_case_.partitioning() + " partitioning)";
  } // ... identifier(...)

  virtual size_t expected_rate(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "L2")
      return polOrder + 1;
    else if (type == "H1_semi")
      return polOrder;
    else if (type == "energy")
      return polOrder;
    else if (type == "eta_NC_OS2014")
      return polOrder;
    else if (type == "eta_R_OS2014")
      return polOrder + 1;
    else if (type == "eta_DF_OS2014")
      return polOrder;
    else if (type == "eta_OS2014")
      return polOrder;
    else if (type == "eff_OS2014")
      return 0;
    else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  } // ... expected_rate(...)

  virtual std::vector< double > expected_results(const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUConformGrid< 2, 2 > > >::value
        || std::is_same< TestCaseType, TestCases::ESV2007Multiscale< ALUGrid< 2, 2, simplex, conforming > > >::value) {
      if (this->test_case_.partitioning() == "[1 1 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {5.80e-01, 2.91e-01, 1.46e-01, 7.28e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {3.36, 3.38, 3.39, 3.40};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[2 2 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {2.90e-01, 1.46e-01, 7.28e-02, 3.64e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {2.48, 2.48, 2.49, 2.49};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[4 4 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {1.46e-01, 7.27e-02, 3.64e-02, 1.82e-02};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {2.04, 2.03, 2.03, 2.04};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else if (this->test_case_.partitioning() == "[8 8 1]") {
        if (polOrder == 1) {
          if (type == "energy")
            return {3.29e-01, 1.63e-01, 8.05e-02, 4.02e-02};
          else if (type == "eta_NC_OS2014")
            return {1.67e-01, 7.90e-02, 3.92e-02, 1.96e-02};
          else if (type == "eta_R_OS2014")
            return {7.24e-02, 3.64e-02, 1.83e-02, 9.10e-03};
          else if (type == "eta_DF_OS2014")
            return {3.56e-01, 1.77e-01, 8.74e-02, 4.36e-02};
          else if (type == "eta_OS2014")
            return {1.11e+00, 5.46e-01, 2.73e-01, 1.37e-01};
          else if (type == "eff_OS2014")
            return {1.82, 1.81, 1.81, 1.81};
          else
            DUNE_THROW(Stuff::Exceptions::test_results_missing, type);
        } else
          DUNE_THROW(Stuff::Exceptions::test_results_missing, polOrder);
      } else
        DUNE_THROW(Stuff::Exceptions::test_results_missing, this->test_case_.partitioning());
    } else
      DUNE_THROW(Stuff::Exceptions::test_results_missing, Stuff::Common::Typename< TestCaseType >::value());
  } // ... expected_results(...)

private:
  virtual std::vector< std::string > available_norms() const DS_OVERRIDE DS_FINAL
  {
    return {"L2", "H1_semi", "energy"};
  }

  virtual double compute_norm(const GridViewType& grid_view,
                              const FunctionType& function,
                              const std::string type) const DS_OVERRIDE DS_FINAL
  {
    using namespace GDT;
    typedef typename TestCaseType::ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;
    typedef typename TestCaseType::ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;
    if (type == "L2") {
      return Products::L2< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "H1_semi") {
      return Products::H1SemiGeneric< GridViewType >(grid_view).induced_norm(function);
    } else if (type == "energy") {
      const auto& diffusion_factor = *(this->test_case_.problem().diffusion_factor());
      assert(!diffusion_factor.parametric());
      assert(diffusion_factor.has_affine_part());
      const auto& diffusion_tensor = *(this->test_case_.problem().diffusion_tensor());
      assert(!diffusion_tensor.parametric());
      assert(diffusion_tensor.has_affine_part());
      Products::Elliptic< DiffusionFactorType, GridViewType, double, DiffusionTensorType >
          elliptic_product(*diffusion_factor.affine_part(), *diffusion_tensor.affine_part(), grid_view);
      return elliptic_product.induced_norm(function);
    } else
      DUNE_THROW(Stuff::Exceptions::wrong_input_given, "Wrong type '" << type << "' requested!");
  }

  virtual std::vector< std::string > available_estimators() const DS_OVERRIDE DS_FINAL
  {
    auto ret = EstimatorType::available();
    if (std::find(ret.begin(), ret.end(), "eta_OS2014") != ret.end())
      ret.push_back("eff_OS2014");
    if (std::find(ret.begin(), ret.end(), "eta_OS2014_alt") != ret.end())
      ret.push_back("eff_OS2014_alt");
    return ret;
  } // ... available_estimators(..)

  virtual double estimate(const VectorType& vector, const std::string type) const DS_OVERRIDE DS_FINAL
  {
    if (type == "eff_OS2014")
      return estimate(vector, "eta_OS2014") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else if (type == "eff_OS2014_alt")
      return estimate(vector, "eta_OS2014_alt") / const_cast< ThisType& >(*this).current_error_norm("energy");
    else {
      assert(this->current_discretization_);
      return EstimatorType::estimate(*this->current_discretization_->ansatz_space(),
                                     vector,
                                     this->test_case_.problem(),
                                     type);
    }
  } // ... estimate(...)
}; // class EocStudyBlockSWIPDG

} // namespace Tests
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_TEST_LINEARELLIPTIC_BLOCK_SWIPDG_HH
<|endoftext|>


<commit_before>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

int main()
{
}
<commit_msg>test commit<commit_after>// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

int main()
{
}

<|endoftext|>


<commit_before>
#include "catch.hpp"

#include <iostream>
#include <cstring>
#include <mapnik/color.hpp>
#include <mapnik/image.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_util_jpeg.hpp>
#include <mapnik/util/fs.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_context.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
#pragma GCC diagnostic pop

inline bool make_directory(std::string const& dir) {
    return boost::filesystem::create_directory(dir);
}

TEST_CASE("image io") {

SECTION("readers") {

    std::string should_throw;
    boost::optional<std::string> type;
    try
    {
        mapnik::image_rgba8 im_og;
        auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();
        mapnik::detail::buffer buf(im_og.bytes(), im_size);
        mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());
        CHECK( im2.bytes() == im_og.bytes() );
#if defined(HAVE_JPEG)
        should_throw = "./test/data/images/blank.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        // actually a png so jpeg reader should throw
        should_throw = "./test/data/images/landusepattern.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        try
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type));
            REQUIRE(false);
        }
        catch (std::exception const& ex)
        {
            REQUIRE( std::string(ex.what()) == std::string("JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50") );
        }

#endif

        REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); // should throw rather than overflow

#if defined(HAVE_CAIRO)
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),
            mapnik::cairo_surface_closer());
        mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));
        im_data.set(1);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );
        // Should set back to fully transparent
        mapnik::cairo_image_to_rgba8(im_data, image_surface);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );
#endif

#if defined(HAVE_PNG)
        should_throw = "./test/data/images/blank.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        should_throw = "./test/data/images/xcode-CgBI.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_TIFF)
        should_throw = "./test/data/images/blank.tiff";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_WEBP)
        should_throw = "./test/data/images/blank.webp";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif
    }
    catch (std::exception const & ex)
    {
        std::clog << ex.what() << "\n";
        REQUIRE(false);
    }

} // END SECTION

SECTION("writers options")
{
#if defined(HAVE_JPEG)
    // test we can parse both jpegXX and quality=XX options
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpegXX"));
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpeg:quality=XX"));
    int q0 = mapnik::detail::parse_jpeg_quality("jpeg50");
    int q1 = mapnik::detail::parse_jpeg_quality("jpeg:quality=50");
    REQUIRE(q0 == q1);
#endif
} // END SECTION

SECTION("image_util : save_to_file/save_to_stream/save_to_string")
{
    mapnik::image_rgba8 im(256,256);
    std::string named_color = "lightblue";
    mapnik::fill(im, mapnik::color(named_color).rgba());
    ////////////////////////////////////////////////////
    std::vector<std::tuple<std::string, std::string> > supported_types;
#if defined(HAVE_PNG)
    supported_types.push_back(std::make_tuple("png","png"));
    supported_types.push_back(std::make_tuple("png","png24"));
    supported_types.push_back(std::make_tuple("png","png32"));
    supported_types.push_back(std::make_tuple("png","png8"));
    supported_types.push_back(std::make_tuple("png","png256"));
#endif
#if defined(HAVE_JPEG)
    supported_types.push_back(std::make_tuple("jpeg","jpeg"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg80"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg90"));
#endif
#if defined(HAVE_TIFF)
    supported_types.push_back(std::make_tuple("tiff","tiff"));
#endif
#if defined(HAVE_WEBP)
    supported_types.push_back(std::make_tuple("webp","webp"));
#endif

    REQUIRE(make_directory("/tmp/mapnik-tests/"));

    for (auto const& info : supported_types)
    {
        std::string extension;
        std::string format;
        std::tie(extension, format) = info;
        std::string filename = (boost::format("/tmp/mapnik-tests/mapnik-%1%.%2%") % named_color % extension).str();
        mapnik::save_to_file(im, filename);
        std::string str = mapnik::save_to_string(im, format);
        std::ostringstream ss;
        mapnik::save_to_stream(im, ss, format);
        CHECK(str.length() == ss.str().length());
        std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename, extension));
        unsigned w = reader->width();
        unsigned h = reader->height();
        auto im2 = reader->read(0, 0, w, h);
        CHECK(im2.size() == im.size());
        if (extension == "png" || extension == "tiff")
        {
            CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));
        }
        if (mapnik::util::exists(filename))
        {
            mapnik::util::remove(filename);
        }
    }
}
} // END TEST_CASE
<commit_msg>fix directory assertion logic<commit_after>
#include "catch.hpp"

#include <iostream>
#include <cstring>
#include <mapnik/color.hpp>
#include <mapnik/image.hpp>
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_util_jpeg.hpp>
#include <mapnik/util/fs.hpp>
#if defined(HAVE_CAIRO)
#include <mapnik/cairo/cairo_context.hpp>
#include <mapnik/cairo/cairo_image_util.hpp>
#endif

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/format.hpp>
#include <boost/filesystem/convenience.hpp>
#pragma GCC diagnostic pop

inline void make_directory(std::string const& dir) {
    boost::filesystem::create_directory(dir);
}

TEST_CASE("image io") {

SECTION("readers") {

    std::string should_throw;
    boost::optional<std::string> type;
    try
    {
        mapnik::image_rgba8 im_og;
        auto im_size = mapnik::image_rgba8::pixel_size * im_og.width() * im_og.height();
        mapnik::detail::buffer buf(im_og.bytes(), im_size);
        mapnik::image_rgba8 im2(im_og.width(), im_og.height(), buf.data());
        CHECK( im2.bytes() == im_og.bytes() );
#if defined(HAVE_JPEG)
        should_throw = "./test/data/images/blank.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        // actually a png so jpeg reader should throw
        should_throw = "./test/data/images/landusepattern.jpg";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        try
        {
            std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type));
            REQUIRE(false);
        }
        catch (std::exception const& ex)
        {
            REQUIRE( std::string(ex.what()) == std::string("JPEG Reader: libjpeg could not read image: Not a JPEG file: starts with 0x89 0x50") );
        }

#endif

        REQUIRE_THROWS(mapnik::image_rgba8 im(-10,-10)); // should throw rather than overflow

#if defined(HAVE_CAIRO)
        mapnik::cairo_surface_ptr image_surface(
            cairo_image_surface_create(CAIRO_FORMAT_ARGB32,256,257),
            mapnik::cairo_surface_closer());
        mapnik::image_rgba8 im_data(cairo_image_surface_get_width(&*image_surface), cairo_image_surface_get_height(&*image_surface));
        im_data.set(1);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(1) );
        // Should set back to fully transparent
        mapnik::cairo_image_to_rgba8(im_data, image_surface);
        REQUIRE( (unsigned)im_data(0,0) == unsigned(0) );
#endif

#if defined(HAVE_PNG)
        should_throw = "./test/data/images/blank.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));

        should_throw = "./test/data/images/xcode-CgBI.png";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_TIFF)
        should_throw = "./test/data/images/blank.tiff";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif

#if defined(HAVE_WEBP)
        should_throw = "./test/data/images/blank.webp";
        REQUIRE( mapnik::util::exists( should_throw ) );
        type = mapnik::type_from_filename(should_throw);
        REQUIRE( type );
        REQUIRE_THROWS(std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(should_throw,*type)));
#endif
    }
    catch (std::exception const & ex)
    {
        std::clog << ex.what() << "\n";
        REQUIRE(false);
    }

} // END SECTION

SECTION("writers options")
{
#if defined(HAVE_JPEG)
    // test we can parse both jpegXX and quality=XX options
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpegXX"));
    REQUIRE_THROWS(mapnik::detail::parse_jpeg_quality("jpeg:quality=XX"));
    int q0 = mapnik::detail::parse_jpeg_quality("jpeg50");
    int q1 = mapnik::detail::parse_jpeg_quality("jpeg:quality=50");
    REQUIRE(q0 == q1);
#endif
} // END SECTION

SECTION("image_util : save_to_file/save_to_stream/save_to_string")
{
    mapnik::image_rgba8 im(256,256);
    std::string named_color = "lightblue";
    mapnik::fill(im, mapnik::color(named_color).rgba());
    ////////////////////////////////////////////////////
    std::vector<std::tuple<std::string, std::string> > supported_types;
#if defined(HAVE_PNG)
    supported_types.push_back(std::make_tuple("png","png"));
    supported_types.push_back(std::make_tuple("png","png24"));
    supported_types.push_back(std::make_tuple("png","png32"));
    supported_types.push_back(std::make_tuple("png","png8"));
    supported_types.push_back(std::make_tuple("png","png256"));
#endif
#if defined(HAVE_JPEG)
    supported_types.push_back(std::make_tuple("jpeg","jpeg"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg80"));
    supported_types.push_back(std::make_tuple("jpeg","jpeg90"));
#endif
#if defined(HAVE_TIFF)
    supported_types.push_back(std::make_tuple("tiff","tiff"));
#endif
#if defined(HAVE_WEBP)
    supported_types.push_back(std::make_tuple("webp","webp"));
#endif

    std::string directory_name("/tmp/mapnik-tests/");
    make_directory(directory_name);
    REQUIRE(mapnik::util::exists(directory_name));

    for (auto const& info : supported_types)
    {
        std::string extension;
        std::string format;
        std::tie(extension, format) = info;
        std::string filename = (boost::format(directory_name + "mapnik-%1%.%2%") % named_color % extension).str();
        mapnik::save_to_file(im, filename);
        std::string str = mapnik::save_to_string(im, format);
        std::ostringstream ss;
        mapnik::save_to_stream(im, ss, format);
        CHECK(str.length() == ss.str().length());
        std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename, extension));
        unsigned w = reader->width();
        unsigned h = reader->height();
        auto im2 = reader->read(0, 0, w, h);
        CHECK(im2.size() == im.size());
        if (extension == "png" || extension == "tiff")
        {
            CHECK(0 == std::memcmp(im2.bytes(), im.bytes(), im.width() * im.height()));
        }
        if (mapnik::util::exists(filename))
        {
            mapnik::util::remove(filename);
        }
    }
}
} // END TEST_CASE
<|endoftext|>


<commit_before>#include <test/unit/math/test_ad.hpp>
#include <cmath>
#include <complex>
#include <vector>
#include <type_traits>

TEST(mixFun, absBasics) {
  using stan::math::abs;
  int a = abs(1);

  double b = abs(-2.3);

  Eigen::Matrix<double, -1, -1> x(2, 3);
  x << 1, 2, 3, 4, 5, 6;
  Eigen::Matrix<double, -1, -1> y = abs(x);

  std::vector<int> u{1, 2, 3, 4};
  std::vector<int> v = abs(u);
}

template <typename T1, typename T2>
using is_complex_and_base_ret = stan::bool_constant<
(!stan::is_complex<stan::scalar_type_t<std::decay_t<T1>>>::value)
 || (stan::is_complex<stan::scalar_type_t<std::decay_t<T1>>>::value &&
     !stan::is_complex<stan::scalar_type_t<std::decay_t<T2>>>::value)>;
TEST(mixFun, abs) {
  auto f = [](const auto& x) {
    auto xx = stan::math::abs(x);
    static_assert(is_complex_and_base_ret<decltype(x), decltype(xx)>::value, "NO!");
    return xx;
  };
  stan::test::expect_common_nonzero_unary(f);
  // 0 (no derivative at 0)
  stan::test::expect_value(f, 0);
  stan::test::expect_value(f, 0.0);

  stan::test::expect_ad(f, -3);
  stan::test::expect_ad(f, -2);
  stan::test::expect_ad(f, 2);

  stan::test::expect_ad(f, -17.3);
  stan::test::expect_ad(f, -0.68);
  stan::test::expect_ad(f, 0.68);
  stan::test::expect_ad(f, 2.0);
  stan::test::expect_ad(f, 4.0);

  // complex tests
  for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
    for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
      stan::test::expect_ad(f, std::complex<double>(re, im));
    }
  }

  // vector<double>
  using svd_t = std::vector<double>;
  stan::test::expect_ad(f, svd_t{});
  stan::test::expect_ad(f, svd_t{1.0});
  stan::test::expect_ad(f, svd_t{1.9, -2.3});

  // vector<vector<double>>
  using svvd_t = std::vector<svd_t>;
  stan::test::expect_ad(f, svvd_t{});
  stan::test::expect_ad(f, svvd_t{svd_t{}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});

  // vector<complex<double>>
  using c_t = std::complex<double>;
  using svc_t = std::vector<c_t>;
  stan::test::expect_ad(f, svc_t{});
  stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});
  stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});

  // vector<vector<complex<double>>>
  using svvc_t = std::vector<svc_t>;
  stan::test::expect_ad(f, svvc_t{});
  stan::test::expect_ad(f, svvc_t{{}});
  stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});
  stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},
                                  svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});

  // VectorXd
  using v_t = Eigen::VectorXd;
  v_t a0(0);
  stan::test::expect_ad(f, a0);
  stan::test::expect_ad_matvar(f, a0);
  v_t a1(1);
  a1 << 1.9;
  stan::test::expect_ad(f, a1);
  stan::test::expect_ad_matvar(f, a1);
  v_t a2(2);
  a2 << 1.9, -2.3;
  stan::test::expect_ad(f, a2);
  stan::test::expect_ad_matvar(f, a2);

  // RowVectorXd
  using rv_t = Eigen::RowVectorXd;
  rv_t b0(0);
  stan::test::expect_ad(f, b0);
  stan::test::expect_ad_matvar(f, b0);
  rv_t b1(1);
  b1 << 1.9;
  stan::test::expect_ad(f, b1);
  stan::test::expect_ad_matvar(f, b1);
  rv_t b2(2);
  b2 << 1.9, -2.3;
  stan::test::expect_ad(f, b2);
  stan::test::expect_ad_matvar(f, b2);

  // MatrixXd
  using m_t = Eigen::MatrixXd;
  m_t c0(0, 0);
  stan::test::expect_ad(f, c0);
  stan::test::expect_ad_matvar(f, c0);
  m_t c0i(0, 2);
  stan::test::expect_ad(f, c0i);
  stan::test::expect_ad_matvar(f, c0i);
  m_t c0ii(2, 0);
  stan::test::expect_ad(f, c0ii);
  stan::test::expect_ad_matvar(f, c0ii);
  m_t c2(2, 1);
  c2 << 1.3, -2.9;
  stan::test::expect_ad(f, c2);
  stan::test::expect_ad_matvar(f, c2);
  m_t c6(3, 2);
  c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;
  stan::test::expect_ad(f, c6);
  stan::test::expect_ad_matvar(f, c6);

  // vector<VectorXd>
  using av_t = std::vector<Eigen::VectorXd>;
  av_t d0;
  stan::test::expect_ad(f, d0);
  stan::test::expect_ad_matvar(f, d0);
  av_t d1{a0};
  stan::test::expect_ad(f, d1);
  stan::test::expect_ad_matvar(f, d1);
  av_t d2{a1, a2};
  stan::test::expect_ad(f, d2);
  stan::test::expect_ad_matvar(f, d2);

  // vector<RowVectorXd>
  using arv_t = std::vector<Eigen::RowVectorXd>;
  arv_t e0;
  stan::test::expect_ad(f, e0);
  stan::test::expect_ad_matvar(f, e0);
  arv_t e1{b0};
  stan::test::expect_ad(f, e1);
  stan::test::expect_ad_matvar(f, e1);
  arv_t e2{b1, b2};
  stan::test::expect_ad(f, e2);
  stan::test::expect_ad_matvar(f, e2);

  // vector<MatrixXd>
  using am_t = std::vector<Eigen::MatrixXd>;
  am_t g0;
  stan::test::expect_ad(f, g0);
  stan::test::expect_ad_matvar(f, g0);
  am_t g1{c0};
  stan::test::expect_ad(f, g1);
  stan::test::expect_ad_matvar(f, g1);
  am_t g2{c2, c6};
  stan::test::expect_ad(f, g2);
  stan::test::expect_ad_matvar(f, g2);

  // VectorXcd
  using vc_t = Eigen::VectorXcd;
  vc_t h0(0);
  stan::test::expect_ad(f, h0);
  vc_t h1(1);
  h1 << c_t{1.9, -1.8};
  stan::test::expect_ad(f, h1);
  vc_t h2(2);
  h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
  stan::test::expect_ad(f, h2);

  // RowVectorXcd
  using rvc_t = Eigen::RowVectorXcd;
  rvc_t j0(0);
  stan::test::expect_ad(f, j0);
  rvc_t j1(1);
  j1 << c_t{1.9, -1.8};
  stan::test::expect_ad(f, j1);
  rvc_t j2(2);
  j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
  stan::test::expect_ad(f, j2);

  // MatrixXcd
  using mc_t = Eigen::MatrixXcd;
  mc_t k0(0, 0);
  stan::test::expect_ad(f, k0);
  mc_t k2(1, 2);
  k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};
  stan::test::expect_ad(f, k2);
  mc_t k6(3, 2);
  k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},
      c_t{-13, 125.7}, c_t{-12.5, -10.5};
  stan::test::expect_ad(f, k6);

  // vector<VectorXcd>
  using avc_t = std::vector<vc_t>;
  avc_t m0;
  stan::test::expect_ad(f, m0);
  avc_t m1{h1};
  stan::test::expect_ad(f, m1);
  avc_t m2{h1, h2};
  stan::test::expect_ad(f, m2);

  // vector<RowVectorXcd>
  using arvc_t = std::vector<rvc_t>;
  arvc_t p0(0);
  stan::test::expect_ad(f, p0);
  arvc_t p1{j1};
  stan::test::expect_ad(f, p1);
  arvc_t p2{j1, j2};
  stan::test::expect_ad(f, p2);

  // vector<MatrixXcd>
  using amc_t = std::vector<mc_t>;
  amc_t q0;
  stan::test::expect_ad(f, q0);
  amc_t q1{k2};
  stan::test::expect_ad(f, q1);
  amc_t q2{k2, k6};
  stan::test::expect_ad(f, q2);
}
TEST(mixFun, absReturnType) {
  // validate return types not overpromoted to complex by assignability
  std::complex<stan::math::var> a = 3;
  stan::math::var b = abs(a);

  std::complex<stan::math::fvar<double>> c = 3;
  stan::math::fvar<double> d = abs(c);
  SUCCEED();
}

TEST(mathMixMatFun, abs_varmat) {
  using stan::math::vec_concat;
  using stan::test::expect_ad_vector_matvar;
  using stan::test::internal::common_nonzero_args;
  auto f = [](const auto& x1) {
    using stan::math::abs;
    return abs(x1);
  };
  std::vector<double> com_args = common_nonzero_args();
  std::vector<double> args{-3, 2, -0.68, 1};
  auto all_args = vec_concat(com_args, args);
  Eigen::VectorXd A(all_args.size());
  for (int i = 0; i < all_args.size(); ++i) {
    A(i) = all_args[i];
  }
  expect_ad_vector_matvar(f, A);
}
<commit_msg>wording fix<commit_after>#include <test/unit/math/test_ad.hpp>
#include <cmath>
#include <complex>
#include <vector>
#include <type_traits>

TEST(mixFun, absBasics) {
  using stan::math::abs;
  int a = abs(1);

  double b = abs(-2.3);

  Eigen::Matrix<double, -1, -1> x(2, 3);
  x << 1, 2, 3, 4, 5, 6;
  Eigen::Matrix<double, -1, -1> y = abs(x);

  std::vector<int> u{1, 2, 3, 4};
  std::vector<int> v = abs(u);
}

template <typename T1, typename T2>
using is_complex_and_base_ret = stan::bool_constant<
(!stan::is_complex<stan::scalar_type_t<std::decay_t<T1>>>::value)
 || (stan::is_complex<stan::scalar_type_t<std::decay_t<T1>>>::value &&
     !stan::is_complex<stan::scalar_type_t<std::decay_t<T2>>>::value)>;
TEST(mixFun, abs) {
  auto f = [](const auto& x) {
    auto xx = stan::math::abs(x);
    static_assert(is_complex_and_base_ret<decltype(x), decltype(xx)>::value, "if x is complex<T> the return must not be T!");
    return xx;
  };
  stan::test::expect_common_nonzero_unary(f);
  // 0 (no derivative at 0)
  stan::test::expect_value(f, 0);
  stan::test::expect_value(f, 0.0);

  stan::test::expect_ad(f, -3);
  stan::test::expect_ad(f, -2);
  stan::test::expect_ad(f, 2);

  stan::test::expect_ad(f, -17.3);
  stan::test::expect_ad(f, -0.68);
  stan::test::expect_ad(f, 0.68);
  stan::test::expect_ad(f, 2.0);
  stan::test::expect_ad(f, 4.0);

  // complex tests
  for (double re : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
    for (double im : std::vector<double>{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {
      stan::test::expect_ad(f, std::complex<double>(re, im));
    }
  }

  // vector<double>
  using svd_t = std::vector<double>;
  stan::test::expect_ad(f, svd_t{});
  stan::test::expect_ad(f, svd_t{1.0});
  stan::test::expect_ad(f, svd_t{1.9, -2.3});

  // vector<vector<double>>
  using svvd_t = std::vector<svd_t>;
  stan::test::expect_ad(f, svvd_t{});
  stan::test::expect_ad(f, svvd_t{svd_t{}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9, 4.8}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9}, svd_t{-13.987}});
  stan::test::expect_ad(f, svvd_t{svd_t{1.9, -2.7}, svd_t{-13.987, 8.8}});

  // vector<complex<double>>
  using c_t = std::complex<double>;
  using svc_t = std::vector<c_t>;
  stan::test::expect_ad(f, svc_t{});
  stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}});
  stan::test::expect_ad(f, svc_t{c_t{1.0, -1.9}, c_t{-9.3, -128.987654}});

  // vector<vector<complex<double>>>
  using svvc_t = std::vector<svc_t>;
  stan::test::expect_ad(f, svvc_t{});
  stan::test::expect_ad(f, svvc_t{{}});
  stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}}});
  stan::test::expect_ad(f, svvc_t{svc_t{c_t{1.2, -2.3}, c_t{-32.8, 1}},
                                  svc_t{c_t{9.3, 9.4}, c_t{182, -95}}});

  // VectorXd
  using v_t = Eigen::VectorXd;
  v_t a0(0);
  stan::test::expect_ad(f, a0);
  stan::test::expect_ad_matvar(f, a0);
  v_t a1(1);
  a1 << 1.9;
  stan::test::expect_ad(f, a1);
  stan::test::expect_ad_matvar(f, a1);
  v_t a2(2);
  a2 << 1.9, -2.3;
  stan::test::expect_ad(f, a2);
  stan::test::expect_ad_matvar(f, a2);

  // RowVectorXd
  using rv_t = Eigen::RowVectorXd;
  rv_t b0(0);
  stan::test::expect_ad(f, b0);
  stan::test::expect_ad_matvar(f, b0);
  rv_t b1(1);
  b1 << 1.9;
  stan::test::expect_ad(f, b1);
  stan::test::expect_ad_matvar(f, b1);
  rv_t b2(2);
  b2 << 1.9, -2.3;
  stan::test::expect_ad(f, b2);
  stan::test::expect_ad_matvar(f, b2);

  // MatrixXd
  using m_t = Eigen::MatrixXd;
  m_t c0(0, 0);
  stan::test::expect_ad(f, c0);
  stan::test::expect_ad_matvar(f, c0);
  m_t c0i(0, 2);
  stan::test::expect_ad(f, c0i);
  stan::test::expect_ad_matvar(f, c0i);
  m_t c0ii(2, 0);
  stan::test::expect_ad(f, c0ii);
  stan::test::expect_ad_matvar(f, c0ii);
  m_t c2(2, 1);
  c2 << 1.3, -2.9;
  stan::test::expect_ad(f, c2);
  stan::test::expect_ad_matvar(f, c2);
  m_t c6(3, 2);
  c6 << 1.3, 2.9, -13.456, 1.898, -0.01, 1.87e21;
  stan::test::expect_ad(f, c6);
  stan::test::expect_ad_matvar(f, c6);

  // vector<VectorXd>
  using av_t = std::vector<Eigen::VectorXd>;
  av_t d0;
  stan::test::expect_ad(f, d0);
  stan::test::expect_ad_matvar(f, d0);
  av_t d1{a0};
  stan::test::expect_ad(f, d1);
  stan::test::expect_ad_matvar(f, d1);
  av_t d2{a1, a2};
  stan::test::expect_ad(f, d2);
  stan::test::expect_ad_matvar(f, d2);

  // vector<RowVectorXd>
  using arv_t = std::vector<Eigen::RowVectorXd>;
  arv_t e0;
  stan::test::expect_ad(f, e0);
  stan::test::expect_ad_matvar(f, e0);
  arv_t e1{b0};
  stan::test::expect_ad(f, e1);
  stan::test::expect_ad_matvar(f, e1);
  arv_t e2{b1, b2};
  stan::test::expect_ad(f, e2);
  stan::test::expect_ad_matvar(f, e2);

  // vector<MatrixXd>
  using am_t = std::vector<Eigen::MatrixXd>;
  am_t g0;
  stan::test::expect_ad(f, g0);
  stan::test::expect_ad_matvar(f, g0);
  am_t g1{c0};
  stan::test::expect_ad(f, g1);
  stan::test::expect_ad_matvar(f, g1);
  am_t g2{c2, c6};
  stan::test::expect_ad(f, g2);
  stan::test::expect_ad_matvar(f, g2);

  // VectorXcd
  using vc_t = Eigen::VectorXcd;
  vc_t h0(0);
  stan::test::expect_ad(f, h0);
  vc_t h1(1);
  h1 << c_t{1.9, -1.8};
  stan::test::expect_ad(f, h1);
  vc_t h2(2);
  h2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
  stan::test::expect_ad(f, h2);

  // RowVectorXcd
  using rvc_t = Eigen::RowVectorXcd;
  rvc_t j0(0);
  stan::test::expect_ad(f, j0);
  rvc_t j1(1);
  j1 << c_t{1.9, -1.8};
  stan::test::expect_ad(f, j1);
  rvc_t j2(2);
  j2 << c_t{1.9, -1.8}, c_t{-128.7, 1.3};
  stan::test::expect_ad(f, j2);

  // MatrixXcd
  using mc_t = Eigen::MatrixXcd;
  mc_t k0(0, 0);
  stan::test::expect_ad(f, k0);
  mc_t k2(1, 2);
  k2 << c_t{1.9, -1.8}, c_t{128.735, 128.734};
  stan::test::expect_ad(f, k2);
  mc_t k6(3, 2);
  k6 << c_t{1.9, -1.8}, c_t{-128.7, 1.3}, c_t{1, 2}, c_t{0.3, -0.5},
      c_t{-13, 125.7}, c_t{-12.5, -10.5};
  stan::test::expect_ad(f, k6);

  // vector<VectorXcd>
  using avc_t = std::vector<vc_t>;
  avc_t m0;
  stan::test::expect_ad(f, m0);
  avc_t m1{h1};
  stan::test::expect_ad(f, m1);
  avc_t m2{h1, h2};
  stan::test::expect_ad(f, m2);

  // vector<RowVectorXcd>
  using arvc_t = std::vector<rvc_t>;
  arvc_t p0(0);
  stan::test::expect_ad(f, p0);
  arvc_t p1{j1};
  stan::test::expect_ad(f, p1);
  arvc_t p2{j1, j2};
  stan::test::expect_ad(f, p2);

  // vector<MatrixXcd>
  using amc_t = std::vector<mc_t>;
  amc_t q0;
  stan::test::expect_ad(f, q0);
  amc_t q1{k2};
  stan::test::expect_ad(f, q1);
  amc_t q2{k2, k6};
  stan::test::expect_ad(f, q2);
}
TEST(mixFun, absReturnType) {
  // validate return types not overpromoted to complex by assignability
  std::complex<stan::math::var> a = 3;
  stan::math::var b = abs(a);

  std::complex<stan::math::fvar<double>> c = 3;
  stan::math::fvar<double> d = abs(c);
  SUCCEED();
}

TEST(mathMixMatFun, abs_varmat) {
  using stan::math::vec_concat;
  using stan::test::expect_ad_vector_matvar;
  using stan::test::internal::common_nonzero_args;
  auto f = [](const auto& x1) {
    using stan::math::abs;
    return abs(x1);
  };
  std::vector<double> com_args = common_nonzero_args();
  std::vector<double> args{-3, 2, -0.68, 1};
  auto all_args = vec_concat(com_args, args);
  Eigen::VectorXd A(all_args.size());
  for (int i = 0; i < all_args.size(); ++i) {
    A(i) = all_args[i];
  }
  expect_ad_vector_matvar(f, A);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * 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 <stdlib.h>
#include <sys/system_properties.h>
#include <sys/types.h>

#include "perfetto/base/logging.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/cts/utils.h"
#include "test/gtest_and_gmock.h"
#include "test/test_helper.h"

#include "protos/perfetto/config/profiling/perf_event_config.gen.h"
#include "protos/perfetto/trace/profiling/profile_common.gen.h"
#include "protos/perfetto/trace/profiling/profile_packet.gen.h"
#include "protos/perfetto/trace/trace_packet.gen.h"

namespace perfetto {
namespace {

// Skip these tests if the device in question doesn't have the necessary kernel
// LSM hooks in perf_event_open. This comes up when a device with an older
// kernel upgrades to R.
bool HasPerfLsmHooks() {
  char buf[PROP_VALUE_MAX + 1] = {};
  int ret = __system_property_get("sys.init.perf_lsm_hooks", buf);
  PERFETTO_CHECK(ret >= 0);
  return std::string(buf) == "1";
}

std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
  base::TestTaskRunner task_runner;

  // (re)start the target app's main activity
  if (IsAppRunning(app_name)) {
    StopApp(app_name, "old.app.stopped", &task_runner);
    task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/);
  }
  StartAppActivity(app_name, "BusyWaitActivity", "target.app.running",
                   &task_runner,
                   /*delay_ms=*/100);
  task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/);

  // set up tracing
  TestHelper helper(&task_runner);
  helper.ConnectConsumer();
  helper.WaitForConsumerConnect();

  TraceConfig trace_config;
  trace_config.add_buffers()->set_size_kb(20 * 1024);
  trace_config.set_duration_ms(3000);
  trace_config.set_data_source_stop_timeout_ms(8000);

  auto* ds_config = trace_config.add_data_sources()->mutable_config();
  ds_config->set_name("linux.perf");
  ds_config->set_target_buffer(0);

  protos::gen::PerfEventConfig perf_config;

  perf_config.set_all_cpus(true);
  perf_config.set_sampling_frequency(10);  // Hz
  ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());

  // start tracing
  helper.StartTracing(trace_config);
  helper.WaitForTracingDisabled(15000 /*ms*/);
  helper.ReadData();
  helper.WaitForReadData();

  return helper.trace();
}

void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
                                  int target_pid) {
  ASSERT_GT(packets.size(), 0u);

  int total_perf_packets = 0;
  int total_samples = 0;
  int target_samples = 0;
  for (const auto& packet : packets) {
    if (!packet.has_perf_sample())
      continue;

    total_perf_packets++;
    EXPECT_GT(packet.timestamp(), 0u) << "all packets should have a timestamp";
    const auto& sample = packet.perf_sample();
    if (sample.has_kernel_records_lost())
      continue;
    if (sample.has_sample_skipped_reason())
      continue;

    total_samples++;
    EXPECT_GT(sample.tid(), 0u);
    EXPECT_GT(sample.callstack_iid(), 0u);

    if (sample.pid() == static_cast<uint32_t>(target_pid))
      target_samples++;
  }

  EXPECT_GT(target_samples, 0) << "packets.size(): " << packets.size()
                               << ", total_perf_packets: " << total_perf_packets
                               << ", total_samples: " << total_samples << "\n";
}

void AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,
                          int target_pid) {
  // The process can still be sampled, but the stacks should be discarded
  // without unwinding.
  for (const auto& packet : packets) {
    if (packet.perf_sample().pid() == static_cast<uint32_t>(target_pid)) {
      EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);
      EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());
    }
  }
}

TEST(TracedPerfCtsTest, SystemWideDebuggableApp) {
  if (!HasPerfLsmHooks())
    return;

  std::string app_name = "android.perfetto.cts.app.debuggable";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  AssertHasSampledStacksForPid(packets, app_pid);
  StopApp(app_name);
}

TEST(TracedPerfCtsTest, SystemWideProfileableApp) {
  if (!HasPerfLsmHooks())
    return;

  std::string app_name = "android.perfetto.cts.app.profileable";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  AssertHasSampledStacksForPid(packets, app_pid);
  StopApp(app_name);
}

TEST(TracedPerfCtsTest, SystemWideReleaseApp) {
  if (!HasPerfLsmHooks())
    return;

  std::string app_name = "android.perfetto.cts.app.release";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  if (IsDebuggableBuild())
    AssertHasSampledStacksForPid(packets, app_pid);
  else
    AssertNoStacksForPid(packets, app_pid);

  StopApp(app_name);
}

}  // namespace
}  // namespace perfetto
<commit_msg>Use GTEST_SKIP when skipping perf cts tests<commit_after>/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * 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 <stdlib.h>
#include <sys/system_properties.h>
#include <sys/types.h>

#include "perfetto/base/logging.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/cts/utils.h"
#include "test/gtest_and_gmock.h"
#include "test/test_helper.h"

#include "protos/perfetto/config/profiling/perf_event_config.gen.h"
#include "protos/perfetto/trace/profiling/profile_common.gen.h"
#include "protos/perfetto/trace/profiling/profile_packet.gen.h"
#include "protos/perfetto/trace/trace_packet.gen.h"

namespace perfetto {
namespace {

// Skip these tests if the device in question doesn't have the necessary kernel
// LSM hooks in perf_event_open. This comes up when a device with an older
// kernel upgrades to R.
bool HasPerfLsmHooks() {
  char buf[PROP_VALUE_MAX + 1] = {};
  int ret = __system_property_get("sys.init.perf_lsm_hooks", buf);
  PERFETTO_CHECK(ret >= 0);
  return std::string(buf) == "1";
}

std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
  base::TestTaskRunner task_runner;

  // (re)start the target app's main activity
  if (IsAppRunning(app_name)) {
    StopApp(app_name, "old.app.stopped", &task_runner);
    task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/);
  }
  StartAppActivity(app_name, "BusyWaitActivity", "target.app.running",
                   &task_runner,
                   /*delay_ms=*/100);
  task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/);

  // set up tracing
  TestHelper helper(&task_runner);
  helper.ConnectConsumer();
  helper.WaitForConsumerConnect();

  TraceConfig trace_config;
  trace_config.add_buffers()->set_size_kb(20 * 1024);
  trace_config.set_duration_ms(3000);
  trace_config.set_data_source_stop_timeout_ms(8000);

  auto* ds_config = trace_config.add_data_sources()->mutable_config();
  ds_config->set_name("linux.perf");
  ds_config->set_target_buffer(0);

  protos::gen::PerfEventConfig perf_config;

  perf_config.set_all_cpus(true);
  perf_config.set_sampling_frequency(10);  // Hz
  ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());

  // start tracing
  helper.StartTracing(trace_config);
  helper.WaitForTracingDisabled(15000 /*ms*/);
  helper.ReadData();
  helper.WaitForReadData();

  return helper.trace();
}

void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
                                  int target_pid) {
  ASSERT_GT(packets.size(), 0u);

  int total_perf_packets = 0;
  int total_samples = 0;
  int target_samples = 0;
  for (const auto& packet : packets) {
    if (!packet.has_perf_sample())
      continue;

    total_perf_packets++;
    EXPECT_GT(packet.timestamp(), 0u) << "all packets should have a timestamp";
    const auto& sample = packet.perf_sample();
    if (sample.has_kernel_records_lost())
      continue;
    if (sample.has_sample_skipped_reason())
      continue;

    total_samples++;
    EXPECT_GT(sample.tid(), 0u);
    EXPECT_GT(sample.callstack_iid(), 0u);

    if (sample.pid() == static_cast<uint32_t>(target_pid))
      target_samples++;
  }

  EXPECT_GT(target_samples, 0) << "packets.size(): " << packets.size()
                               << ", total_perf_packets: " << total_perf_packets
                               << ", total_samples: " << total_samples << "\n";
}

void AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,
                          int target_pid) {
  // The process can still be sampled, but the stacks should be discarded
  // without unwinding.
  for (const auto& packet : packets) {
    if (packet.perf_sample().pid() == static_cast<uint32_t>(target_pid)) {
      EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);
      EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());
    }
  }
}

TEST(TracedPerfCtsTest, SystemWideDebuggableApp) {
  if (!HasPerfLsmHooks())
    GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";

  std::string app_name = "android.perfetto.cts.app.debuggable";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  AssertHasSampledStacksForPid(packets, app_pid);
  StopApp(app_name);
}

TEST(TracedPerfCtsTest, SystemWideProfileableApp) {
  if (!HasPerfLsmHooks())
    GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";

  std::string app_name = "android.perfetto.cts.app.profileable";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  AssertHasSampledStacksForPid(packets, app_pid);
  StopApp(app_name);
}

TEST(TracedPerfCtsTest, SystemWideReleaseApp) {
  if (!HasPerfLsmHooks())
    GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";

  std::string app_name = "android.perfetto.cts.app.release";
  const auto& packets = ProfileSystemWide(app_name);
  int app_pid = PidForProcessName(app_name);
  ASSERT_GT(app_pid, 0) << "failed to find pid for target process";

  if (IsDebuggableBuild())
    AssertHasSampledStacksForPid(packets, app_pid);
  else
    AssertNoStacksForPid(packets, app_pid);

  StopApp(app_name);
}

}  // namespace
}  // namespace perfetto
<|endoftext|>


<commit_before>#include "FanController.h"

FanController::FanController(Servo _yaw, Servo _pitch):
  yaw(_yaw),
  pitch(_pitch){

  }

void FanController::initialize(){

}

void FanController::up(){

}

void FanController::down(){

}

void FanController::left(){

}

void FanController::right(){

}

<commit_msg>this is not for the robot<commit_after>#include "FanController.h"

FanController::FanController(Servo _yaw, Servo _pitch):
  yaw(_yaw),
  pitch(_pitch){

  }

void FanController::initialize(){

}

int FanController::reportPitchAngle(){

}

int FanController::reportYawAngle(){

}

float FanController::getCandleDistance(){

}

boolean FanController::findCandle(){

}

void FanController::up(){

}

void FanController::down(){

}

void FanController::left(){

}

void FanController::right(){

}

<|endoftext|>


<commit_before>#include "kwm.h"
#include <pthread.h>

kwm_code KWMCode;
export_table ExportTable;
std::string KwmFilePath;
std::string HotkeySOFullFilePath;

std::vector<screen_info> DisplayLst;
std::vector<window_info> WindowLst;
std::map<int, std::vector<int> > SpacesOfWindow;
int CurrentSpace = 0;
int PrevSpace = -1;

ProcessSerialNumber FocusedPSN;
AXUIElementRef FocusedWindowRef;
window_info *FocusedWindow;
int MarkedWindowID = -1;

uint32_t MaxDisplayCount = 5;
uint32_t ActiveDisplaysCount;
CGDirectDisplayID ActiveDisplays[5];

pthread_t BackgroundThread;

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    switch(Type)
    {
        case kCGEventKeyDown:
        {
            CGEventFlags Flags = CGEventGetFlags(Event);
            bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;
            bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;
            bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;
            CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);

            std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
            if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
            {
                DEBUG("Reloading hotkeys.so")
                UnloadKwmCode(&KWMCode);
                KWMCode = LoadKwmCode();
            }

            if(KWMCode.IsValid)
            {
                // Toggle keytap on | off
                if(KWMCode.KWMHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return NULL;

                // capture custom hotkeys
                if(KWMCode.CustomHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return NULL;

                // Let system hotkeys pass through as normal
                if(KWMCode.SystemHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return Event;
            }

            if(ExportTable.KwmFocusMode == FocusFollowsMouse)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&FocusedPSN, Event);
                return NULL;
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(ExportTable.KwmFocusMode != FocusDisabled)
            {
                FocusWindowBelowCursor();
            }
        } break;
    }

    return Event;
}

kwm_code LoadKwmCode()
{
    kwm_code Code = {};

    Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
    Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(),  RTLD_LAZY);
    if(Code.KwmHotkeySO)
    {
        Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
        Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "SystemHotkeyCommands");
        Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "CustomHotkeyCommands");
    }
    else
    {
        DEBUG("LoadKwmCode() Could not open '" << HotkeySOFullFilePath << "'")
    }

    Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands);
    return Code;
}

void UnloadKwmCode(kwm_code *Code)
{
    if(Code->KwmHotkeySO)
    {
        dlclose(Code->KwmHotkeySO);
    }

    Code->HotkeySOFileTime = "";
    Code->KWMHotkeyCommands = 0;
    Code->SystemHotkeyCommands = 0;
    Code->CustomHotkeyCommands = 0;
    Code->IsValid = 0;
}

std::string KwmGetFileTime(const char *File)
{
    struct stat attr;
    stat(File, &attr);

    return ctime(&attr.st_mtime);
}

void BuildExportTable()
{
    ExportTable.KwmFilePath = KwmFilePath;
    ExportTable.KwmFocusMode = FocusAutoraise;;
    ExportTable.FocusedWindowRef = FocusedWindowRef;
    ExportTable.FocusedWindow = FocusedWindow;

    ExportTable.FocusWindowBelowCursor = &FocusWindowBelowCursor;
    ExportTable.SetWindowDimensions = &SetWindowDimensions;
    ExportTable.ToggleFocusedWindowFullscreen = &ToggleFocusedWindowFullscreen;
    ExportTable.SwapFocusedWindowWithNearest = &SwapFocusedWindowWithNearest;
    ExportTable.ShiftWindowFocus = &ShiftWindowFocus;
    ExportTable.CycleFocusedWindowDisplay = &CycleFocusedWindowDisplay;
    ExportTable.AddWindowToTree = &AddWindowToTree;
    ExportTable.RemoveWindowFromTree = &RemoveWindowFromTree;
    ExportTable.MarkWindowContainer = &MarkWindowContainer;
    ExportTable.KwmRestart = &KwmRestart;
}

void KwmRestart()
{
    DEBUG("KWM Restarting..")
    const char **ExecArgs = new const char*[2];
    ExecArgs[0] = "kwm";
    ExecArgs[1] = NULL;
    std::string KwmBinPath = KwmFilePath + "/kwm";
    execv(KwmBinPath.c_str(), (char**)ExecArgs);
}

void * KwmWindowMonitor(void*)
{
    while(1)
    {
        DEBUG("KwmWindowMonitor()")
        UpdateWindowTree();
        usleep(200000);
    }
}

void KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Could not access OSX Accessibility!");

    KwmFilePath = getcwd(NULL, 0);
    HotkeySOFullFilePath = KwmFilePath + "/hotkeys.so";

    KWMCode = LoadKwmCode();
    BuildExportTable();

    GetActiveSpaces();
    GetActiveDisplays();

    UpdateWindowTree();
    FocusWindowBelowCursor();

    pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}

bool CheckPrivileges()
{
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
            Keys, Values, sizeof(Keys) / sizeof(*Keys),
            &kCFCopyStringDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks);

    return AXIsProcessTrustedWithOptions(Options);
}

void Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

int main(int argc, char **argv)
{
    KwmInit();

    CFMachPortRef EventTap;
    CGEventMask EventMask;
    CFRunLoopSourceRef RunLoopSource;

    EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));
    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);

    if(!EventTap || !CGEventTapIsEnabled(EventTap))
        Fatal("ERROR: Could not create event-tap!");

    RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(EventTap, true);
    CFRunLoopRun();
    return 0;
}
<commit_msg>removed debug print to prevent random useless spam<commit_after>#include "kwm.h"
#include <pthread.h>

kwm_code KWMCode;
export_table ExportTable;
std::string KwmFilePath;
std::string HotkeySOFullFilePath;

std::vector<screen_info> DisplayLst;
std::vector<window_info> WindowLst;
std::map<int, std::vector<int> > SpacesOfWindow;
int CurrentSpace = 0;
int PrevSpace = -1;

ProcessSerialNumber FocusedPSN;
AXUIElementRef FocusedWindowRef;
window_info *FocusedWindow;
int MarkedWindowID = -1;

uint32_t MaxDisplayCount = 5;
uint32_t ActiveDisplaysCount;
CGDirectDisplayID ActiveDisplays[5];

pthread_t BackgroundThread;

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    switch(Type)
    {
        case kCGEventKeyDown:
        {
            CGEventFlags Flags = CGEventGetFlags(Event);
            bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;
            bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;
            bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;
            CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);

            std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
            if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
            {
                DEBUG("Reloading hotkeys.so")
                UnloadKwmCode(&KWMCode);
                KWMCode = LoadKwmCode();
            }

            if(KWMCode.IsValid)
            {
                // Toggle keytap on | off
                if(KWMCode.KWMHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return NULL;

                // capture custom hotkeys
                if(KWMCode.CustomHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return NULL;

                // Let system hotkeys pass through as normal
                if(KWMCode.SystemHotkeyCommands(&ExportTable, CmdKey, CtrlKey, AltKey, Keycode))
                    return Event;
            }

            if(ExportTable.KwmFocusMode == FocusFollowsMouse)
            {
                CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
                CGEventPostToPSN(&FocusedPSN, Event);
                return NULL;
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(ExportTable.KwmFocusMode != FocusDisabled)
            {
                FocusWindowBelowCursor();
            }
        } break;
    }

    return Event;
}

kwm_code LoadKwmCode()
{
    kwm_code Code = {};

    Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
    Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(),  RTLD_LAZY);
    if(Code.KwmHotkeySO)
    {
        Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
        Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "SystemHotkeyCommands");
        Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "CustomHotkeyCommands");
    }
    else
    {
        DEBUG("LoadKwmCode() Could not open '" << HotkeySOFullFilePath << "'")
    }

    Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands);
    return Code;
}

void UnloadKwmCode(kwm_code *Code)
{
    if(Code->KwmHotkeySO)
    {
        dlclose(Code->KwmHotkeySO);
    }

    Code->HotkeySOFileTime = "";
    Code->KWMHotkeyCommands = 0;
    Code->SystemHotkeyCommands = 0;
    Code->CustomHotkeyCommands = 0;
    Code->IsValid = 0;
}

std::string KwmGetFileTime(const char *File)
{
    struct stat attr;
    stat(File, &attr);

    return ctime(&attr.st_mtime);
}

void BuildExportTable()
{
    ExportTable.KwmFilePath = KwmFilePath;
    ExportTable.KwmFocusMode = FocusAutoraise;;
    ExportTable.FocusedWindowRef = FocusedWindowRef;
    ExportTable.FocusedWindow = FocusedWindow;

    ExportTable.FocusWindowBelowCursor = &FocusWindowBelowCursor;
    ExportTable.SetWindowDimensions = &SetWindowDimensions;
    ExportTable.ToggleFocusedWindowFullscreen = &ToggleFocusedWindowFullscreen;
    ExportTable.SwapFocusedWindowWithNearest = &SwapFocusedWindowWithNearest;
    ExportTable.ShiftWindowFocus = &ShiftWindowFocus;
    ExportTable.CycleFocusedWindowDisplay = &CycleFocusedWindowDisplay;
    ExportTable.AddWindowToTree = &AddWindowToTree;
    ExportTable.RemoveWindowFromTree = &RemoveWindowFromTree;
    ExportTable.MarkWindowContainer = &MarkWindowContainer;
    ExportTable.KwmRestart = &KwmRestart;
}

void KwmRestart()
{
    DEBUG("KWM Restarting..")
    const char **ExecArgs = new const char*[2];
    ExecArgs[0] = "kwm";
    ExecArgs[1] = NULL;
    std::string KwmBinPath = KwmFilePath + "/kwm";
    execv(KwmBinPath.c_str(), (char**)ExecArgs);
}

void * KwmWindowMonitor(void*)
{
    while(1)
    {
        //DEBUG("KwmWindowMonitor()")
        UpdateWindowTree();
        usleep(200000);
    }
}

void KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Could not access OSX Accessibility!");

    KwmFilePath = getcwd(NULL, 0);
    HotkeySOFullFilePath = KwmFilePath + "/hotkeys.so";

    KWMCode = LoadKwmCode();
    BuildExportTable();

    GetActiveSpaces();
    GetActiveDisplays();

    UpdateWindowTree();
    FocusWindowBelowCursor();

    pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}

bool CheckPrivileges()
{
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
            Keys, Values, sizeof(Keys) / sizeof(*Keys),
            &kCFCopyStringDictionaryKeyCallBacks,
            &kCFTypeDictionaryValueCallBacks);

    return AXIsProcessTrustedWithOptions(Options);
}

void Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

int main(int argc, char **argv)
{
    KwmInit();

    CFMachPortRef EventTap;
    CGEventMask EventMask;
    CFRunLoopSourceRef RunLoopSource;

    EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));
    EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);

    if(!EventTap || !CGEventTapIsEnabled(EventTap))
        Fatal("ERROR: Could not create event-tap!");

    RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(EventTap, true);
    CFRunLoopRun();
    return 0;
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <unordered_set>

// with these settings it works up to size 16
typedef uint32_t pos_t;         // increase the size of this for larger boards
constexpr pos_t CELL_WIDTH = 2; // number of bits per cell

constexpr pos_t CELL_MAX = (1 << CELL_WIDTH) - 1;          // max value of a cell
constexpr pos_t MAX_SIZE = sizeof(pos_t) * 8 / CELL_WIDTH; // max board size

enum Cell : pos_t { EMPTY = 0, BLACK = 1, WHITE = 2 };

struct Board {
    pos_t board = 0;
    inline Cell get(const pos_t pos) const { return Cell(board >> pos * CELL_WIDTH & CELL_MAX); }
    inline void set(const pos_t pos, const Cell color) {
        board ^= board & CELL_MAX << pos * CELL_WIDTH ^ color << pos * CELL_WIDTH;
    }
    bool operator==(const Board o) const { return o.board == board; }
};

struct BoardHasher {
    size_t operator()(const Board b) const { return b.board; }
};

struct History {
    std::unordered_set<Board, BoardHasher> states;
    void add(const Board s) { states.insert(s); }
    bool check(const Board s) const { return states.find(s) != states.end(); }
};
<commit_msg>Add basic state and move structs<commit_after>#include <cstdint>
#include <unordered_set>

// with these settings it works up to size 16
typedef uint32_t pos_t;         // increase the size of this for larger boards
constexpr pos_t CELL_WIDTH = 2; // number of bits per cell

constexpr pos_t CELL_MAX = (1 << CELL_WIDTH) - 1;          // max value of a cell
constexpr pos_t MAX_SIZE = sizeof(pos_t) * 8 / CELL_WIDTH; // max board size

enum Cell : pos_t { EMPTY = 0, BLACK = 1, WHITE = 2 };

struct Board {
    pos_t board = 0;
    inline Cell get(const pos_t pos) const { return Cell(board >> pos * CELL_WIDTH & CELL_MAX); }
    inline void set(const pos_t pos, const Cell color) {
        board ^= board & CELL_MAX << pos * CELL_WIDTH ^ color << pos * CELL_WIDTH;
    }
    bool operator==(const Board o) const { return o.board == board; }
};

struct BoardHasher {
    size_t operator()(const Board b) const { return b.board; }
};

struct History {
    std::unordered_set<Board, BoardHasher> states;
    void add(const Board s) { states.insert(s); }
    bool check(const Board s) const { return states.find(s) != states.end(); }
};

struct State {
    Board board;
    History history;
    enum GameState { ALIVE, PASS, GAME_OVER } gameState;
};

struct Move {
    Move(Cell color, pos_t position, bool pass) : color(color), position(position), pass(pass) {}
    Cell color;
    pos_t position;
    bool pass;
};
<|endoftext|>