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

#include <d3d10.h>
#include <d3dx10.h>

#include "../DataStream.h"
#include "../Utilities.h"

#include "Direct3D10Exception.h"

#include "Device10.h"
#include "Resource10.h"
#include "Buffer.h"
#include "Texture1D.h"
#include "Texture2D.h"
#include "Texture3D.h"

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Globalization;

namespace SlimDX
{
namespace Direct3D10
{
	SlimDX::DXGI::Surface^ Resource::AsSurface()
	{
		IDXGISurface* unknown = 0;
		GUID guid = Utilities::GetNativeGuidForType( this->GetType() );
		HRESULT hr = InternalPointer->QueryInterface(guid, reinterpret_cast<void**>(&unknown));
		if(RECORD_D3D10(hr).IsFailure)
			return nullptr;

		unknown->Release();

		SlimDX::DXGI::Surface^ result;
		ComObject^ object = ObjectTable::Find(IntPtr(unknown));
		result = SlimDX::DXGI::Surface::FromPointer(unknown);

		if(object == nullptr) {
			ObjectTable::Remove(result);
		}

		return result;
	}

	generic< class T > where T : Resource, ref class
	T Resource::FromSwapChain( SlimDX::DXGI::SwapChain^ swapChain, int index )
	{
		IUnknown* unknown = 0;
		GUID guid = Utilities::GetNativeGuidForType( T::typeid );
		RECORD_D3D10( swapChain->InternalPointer->GetBuffer( index, guid, reinterpret_cast<void**>( &unknown ) ) );
		if( Result::Last.IsFailure )
			return T();

		BindingFlags flags = BindingFlags::Static | BindingFlags::InvokeMethod | BindingFlags::NonPublic;
		array<System::Object^>^ args = gcnew array<System::Object^>( 1 );
		args[ 0 ] = IntPtr( unknown );

		// Trying to invoke "FromPointer" directly will choose the IntPtr overload since it's more
		// cumbersome to pass a native pointer as an argument here. The IntPtr overload is intended
		// to be the user-pointer overload, however, which isn't what we want; thus the thunk.
		T result = safe_cast<T>( T::typeid->InvokeMember( "FromPointerReflectionThunk", flags, nullptr, nullptr, args, CultureInfo::InvariantCulture ) );
		return result;
	}

	Resource^ Resource::FromPointer( System::IntPtr pointer )
	{
		if( pointer == System::IntPtr::Zero )
			throw gcnew System::ArgumentNullException( "pointer" );

		Resource^ tableEntry = safe_cast<Resource^>( SlimDX::ObjectTable::Find( static_cast<System::IntPtr>( pointer ) ) );
		if( tableEntry != nullptr )
			return tableEntry;

		void* result = 0;
		IUnknown* unknown = static_cast<IUnknown*>( pointer.ToPointer() );
		HRESULT hr = unknown->QueryInterface(IID_ID3D10Resource, &result);
		if( FAILED( hr ) )
			throw gcnew InvalidCastException( "Failed to QueryInterface on user-supplied pointer." );

		// find out what this thing actually is
		ID3D10Resource* resource = static_cast<ID3D10Resource*>( unknown );
		D3D10_RESOURCE_DIMENSION type;
		resource->GetType( &type );
		resource->Release();

		// chain to the correct ctor (not the fastest way to do this, but good enough for now)
		switch(type)
		{
		case D3D10_RESOURCE_DIMENSION_BUFFER:
			return Buffer::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
			return Texture1D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
			return Texture2D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
			return Texture3D::FromPointer( pointer );

		default:
			throw gcnew InvalidCastException( "Unrecognized resource type." );
		}
	}

	Resource^ Resource::FromPointer( ID3D10Resource* pointer )
	{
		if( pointer == NULL )
			return nullptr;

		Resource^ tableEntry = safe_cast<Resource^>( SlimDX::ObjectTable::Find( static_cast<System::IntPtr>( pointer ) ) );
		if( tableEntry != nullptr )
		{
			pointer->Release();
			return tableEntry;
		}

		//not in the table, find out what this thing actually is
		D3D10_RESOURCE_DIMENSION type;
		pointer->GetType( &type );

		// chain to the correct ctor (not the fastest way to do this, but good enough for now)
		switch(type)
		{
		case D3D10_RESOURCE_DIMENSION_BUFFER:
			return Buffer::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
			return Texture1D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
			return Texture2D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
			return Texture3D::FromPointer( pointer );

		default:
			throw gcnew InvalidCastException( "Unrecognized resource type." );
		}
	}

	DXGI::ResourcePriority Resource::EvictionPriority::get()
	{
		return static_cast<DXGI::ResourcePriority>( InternalPointer->GetEvictionPriority() );
	}

	void Resource::EvictionPriority::set( DXGI::ResourcePriority value )
	{
		InternalPointer->SetEvictionPriority( static_cast<UINT>( value ) );
	}

	ResourceDimension Resource::Dimension::get()
	{
		D3D10_RESOURCE_DIMENSION type;
		InternalPointer->GetType(&type);
		return static_cast<ResourceDimension>( type );
	}

	Result Resource::LoadTextureFromTexture(Resource^ source, Resource^ destination, TextureLoadInformation loadInformation)
	{
		HRESULT hr = D3DX10LoadTextureFromTexture(source->InternalPointer, reinterpret_cast<D3DX10_TEXTURE_LOAD_INFO*>(&loadInformation), destination->InternalPointer);
		return RECORD_D3D10(hr);
	}

	Result Resource::FilterTexture(Resource^ texture, int sourceLevel, FilterFlags mipFilter)
	{
		HRESULT hr = D3DX10FilterTexture(texture->InternalPointer, sourceLevel, static_cast<UINT>(mipFilter));
		return RECORD_D3D10(hr);
	}

	int Resource::CalculateSubresourceIndex( int mipSlice, int arraySlice, int mipLevels )
	{
		return D3D10CalcSubresource( static_cast<UINT>( mipSlice ), static_cast<UINT>( arraySlice ), static_cast<UINT>( mipLevels ) );
	}

	int Resource::GetMipSize( int mipSlice, int baseSliceSize )
	{
		float size = static_cast<float>( baseSliceSize );

		while( mipSlice > 0 )
		{
			size = std::floorf(size / 2.0f);
			--mipSlice;
		}

		return (static_cast< int >(size));
	}

	ID3D10Resource* Resource::ConstructFromFile( SlimDX::Direct3D10::Device^ device, String^ fileName, D3DX10_IMAGE_LOAD_INFO* info )
	{
		ID3D10Resource* resource = 0;
		pin_ptr<const wchar_t> pinnedName = PtrToStringChars( fileName );
		HRESULT hr = D3DX10CreateTextureFromFile( device->InternalPointer, pinnedName, info, 0, &resource, 0 );
		RECORD_D3D10( hr );

		return resource;
	}

	ID3D10Resource* Resource::ConstructFromMemory( SlimDX::Direct3D10::Device^ device, array<Byte>^ memory, D3DX10_IMAGE_LOAD_INFO* info )
	{
		pin_ptr<unsigned char> pinnedMemory = &memory[0];

		ID3D10Resource* resource = 0;
		HRESULT hr = D3DX10CreateTextureFromMemory( device->InternalPointer, pinnedMemory, memory->Length, info, 0, &resource, 0 );
		RECORD_D3D10( hr );

		return resource;
	}

	ID3D10Resource* Resource::ConstructFromStream( SlimDX::Direct3D10::Device^ device, Stream^ stream, int sizeInBytes, D3DX10_IMAGE_LOAD_INFO* info )
	{
		DataStream^ ds = nullptr;
		array<Byte>^ memory = SlimDX::Utilities::ReadStream( stream, sizeInBytes, &ds );

		if( memory == nullptr )
		{
			ID3D10Resource* resource = NULL;
			SIZE_T size = static_cast<SIZE_T>( ds->RemainingLength );
			HRESULT hr = D3DX10CreateTextureFromMemory( device->InternalPointer, ds->SeekToEnd(), size,
				info, NULL, &resource, NULL );
			RECORD_D3D10( hr );

			return resource;
		}

		return ConstructFromMemory( device, memory, info );
	}
}
}
<commit_msg>Added AsSurface to D3D10 Resource for getting a DXGI Surface from D3D10 resources.<commit_after>#include "stdafx.h"
/*
* Copyright (c) 2007-2010 SlimDX Group
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

#include <d3d10.h>
#include <d3dx10.h>

#include "../DataStream.h"
#include "../Utilities.h"

#include "Direct3D10Exception.h"

#include "Device10.h"
#include "Resource10.h"
#include "Buffer.h"
#include "Texture1D.h"
#include "Texture2D.h"
#include "Texture3D.h"

using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Globalization;

namespace SlimDX
{
namespace Direct3D10
{
	SlimDX::DXGI::Surface^ Resource::AsSurface()
	{
		IDXGISurface* unknown = 0;
		GUID guid = Utilities::GetNativeGuidForType( this->GetType() );
		HRESULT hr = InternalPointer->QueryInterface(guid, reinterpret_cast<void**>(&unknown));
		if(RECORD_D3D10(hr).IsFailure)
			return nullptr;

		unknown->Release();

		ObjectTable::Remove(this);
		SlimDX::DXGI::Surface^ result = gcnew SlimDX::DXGI::Surface(unknown, nullptr);
		ObjectTable::Remove(result);
		ObjectTable::Add(this, nullptr);

		return result;
	}

	generic< class T > where T : Resource, ref class
	T Resource::FromSwapChain( SlimDX::DXGI::SwapChain^ swapChain, int index )
	{
		IUnknown* unknown = 0;
		GUID guid = Utilities::GetNativeGuidForType( T::typeid );
		RECORD_D3D10( swapChain->InternalPointer->GetBuffer( index, guid, reinterpret_cast<void**>( &unknown ) ) );
		if( Result::Last.IsFailure )
			return T();

		BindingFlags flags = BindingFlags::Static | BindingFlags::InvokeMethod | BindingFlags::NonPublic;
		array<System::Object^>^ args = gcnew array<System::Object^>( 1 );
		args[ 0 ] = IntPtr( unknown );

		// Trying to invoke "FromPointer" directly will choose the IntPtr overload since it's more
		// cumbersome to pass a native pointer as an argument here. The IntPtr overload is intended
		// to be the user-pointer overload, however, which isn't what we want; thus the thunk.
		T result = safe_cast<T>( T::typeid->InvokeMember( "FromPointerReflectionThunk", flags, nullptr, nullptr, args, CultureInfo::InvariantCulture ) );
		return result;
	}

	Resource^ Resource::FromPointer( System::IntPtr pointer )
	{
		if( pointer == System::IntPtr::Zero )
			throw gcnew System::ArgumentNullException( "pointer" );

		Resource^ tableEntry = safe_cast<Resource^>( SlimDX::ObjectTable::Find( static_cast<System::IntPtr>( pointer ) ) );
		if( tableEntry != nullptr )
			return tableEntry;

		void* result = 0;
		IUnknown* unknown = static_cast<IUnknown*>( pointer.ToPointer() );
		HRESULT hr = unknown->QueryInterface(IID_ID3D10Resource, &result);
		if( FAILED( hr ) )
			throw gcnew InvalidCastException( "Failed to QueryInterface on user-supplied pointer." );

		// find out what this thing actually is
		ID3D10Resource* resource = static_cast<ID3D10Resource*>( unknown );
		D3D10_RESOURCE_DIMENSION type;
		resource->GetType( &type );
		resource->Release();

		// chain to the correct ctor (not the fastest way to do this, but good enough for now)
		switch(type)
		{
		case D3D10_RESOURCE_DIMENSION_BUFFER:
			return Buffer::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
			return Texture1D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
			return Texture2D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
			return Texture3D::FromPointer( pointer );

		default:
			throw gcnew InvalidCastException( "Unrecognized resource type." );
		}
	}

	Resource^ Resource::FromPointer( ID3D10Resource* pointer )
	{
		if( pointer == NULL )
			return nullptr;

		Resource^ tableEntry = safe_cast<Resource^>( SlimDX::ObjectTable::Find( static_cast<System::IntPtr>( pointer ) ) );
		if( tableEntry != nullptr )
		{
			pointer->Release();
			return tableEntry;
		}

		//not in the table, find out what this thing actually is
		D3D10_RESOURCE_DIMENSION type;
		pointer->GetType( &type );

		// chain to the correct ctor (not the fastest way to do this, but good enough for now)
		switch(type)
		{
		case D3D10_RESOURCE_DIMENSION_BUFFER:
			return Buffer::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE1D:
			return Texture1D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE2D:
			return Texture2D::FromPointer( pointer );
		case D3D10_RESOURCE_DIMENSION_TEXTURE3D:
			return Texture3D::FromPointer( pointer );

		default:
			throw gcnew InvalidCastException( "Unrecognized resource type." );
		}
	}

	DXGI::ResourcePriority Resource::EvictionPriority::get()
	{
		return static_cast<DXGI::ResourcePriority>( InternalPointer->GetEvictionPriority() );
	}

	void Resource::EvictionPriority::set( DXGI::ResourcePriority value )
	{
		InternalPointer->SetEvictionPriority( static_cast<UINT>( value ) );
	}

	ResourceDimension Resource::Dimension::get()
	{
		D3D10_RESOURCE_DIMENSION type;
		InternalPointer->GetType(&type);
		return static_cast<ResourceDimension>( type );
	}

	Result Resource::LoadTextureFromTexture(Resource^ source, Resource^ destination, TextureLoadInformation loadInformation)
	{
		HRESULT hr = D3DX10LoadTextureFromTexture(source->InternalPointer, reinterpret_cast<D3DX10_TEXTURE_LOAD_INFO*>(&loadInformation), destination->InternalPointer);
		return RECORD_D3D10(hr);
	}

	Result Resource::FilterTexture(Resource^ texture, int sourceLevel, FilterFlags mipFilter)
	{
		HRESULT hr = D3DX10FilterTexture(texture->InternalPointer, sourceLevel, static_cast<UINT>(mipFilter));
		return RECORD_D3D10(hr);
	}

	int Resource::CalculateSubresourceIndex( int mipSlice, int arraySlice, int mipLevels )
	{
		return D3D10CalcSubresource( static_cast<UINT>( mipSlice ), static_cast<UINT>( arraySlice ), static_cast<UINT>( mipLevels ) );
	}

	int Resource::GetMipSize( int mipSlice, int baseSliceSize )
	{
		float size = static_cast<float>( baseSliceSize );

		while( mipSlice > 0 )
		{
			size = std::floorf(size / 2.0f);
			--mipSlice;
		}

		return (static_cast< int >(size));
	}

	ID3D10Resource* Resource::ConstructFromFile( SlimDX::Direct3D10::Device^ device, String^ fileName, D3DX10_IMAGE_LOAD_INFO* info )
	{
		ID3D10Resource* resource = 0;
		pin_ptr<const wchar_t> pinnedName = PtrToStringChars( fileName );
		HRESULT hr = D3DX10CreateTextureFromFile( device->InternalPointer, pinnedName, info, 0, &resource, 0 );
		RECORD_D3D10( hr );

		return resource;
	}

	ID3D10Resource* Resource::ConstructFromMemory( SlimDX::Direct3D10::Device^ device, array<Byte>^ memory, D3DX10_IMAGE_LOAD_INFO* info )
	{
		pin_ptr<unsigned char> pinnedMemory = &memory[0];

		ID3D10Resource* resource = 0;
		HRESULT hr = D3DX10CreateTextureFromMemory( device->InternalPointer, pinnedMemory, memory->Length, info, 0, &resource, 0 );
		RECORD_D3D10( hr );

		return resource;
	}

	ID3D10Resource* Resource::ConstructFromStream( SlimDX::Direct3D10::Device^ device, Stream^ stream, int sizeInBytes, D3DX10_IMAGE_LOAD_INFO* info )
	{
		DataStream^ ds = nullptr;
		array<Byte>^ memory = SlimDX::Utilities::ReadStream( stream, sizeInBytes, &ds );

		if( memory == nullptr )
		{
			ID3D10Resource* resource = NULL;
			SIZE_T size = static_cast<SIZE_T>( ds->RemainingLength );
			HRESULT hr = D3DX10CreateTextureFromMemory( device->InternalPointer, ds->SeekToEnd(), size,
				info, NULL, &resource, NULL );
			RECORD_D3D10( hr );

			return resource;
		}

		return ConstructFromMemory( device, memory, info );
	}
}
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP
#define STAN_MATH_PRIM_META_REF_TYPE_HPP

#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/is_vector.hpp>
#include <stan/math/prim/meta/plain_type.hpp>
#include <stan/math/prim/fun/Eigen.hpp>

#include <type_traits>

namespace stan {

/**
 * If the condition is true determines appropriate type for assigning expression
 * of given type to, to evaluate expensive expressions, but not make a copy if T
 * involves no calculations. This works similarly as `Eigen::Ref`. It also
 * handles rvalue references, so it can be used with perfect forwarding. If the
 * condition is false the expression will never be evaluated.
 *
 * Warning: if a variable of this type could be assigned a rvalue, make sure
 * template parameter `T` is of correct reference type (rvalue).
 * @tparam T type to determine reference for
 */
template <bool Condition, typename T, typename = void>
struct ref_type_if {
  using T_plain = plain_type_t<T>;
  using T_optionally_ref
      = std::conditional_t<std::is_rvalue_reference<T>::value,
                           std::remove_reference_t<T>, const T&>;
  using type = std::conditional_t<
      Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>::
              template match<std::decay_t<T>>::MatchAtCompileTime
          || !Condition,
      T_optionally_ref, T_plain>;
};

template <bool Condition, typename T>
struct ref_type_if<Condition, T, require_t<bool_constant<!is_eigen<T>::value || is_arena_matrix<T>::value>>> {
  using type = std::conditional_t<std::is_rvalue_reference<T>::value,
                                  std::remove_reference_t<T>, const T&>;
};

template <typename T>
using ref_type_t = typename ref_type_if<true, T>::type;

template <bool Condition, typename T>
using ref_type_if_t = typename ref_type_if<Condition, T>::type;

/**
 * Determines appropriate type for assigning expression of given type to, so
 * that the resulting type has directly accessible contiguous colum-major data,
 * which is needed to copy to OpenCL device for construction of matrix_cl.
 *
 * THis is similar to `ref_type` except this also copies expressions, which do
 * not have contiguous data (in both dimensions) or have row major storage
 * order.
 *
 * Warning: if a variable of this type could be assigned a rvalue, make sure
 * template parameter `T` is of correct reference type (rvalue).
 * @tparam T type to determine reference for
 */
template <typename T, typename = void>
struct ref_type_for_opencl {
  using T_val = std::remove_reference_t<T>;
  using T_plain_col_major = std::conditional_t<
      std::is_same<typename Eigen::internal::traits<T_val>::XprKind,
                   Eigen::MatrixXpr>::value,
      Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime,
                    T_val::ColsAtCompileTime>,
      Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime,
                   T_val::ColsAtCompileTime>>;
  using T_optionally_ref
      = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>;
  // Setting Outer stride of Ref to 0 (default) won't actually check that
  // expression has contiguous outer stride. Instead we need to check that
  // evaluator flags contain LinearAccessBit and PacketAccessBit.
  using type = std::conditional_t<
      Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>::
              template match<T_val>::MatchAtCompileTime
          && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit)
          && (Eigen::internal::evaluator<T_val>::Flags
              & Eigen::PacketAccessBit),
      T_optionally_ref, T_plain_col_major>;
};

template <typename T>
struct ref_type_for_opencl<T, require_not_eigen_t<T>> {
  using type = std::conditional_t<std::is_rvalue_reference<T>::value,
                                  std::remove_reference_t<T>, const T&>;
};

template <typename T>
using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type;

}  // namespace stan

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_META_REF_TYPE_HPP
#define STAN_MATH_PRIM_META_REF_TYPE_HPP

#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/is_vector.hpp>
#include <stan/math/prim/meta/plain_type.hpp>
#include <stan/math/prim/fun/Eigen.hpp>

#include <type_traits>

namespace stan {

/**
 * If the condition is true determines appropriate type for assigning expression
 * of given type to, to evaluate expensive expressions, but not make a copy if T
 * involves no calculations. This works similarly as `Eigen::Ref`. It also
 * handles rvalue references, so it can be used with perfect forwarding. If the
 * condition is false the expression will never be evaluated.
 *
 * Warning: if a variable of this type could be assigned a rvalue, make sure
 * template parameter `T` is of correct reference type (rvalue).
 * @tparam T type to determine reference for
 */
template <bool Condition, typename T, typename = void>
struct ref_type_if {
  using T_plain = plain_type_t<T>;
  using T_optionally_ref
      = std::conditional_t<std::is_rvalue_reference<T>::value,
                           std::remove_reference_t<T>, const T&>;
  using type = std::conditional_t<
      Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain>>>::
              template match<std::decay_t<T>>::MatchAtCompileTime
          || !Condition,
      T_optionally_ref, T_plain>;
};

template <bool Condition, typename T>
struct ref_type_if<Condition, T,
                   require_t<bool_constant<!is_eigen<T>::value
                                           || is_arena_matrix<T>::value>>> {
  using type = std::conditional_t<std::is_rvalue_reference<T>::value,
                                  std::remove_reference_t<T>, const T&>;
};

template <typename T>
using ref_type_t = typename ref_type_if<true, T>::type;

template <bool Condition, typename T>
using ref_type_if_t = typename ref_type_if<Condition, T>::type;

/**
 * Determines appropriate type for assigning expression of given type to, so
 * that the resulting type has directly accessible contiguous colum-major data,
 * which is needed to copy to OpenCL device for construction of matrix_cl.
 *
 * THis is similar to `ref_type` except this also copies expressions, which do
 * not have contiguous data (in both dimensions) or have row major storage
 * order.
 *
 * Warning: if a variable of this type could be assigned a rvalue, make sure
 * template parameter `T` is of correct reference type (rvalue).
 * @tparam T type to determine reference for
 */
template <typename T, typename = void>
struct ref_type_for_opencl {
  using T_val = std::remove_reference_t<T>;
  using T_plain_col_major = std::conditional_t<
      std::is_same<typename Eigen::internal::traits<T_val>::XprKind,
                   Eigen::MatrixXpr>::value,
      Eigen::Matrix<value_type_t<T>, T_val::RowsAtCompileTime,
                    T_val::ColsAtCompileTime>,
      Eigen::Array<value_type_t<T>, T_val::RowsAtCompileTime,
                   T_val::ColsAtCompileTime>>;
  using T_optionally_ref
      = std::conditional_t<std::is_rvalue_reference<T>::value, T_val, const T&>;
  // Setting Outer stride of Ref to 0 (default) won't actually check that
  // expression has contiguous outer stride. Instead we need to check that
  // evaluator flags contain LinearAccessBit and PacketAccessBit.
  using type = std::conditional_t<
      Eigen::internal::traits<Eigen::Ref<std::decay_t<T_plain_col_major>>>::
              template match<T_val>::MatchAtCompileTime
          && (Eigen::internal::evaluator<T_val>::Flags & Eigen::LinearAccessBit)
          && (Eigen::internal::evaluator<T_val>::Flags
              & Eigen::PacketAccessBit),
      T_optionally_ref, T_plain_col_major>;
};

template <typename T>
struct ref_type_for_opencl<T, require_not_eigen_t<T>> {
  using type = std::conditional_t<std::is_rvalue_reference<T>::value,
                                  std::remove_reference_t<T>, const T&>;
};

template <typename T>
using ref_type_for_opencl_t = typename ref_type_for_opencl<T>::type;

}  // namespace stan

#endif
<|endoftext|>


<commit_before>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program 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 General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "createdirectorydialog.h"
#include "progressdialog.h"
#include "renamedialog.h"
#include "mtpobjectsmodel.h"
#include "fileuploader.h"
#include <QDebug>
#include <QMessageBox>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSettings>
#include <QDir>

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	_ui(new Ui::MainWindow),
	_objectModel(new MtpObjectsModel(this)),
	_uploader(new FileUploader(_objectModel, this))
{
	_ui->setupUi(this);
	connect(_ui->listView, SIGNAL(doubleClicked(QModelIndex)), SLOT(onActivated(QModelIndex)));
	connect(_ui->listView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showContextMenu(QPoint)));
	connect(_ui->actionBack, SIGNAL(triggered()), SLOT(back()));
	connect(_ui->actionGo_Down, SIGNAL(triggered()), SLOT(down()));
	connect(_ui->actionCreateDirectory, SIGNAL(triggered()), SLOT(createDirectory()));
	connect(_ui->actionUploadDirectory, SIGNAL(triggered()), SLOT(uploadDirectories()));
	connect(_ui->actionUpload_Album, SIGNAL(triggered()), SLOT(uploadAlbum()));
	connect(_ui->actionUpload, SIGNAL(triggered()), SLOT(uploadFiles()));
}

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

void MainWindow::showEvent(QShowEvent *)
{
	if (!_device)
	{
		_device = mtp::Device::Find();
		if (!_device)
		{
			QMessageBox::critical(this, tr("No MTP device found"), tr("No MTP device found"));
			return;
		}
		_objectModel->setSession(_device->OpenSession(1));
		_ui->listView->setModel(_objectModel);
	}
}

void MainWindow::onActivated ( const QModelIndex & index )
{
	if (_objectModel->enter(index.row()))
		_history.push_back(_objectModel->parentObjectId());
}

void MainWindow::showContextMenu ( const QPoint & pos )
{
	QItemSelectionModel *selection =_ui->listView->selectionModel();
	QModelIndexList rows = selection->selectedRows();

	QMenu menu(this);
	//http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
	QAction * download_objects = menu.addAction("Download");
	QAction * rename_object = menu.addAction("Rename");
	rename_object->setEnabled(rows.size() == 1);
	QAction * delete_objects = menu.addAction(QIcon::fromTheme("edit-delete"), "Delete");
	QAction * action = menu.exec(_ui->listView->mapToGlobal(pos));
	if (!action)
		return;

	if (action == download_objects)
	{
		QList<quint32> objects;
		for(int i = 0; i < rows.size(); ++i)
		{
			QModelIndex row = rows[i];
			objects.push_back(_objectModel->objectIdAt(row.row()));
		}
		downloadFiles(objects);
	}
	else
	{
		for(int i = rows.size() - 1; i >= 0; --i)
		{
			QModelIndex row = rows[i];
			if (action == delete_objects)
				_objectModel->removeRow(row.row());
			else if (action == rename_object)
			{
				RenameDialog d(_objectModel->data(row).toString(), this);
				int r = d.exec();
				if (r)
					_objectModel->rename(row.row(), d.name());
			}
			else
				qDebug() << "unknown action!";
		}
	}
}

void MainWindow::back()
{
	if (_history.empty())
		return;
	_history.pop_back();
	mtp::u32 oid = _history.empty()? mtp::Session::Root: _history.back();
	_objectModel->setParent(oid);
}

void MainWindow::down()
{
	if (_objectModel->enter(_ui->listView->currentIndex().row()))
		_history.push_back(_objectModel->parentObjectId());
}

void MainWindow::createDirectory()
{
	CreateDirectoryDialog d(this);
	if (d.exec() && !d.name().isEmpty())
		_objectModel->createDirectory(d.name(), false);
}

void MainWindow::uploadFiles(const QStringList &files)
{
	if (files.isEmpty())
		return;

	qDebug() << "uploadFiles " << files;
	unsigned limit = 0;
	//temp workaround kernel/libusb bug
	{
		QFile f("/sys/module/usbcore/parameters/usbfs_memory_mb");
		if (f.open(QIODevice::ReadOnly | QIODevice::Text))
		{
			QTextStream stream(&f);
			stream >> limit;
			qDebug() << "usbfs limit: " << limit << "Mib";
		}
		else
			qDebug() << "cannot read limit on usbfs transaction";
	}
	unsigned max = 0;
	for(QString file : files)
	{
		QFileInfo fi(file);
		unsigned mb = (fi.size() + 1024 * 1024 - 1) / 1024 / 1024;
		if (mb > max)
			max = mb;
	}

	if (limit && max > limit)
	{
		QMessageBox::warning(this, "Error", "This file(s) will trigger the bug in libusb-1.0.\n"
			"Please increase usbfs memory usage limit with the following command as root:\n"
			"echo -n " + QString::number(max * 3 / 2) + " > /sys/module/usbcore/parameters/usbfs_memory_mb\n"
			"and then, try again"
		);
		return;
	}
	ProgressDialog progressDialog(this);
	progressDialog.setModal(true);
	progressDialog.setValue(0);

	connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float)));
	connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString)));
	connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept()));
	_uploader->upload(files);

	progressDialog.exec();
}

void MainWindow::downloadFiles(const QList<quint32> &objects)
{
	if (objects.isEmpty())
		return;

	QString path = QFileDialog::getExistingDirectory(this, tr("Enter destination directory"));
	if (path.isEmpty())
		return;

	qDebug() << "downloading to " << path;
	ProgressDialog progressDialog(this);
	progressDialog.show();

	connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float)));
	connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString)));
	connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept()));
	_uploader->download(path, objects);

	progressDialog.exec();
}

void MainWindow::uploadFiles()
{
	QFileDialog d(this);

	QSettings settings;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			d.setDirectory(ld.toString());
	}

	d.setAcceptMode(QFileDialog::AcceptOpen);
	d.setFileMode(QFileDialog::ExistingFiles);
	d.setOption(QFileDialog::ShowDirsOnly, false);
	d.exec();

	settings.setValue("the-latest-directory", d.directory().absolutePath());

	uploadFiles(d.selectedFiles());
}

void MainWindow::uploadDirectories()
{
	QSettings settings;
	QString dirPath;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			dirPath = ld.toString();
	}

	dirPath = QFileDialog::getExistingDirectory(this, "Upload Directories", dirPath);
	if (dirPath.isEmpty())
		return;

	settings.setValue("the-latest-directory", dirPath);

	QDir dir(dirPath);
	qDebug() << "adding directory " << dir.dirName();
	mtp::u32 dirId = _objectModel->createDirectory(dir.dirName(), false);
	_objectModel->setParent(dirId);
	_history.push_back(dirId);

	QStringList files;
	for(QString file : dir.entryList(QDir::Files))
	{
		files.push_back(dir.canonicalPath() + "/" + file);
	}
	uploadFiles(files);
	back();
}

void MainWindow::uploadAlbum()
{
	QString dirPath;
	QSettings settings;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			dirPath = ld.toString();
	}

	dirPath = QFileDialog::getExistingDirectory(this, "Upload Album", dirPath);
	if (!dirPath.isEmpty()) {
		settings.setValue("the-latest-directory", dirPath);
		uploadAlbum(dirPath);
	}
	back();
}

namespace
{
	int GetScore(const QString &str_)
	{
		QString str = str_.toLower();
		int score = 0;
		if (str.contains("art"))
			score += 1;
		if (str.contains("album"))
			score += 1;
		if (str.contains("large"))
			score += 2;
		if (str.contains("small"))
			score += 1;
		if (str.contains("folder"))
			score += 1;
		return score;
	}

	bool HeuristicLess(const QString &s1, const QString &s2)
	{
		return GetScore(s1) > GetScore(s2);
	}
}

void MainWindow::uploadAlbum(QString dirPath)
{
	QDir dir(dirPath);
	qDebug() << "adding directory " << dir.dirName();

	mtp::u32 dirId = _objectModel->createDirectory(dir.dirName(), true);
	_objectModel->setParent(dirId);
	_history.push_back(dirId);

	QString cover, coverTarget;
	QStringList covers;
	{
		QStringList ext({"*.png", "*.jpg", "*.jpeg"});
		covers = dir.entryList(ext, QDir::Files);
		qSort(covers.begin(), covers.end(), &HeuristicLess);
		qDebug() << "covers" << covers;
		if (!covers.isEmpty())
			cover = covers.front();

		if (cover.endsWith(".png"))
			coverTarget = "albumart.png";
		else
			coverTarget = "albumart.jpg";

		qDebug() << "use " << cover << " as album art -> " << coverTarget;
	}

	_objectModel->uploadFile(dir.canonicalPath() + "/" + cover, coverTarget);

	QStringList files;
	for(QString file : dir.entryList(QDir::Files))
	{
		if (!covers.contains(file))
			files.push_back(dir.canonicalPath() + "/" + file);
	}
	uploadFiles(files);
}
<commit_msg>removed warning about usb devio limit<commit_after>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program 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 General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "createdirectorydialog.h"
#include "progressdialog.h"
#include "renamedialog.h"
#include "mtpobjectsmodel.h"
#include "fileuploader.h"
#include <QDebug>
#include <QMessageBox>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSettings>
#include <QDir>

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	_ui(new Ui::MainWindow),
	_objectModel(new MtpObjectsModel(this)),
	_uploader(new FileUploader(_objectModel, this))
{
	_ui->setupUi(this);
	connect(_ui->listView, SIGNAL(doubleClicked(QModelIndex)), SLOT(onActivated(QModelIndex)));
	connect(_ui->listView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(showContextMenu(QPoint)));
	connect(_ui->actionBack, SIGNAL(triggered()), SLOT(back()));
	connect(_ui->actionGo_Down, SIGNAL(triggered()), SLOT(down()));
	connect(_ui->actionCreateDirectory, SIGNAL(triggered()), SLOT(createDirectory()));
	connect(_ui->actionUploadDirectory, SIGNAL(triggered()), SLOT(uploadDirectories()));
	connect(_ui->actionUpload_Album, SIGNAL(triggered()), SLOT(uploadAlbum()));
	connect(_ui->actionUpload, SIGNAL(triggered()), SLOT(uploadFiles()));
}

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

void MainWindow::showEvent(QShowEvent *)
{
	if (!_device)
	{
		_device = mtp::Device::Find();
		if (!_device)
		{
			QMessageBox::critical(this, tr("No MTP device found"), tr("No MTP device found"));
			return;
		}
		_objectModel->setSession(_device->OpenSession(1));
		_ui->listView->setModel(_objectModel);
	}
}

void MainWindow::onActivated ( const QModelIndex & index )
{
	if (_objectModel->enter(index.row()))
		_history.push_back(_objectModel->parentObjectId());
}

void MainWindow::showContextMenu ( const QPoint & pos )
{
	QItemSelectionModel *selection =_ui->listView->selectionModel();
	QModelIndexList rows = selection->selectedRows();

	QMenu menu(this);
	//http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
	QAction * download_objects = menu.addAction("Download");
	QAction * rename_object = menu.addAction("Rename");
	rename_object->setEnabled(rows.size() == 1);
	QAction * delete_objects = menu.addAction(QIcon::fromTheme("edit-delete"), "Delete");
	QAction * action = menu.exec(_ui->listView->mapToGlobal(pos));
	if (!action)
		return;

	if (action == download_objects)
	{
		QList<quint32> objects;
		for(int i = 0; i < rows.size(); ++i)
		{
			QModelIndex row = rows[i];
			objects.push_back(_objectModel->objectIdAt(row.row()));
		}
		downloadFiles(objects);
	}
	else
	{
		for(int i = rows.size() - 1; i >= 0; --i)
		{
			QModelIndex row = rows[i];
			if (action == delete_objects)
				_objectModel->removeRow(row.row());
			else if (action == rename_object)
			{
				RenameDialog d(_objectModel->data(row).toString(), this);
				int r = d.exec();
				if (r)
					_objectModel->rename(row.row(), d.name());
			}
			else
				qDebug() << "unknown action!";
		}
	}
}

void MainWindow::back()
{
	if (_history.empty())
		return;
	_history.pop_back();
	mtp::u32 oid = _history.empty()? mtp::Session::Root: _history.back();
	_objectModel->setParent(oid);
}

void MainWindow::down()
{
	if (_objectModel->enter(_ui->listView->currentIndex().row()))
		_history.push_back(_objectModel->parentObjectId());
}

void MainWindow::createDirectory()
{
	CreateDirectoryDialog d(this);
	if (d.exec() && !d.name().isEmpty())
		_objectModel->createDirectory(d.name(), false);
}

void MainWindow::uploadFiles(const QStringList &files)
{
	if (files.isEmpty())
		return;

	qDebug() << "uploadFiles " << files;
	ProgressDialog progressDialog(this);
	progressDialog.setModal(true);
	progressDialog.setValue(0);

	connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float)));
	connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString)));
	connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept()));
	_uploader->upload(files);

	progressDialog.exec();
}

void MainWindow::downloadFiles(const QList<quint32> &objects)
{
	if (objects.isEmpty())
		return;

	QString path = QFileDialog::getExistingDirectory(this, tr("Enter destination directory"));
	if (path.isEmpty())
		return;

	qDebug() << "downloading to " << path;
	ProgressDialog progressDialog(this);
	progressDialog.show();

	connect(_uploader, SIGNAL(uploadProgress(float)), &progressDialog, SLOT(setValue(float)));
	connect(_uploader, SIGNAL(uploadStarted(QString)), &progressDialog, SLOT(setFilename(QString)));
	connect(_uploader, SIGNAL(finished()), &progressDialog, SLOT(accept()));
	_uploader->download(path, objects);

	progressDialog.exec();
}

void MainWindow::uploadFiles()
{
	QFileDialog d(this);

	QSettings settings;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			d.setDirectory(ld.toString());
	}

	d.setAcceptMode(QFileDialog::AcceptOpen);
	d.setFileMode(QFileDialog::ExistingFiles);
	d.setOption(QFileDialog::ShowDirsOnly, false);
	d.exec();

	settings.setValue("the-latest-directory", d.directory().absolutePath());

	uploadFiles(d.selectedFiles());
}

void MainWindow::uploadDirectories()
{
	QSettings settings;
	QString dirPath;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			dirPath = ld.toString();
	}

	dirPath = QFileDialog::getExistingDirectory(this, "Upload Directories", dirPath);
	if (dirPath.isEmpty())
		return;

	settings.setValue("the-latest-directory", dirPath);

	QDir dir(dirPath);
	qDebug() << "adding directory " << dir.dirName();
	mtp::u32 dirId = _objectModel->createDirectory(dir.dirName(), false);
	_objectModel->setParent(dirId);
	_history.push_back(dirId);

	QStringList files;
	for(QString file : dir.entryList(QDir::Files))
	{
		files.push_back(dir.canonicalPath() + "/" + file);
	}
	uploadFiles(files);
	back();
}

void MainWindow::uploadAlbum()
{
	QString dirPath;
	QSettings settings;
	{
		QVariant ld = settings.value("the-latest-directory");
		if (ld.isValid())
			dirPath = ld.toString();
	}

	dirPath = QFileDialog::getExistingDirectory(this, "Upload Album", dirPath);
	if (!dirPath.isEmpty()) {
		settings.setValue("the-latest-directory", dirPath);
		uploadAlbum(dirPath);
	}
	back();
}

namespace
{
	int GetScore(const QString &str_)
	{
		QString str = str_.toLower();
		int score = 0;
		if (str.contains("art"))
			score += 1;
		if (str.contains("album"))
			score += 1;
		if (str.contains("large"))
			score += 2;
		if (str.contains("small"))
			score += 1;
		if (str.contains("folder"))
			score += 1;
		return score;
	}

	bool HeuristicLess(const QString &s1, const QString &s2)
	{
		return GetScore(s1) > GetScore(s2);
	}
}

void MainWindow::uploadAlbum(QString dirPath)
{
	QDir dir(dirPath);
	qDebug() << "adding directory " << dir.dirName();

	mtp::u32 dirId = _objectModel->createDirectory(dir.dirName(), true);
	_objectModel->setParent(dirId);
	_history.push_back(dirId);

	QString cover, coverTarget;
	QStringList covers;
	{
		QStringList ext({"*.png", "*.jpg", "*.jpeg"});
		covers = dir.entryList(ext, QDir::Files);
		qSort(covers.begin(), covers.end(), &HeuristicLess);
		qDebug() << "covers" << covers;
		if (!covers.isEmpty())
			cover = covers.front();

		if (cover.endsWith(".png"))
			coverTarget = "albumart.png";
		else
			coverTarget = "albumart.jpg";

		qDebug() << "use " << cover << " as album art -> " << coverTarget;
	}

	_objectModel->uploadFile(dir.canonicalPath() + "/" + cover, coverTarget);

	QStringList files;
	for(QString file : dir.entryList(QDir::Files))
	{
		if (!covers.contains(file))
			files.push_back(dir.canonicalPath() + "/" + file);
	}
	uploadFiles(files);
}
<|endoftext|>


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

#include <QFileDialog>
#include <iostream>
#include <QMessageBox>

#include "src/xmlio.hpp"
#include "src/exceptions.hpp"
#include "addsemestredialog.h"

#define UVM UvManager::getInstance()

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);
    QMainWindow::showMaximized();
}

MainWindow::~MainWindow() {
    delete ui;
    UvManager::freeInstance();
}

void MainWindow::loadFile() {

    QString filename = QFileDialog::getOpenFileName(this, "Ouvrir le fichier");
    if (filename.isNull()) { return; }

    UVM->setPolicy(new XmlIo(filename));
    try {
        UVM->load();
    } catch(const Exception& e) {
        QMessageBox error(this);
        error.setText(e.getinfo());
        error.exec();
        return;
    }

    ui->uvdisplay->refresh();
    AddSemestreDialog s(this);
    s.exec();
}

void MainWindow::saveFile() {
    if (UVM->hasPolicyDefined()) {
        UVM->save();
    } else {
        QMessageBox error(this);
        error.setText("Aucune donnée chargée");
        error.exec();
        return;
    }
}
<commit_msg>Plus de popup au démarrage<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <iostream>
#include <QMessageBox>

#include "src/xmlio.hpp"
#include "src/exceptions.hpp"
#include "addsemestredialog.h"

#define UVM UvManager::getInstance()

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {
    ui->setupUi(this);
    QMainWindow::showMaximized();
}

MainWindow::~MainWindow() {
    delete ui;
    UvManager::freeInstance();
}

void MainWindow::loadFile() {

    QString filename = QFileDialog::getOpenFileName(this, "Ouvrir le fichier");
    if (filename.isNull()) { return; }

    UVM->setPolicy(new XmlIo(filename));
    try {
        UVM->load();
    } catch(const Exception& e) {
        QMessageBox error(this);
        error.setText(e.getinfo());
        error.exec();
        return;
    }

    ui->uvdisplay->refresh();
}

void MainWindow::saveFile() {
    if (UVM->hasPolicyDefined()) {
        UVM->save();
    } else {
        QMessageBox error(this);
        error.setText("Aucune donnée chargée");
        error.exec();
        return;
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3136
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3136 to 3137<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3137
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3416
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3416 to 3417<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3417
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>#include "skse/PluginAPI.h"
#include "skse/skse_version.h"
#include "skse/GameAPI.h"
#include "skse/GameMenus.h"

#include "skse/SafeWrite.h"

#define NOMENUPAUSE_HOOK_ADDR 0x0069cc6e

IDebugLog gLog("NoMenuPause.log");

PluginHandle g_pluginHandle = kPluginHandle_Invalid;
SKSEMessagingInterface*	g_messaging = nullptr;

// These menus cannot be paused!
BSFixedString MainMenu("Main Menu");
BSFixedString LoadingMenu("Loading Menu");
BSFixedString Console("Console");
BSFixedString TutorialMenu("Tutorial Menu");
BSFixedString TweenMenu("TweenMenu");

// These menus can be paused!
BSFixedString MagicMenu("MagicMenu"); // Will not be paused if accessed through the "tween" menu.
BSFixedString InventoryMenu("InventoryMenu"); // Will not be paused if accessed through the "tween" menu.
BSFixedString ContainerMenu("ContainerMenu");
BSFixedString FavoritesMenu("FavoritesMenu");
BSFixedString BookMenu("Book Menu");
//BSFixedString LockpickingMenu("Lockpicking Menu"); // Does not work :(
BSFixedString BarterMenu("BarterMenu");
BSFixedString CraftingMenu("Crafting Menu");
BSFixedString TrainingMenu("Training Menu");

bool __fastcall GetNoPause(MenuManager* mm) {
	UInt32 menuStackCount = *(UInt32*)((UInt32)mm + 0x9c);

	if (menuStackCount > 1) {
		if (mm->IsMenuOpen(&MainMenu) || mm->IsMenuOpen(&LoadingMenu) || mm->IsMenuOpen(&Console) || mm->IsMenuOpen(&TutorialMenu) || mm->IsMenuOpen(&TweenMenu)) {
			return false;
		}
		return mm->IsMenuOpen(&MagicMenu) || mm->IsMenuOpen(&InventoryMenu) || mm->IsMenuOpen(&ContainerMenu) || mm->IsMenuOpen(&FavoritesMenu) || mm->IsMenuOpen(&BookMenu) || mm->IsMenuOpen(&BarterMenu) || mm->IsMenuOpen(&CraftingMenu) || mm->IsMenuOpen(&TrainingMenu);
	}

	return false;
}

extern "C" {

	bool SKSEPlugin_Query(const SKSEInterface* skse, PluginInfo* info) {
		_MESSAGE("SKSEPlugin_Query begin");

		// populate info structure
		info->infoVersion = PluginInfo::kInfoVersion;
		info->name = "NoMenuPause Plugin";
		info->version = 1;

		// store plugin handle so we can identify ourselves later
		g_pluginHandle = skse->GetPluginHandle();

		if (skse->isEditor) {
			_MESSAGE("loaded in editor, marking as incompatible");

			return false;
		}
		else if (skse->runtimeVersion != RUNTIME_VERSION_1_9_32_0) {
			_MESSAGE("unsupported runtime version %08X", skse->runtimeVersion);

			return false;
		}

		_MESSAGE("SKSEPlugin_Query end");

		// supported runtime version
		return true;
	}

	bool SKSEPlugin_Load(const SKSEInterface * skse) {
		_MESSAGE("SKSEPlugin_Load begin");

		UInt32 hs, he;
		__asm {
			push eax;
			mov eax, START_OF_HOOK;
			mov hs, eax;
			mov eax, END_OF_HOOK;
			mov he, eax;
			pop eax;

			jmp SKIP_HOOK;

		START_OF_HOOK:
			pushad;
			call GetNoPause;
			cmp eax, 0x1;
			popad;
			jz END_OF_HOOK;

			cmp[ecx + 0x000000C8], ebx;

		END_OF_HOOK:
			nop;
			nop;
			nop;
			nop;
			nop;

		SKIP_HOOK:
		}

		WriteRelJump(NOMENUPAUSE_HOOK_ADDR, hs);
		SafeWrite8(NOMENUPAUSE_HOOK_ADDR + 5, 0x90);
		WriteRelJump(he, NOMENUPAUSE_HOOK_ADDR + 6);

		_MESSAGE("SKSEPlugin_Load end");

		return true;
	}

};
<commit_msg>Removed messaging interface since it's no longer used.<commit_after>#include "skse/PluginAPI.h"
#include "skse/skse_version.h"
#include "skse/GameAPI.h"
#include "skse/GameMenus.h"

#include "skse/SafeWrite.h"

#define NOMENUPAUSE_HOOK_ADDR 0x0069cc6e

IDebugLog gLog("NoMenuPause.log");

PluginHandle g_pluginHandle = kPluginHandle_Invalid;

// These menus cannot be paused!
BSFixedString MainMenu("Main Menu");
BSFixedString LoadingMenu("Loading Menu");
BSFixedString Console("Console");
BSFixedString TutorialMenu("Tutorial Menu");
BSFixedString TweenMenu("TweenMenu");

// These menus can be paused!
BSFixedString MagicMenu("MagicMenu"); // Will not be paused if accessed through the "tween" menu.
BSFixedString InventoryMenu("InventoryMenu"); // Will not be paused if accessed through the "tween" menu.
BSFixedString ContainerMenu("ContainerMenu");
BSFixedString FavoritesMenu("FavoritesMenu");
BSFixedString BookMenu("Book Menu");
//BSFixedString LockpickingMenu("Lockpicking Menu"); // Does not work :(
BSFixedString BarterMenu("BarterMenu");
BSFixedString CraftingMenu("Crafting Menu");
BSFixedString TrainingMenu("Training Menu");

bool __fastcall GetNoPause(MenuManager* mm) {
	UInt32 menuStackCount = *(UInt32*)((UInt32)mm + 0x9c);

	if (menuStackCount > 1) {
		if (mm->IsMenuOpen(&MainMenu) || mm->IsMenuOpen(&LoadingMenu) || mm->IsMenuOpen(&Console) || mm->IsMenuOpen(&TutorialMenu) || mm->IsMenuOpen(&TweenMenu)) {
			return false;
		}
		return mm->IsMenuOpen(&MagicMenu) || mm->IsMenuOpen(&InventoryMenu) || mm->IsMenuOpen(&ContainerMenu) || mm->IsMenuOpen(&FavoritesMenu) || mm->IsMenuOpen(&BookMenu) || mm->IsMenuOpen(&BarterMenu) || mm->IsMenuOpen(&CraftingMenu) || mm->IsMenuOpen(&TrainingMenu);
	}

	return false;
}

extern "C" {

	bool SKSEPlugin_Query(const SKSEInterface* skse, PluginInfo* info) {
		_MESSAGE("SKSEPlugin_Query begin");

		// populate info structure
		info->infoVersion = PluginInfo::kInfoVersion;
		info->name = "NoMenuPause Plugin";
		info->version = 1;

		// store plugin handle so we can identify ourselves later
		g_pluginHandle = skse->GetPluginHandle();

		if (skse->isEditor) {
			_MESSAGE("loaded in editor, marking as incompatible");

			return false;
		}
		else if (skse->runtimeVersion != RUNTIME_VERSION_1_9_32_0) {
			_MESSAGE("unsupported runtime version %08X", skse->runtimeVersion);

			return false;
		}

		_MESSAGE("SKSEPlugin_Query end");

		// supported runtime version
		return true;
	}

	bool SKSEPlugin_Load(const SKSEInterface * skse) {
		_MESSAGE("SKSEPlugin_Load begin");

		UInt32 hs, he;
		__asm {
			push eax;
			mov eax, START_OF_HOOK;
			mov hs, eax;
			mov eax, END_OF_HOOK;
			mov he, eax;
			pop eax;

			jmp SKIP_HOOK;

		START_OF_HOOK:
			pushad;
			call GetNoPause;
			cmp eax, 0x1;
			popad;
			jz END_OF_HOOK;

			cmp[ecx + 0x000000C8], ebx;

		END_OF_HOOK:
			nop;
			nop;
			nop;
			nop;
			nop;

		SKIP_HOOK:
		}

		WriteRelJump(NOMENUPAUSE_HOOK_ADDR, hs);
		SafeWrite8(NOMENUPAUSE_HOOK_ADDR + 5, 0x90);
		WriteRelJump(he, NOMENUPAUSE_HOOK_ADDR + 6);

		_MESSAGE("SKSEPlugin_Load end");

		return true;
	}

};
<|endoftext|>


<commit_before>/******************************************************************************************[Main.C]
MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/

#include <ctime>
#include <cstring>
#include <stdint.h>
#include <errno.h>

#include <signal.h>
#include <zlib.h>

#include "Solver.h"

/*************************************************************************************/
#ifdef _MSC_VER
#include <ctime>

static inline double cpuTime(void) {
    return (double)clock() / CLOCKS_PER_SEC; }
#else

#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>

static inline double cpuTime(void) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
#endif

#if defined(__linux__)
static inline int memReadStat(int field)
{
    char    name[256];
    pid_t pid = getpid();
    sprintf(name, "/proc/%d/statm", pid);
    FILE*   in = fopen(name, "rb");
    if (in == NULL) return 0;
    int     value;
    for (; field >= 0; field--)
        fscanf(in, "%d", &value);
    fclose(in);
    return value;
}
static inline uint64_t memUsed() { return (uint64_t)memReadStat(0) * (uint64_t)getpagesize(); }

#elif defined(__FreeBSD__)
static inline uint64_t memUsed(void) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return ru.ru_maxrss*1024; }

#else
static inline uint64_t memUsed() { return 0; }
#endif

#if defined(__linux__)
#include <fpu_control.h>
#endif

//=================================================================================================
// DIMACS Parser:

#define CHUNK_LIMIT 1048576

class StreamBuffer {
    FILE*  in;
    char    buf[CHUNK_LIMIT];
    int     pos;
    int     size;

    void assureLookahead() {
        if (pos >= size) {
            pos  = 0;
            size = fread(buf, 1, sizeof(buf), in); } }

public:
    StreamBuffer(FILE* i) : in(i), pos(0), size(0) {
        assureLookahead(); }

    int  operator *  () { return (pos >= size) ? EOF : buf[pos]; }
    void operator ++ () { pos++; assureLookahead(); }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

template<class B>
static void skipWhitespace(B& in) {
    while ((*in >= 9 && *in <= 13) || *in == 32)
        ++in; }

template<class B>
static void skipLine(B& in) {
    for (;;){
        if (*in == EOF || *in == '\0') return;
        if (*in == '\n') { ++in; return; }
        ++in; } }

template<class B>
static int parseInt(B& in) {
    int     val = 0;
    bool    neg = false;
    skipWhitespace(in);
    if      (*in == '-') neg = true, ++in;
    else if (*in == '+') ++in;
    if (*in < '0' || *in > '9') reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
    while (*in >= '0' && *in <= '9')
        val = val*10 + (*in - '0'),
        ++in;
    return neg ? -val : val; }

template<class B>
static void readClause(B& in, Solver& S, vec<Lit>& lits) {
    int     parsed_lit, var;
    lits.clear();
    for (;;){
        parsed_lit = parseInt(in);
        if (parsed_lit == 0) break;
        var = abs(parsed_lit)-1;
        while (var >= S.nVars()) S.newVar();
        lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
    }
}

template<class B>
static bool match(B& in, char* str) {
    for (; *str != 0; ++str, ++in)
        if (*str != *in)
            return false;
    return true;
}

template<class B>
static void parse_DIMACS_main(B& in, Solver& S) {
    vec<Lit> lits;
    for (;;){
        skipWhitespace(in);
        if (*in == EOF)
            break;
        else if (*in == 'p'){
            if (match(in, "p cnf")){
                int vars    = parseInt(in);
                int clauses = parseInt(in);
                reportf("|  Number of variables:  %-12d                                         |\n", vars);
                reportf("|  Number of clauses:    %-12d                                         |\n", clauses);
            }else{
                reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
            }
        } else if (*in == 'c' || *in == 'p')
            skipLine(in);
        else
            readClause(in, S, lits),
            S.addClause(lits);
    }
}

// Inserts problem into solver.
//
static void parse_DIMACS(FILE* input_stream, Solver& S) {
    StreamBuffer in(input_stream);
    parse_DIMACS_main(in, S); }

//=================================================================================================

void printStats(Solver& solver)
{
    double   cpu_time = cpuTime();
    uint64_t mem_used = memUsed();
    reportf("restarts              : %lld\n", solver.starts);
    reportf("conflicts             : %-12lld   (%.0f /sec)\n", solver.conflicts   , solver.conflicts   /cpu_time);
    reportf("decisions             : %-12lld   (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions   /cpu_time);
    reportf("propagations          : %-12lld   (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
    reportf("conflict literals     : %-12lld   (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
    if (mem_used != 0) reportf("Memory used           : %.2f MB\n", mem_used / 1048576.0);
    reportf("CPU time              : %g s\n", cpu_time);
}

Solver* solver;
static void SIGINT_handler(int signum) {
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    printStats(*solver);
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    exit(1); }

//=================================================================================================
// Main:

void printUsage(char** argv)
{
    reportf("USAGE: %s [options] <input-file> <result-output-file>\n\n  where input may be either in plain or gzipped DIMACS.\n\n", argv[0]);
    reportf("OPTIONS:\n\n");
    reportf("  -polarity-mode = {true,false,rnd}\n");
    reportf("  -decay         = <num> [ 0 - 1 ]\n");
    reportf("  -rnd-freq      = <num> [ 0 - 1 ]\n");
    reportf("  -verbosity     = {0,1,2}\n");
    reportf("\n");
}

const char* hasPrefix(const char* str, const char* prefix)
{
    int len = strlen(prefix);
    if (strncmp(str, prefix, len) == 0)
        return str + len;
    else
        return NULL;
}

int main(int argc, char** argv)
{
    Solver      S;
    S.verbosity = 1;

    /*int         i, j;
    const char* value;
    for (i = j = 0; i < argc; i++){
        if ((value = hasPrefix(argv[i], "-polarity-mode="))){
            if (strcmp(value, "true") == 0)
                S.polarity_mode = Solver::polarity_true;
            else if (strcmp(value, "false") == 0)
                S.polarity_mode = Solver::polarity_false;
            else if (strcmp(value, "rnd") == 0)
                S.polarity_mode = Solver::polarity_rnd;
            else{
                reportf("ERROR! unknown polarity-mode %s\n", value);
                exit(0); }

        }else if ((value = hasPrefix(argv[i], "-rnd-freq="))){
            double rnd;
            if (sscanf(value, "%lf", &rnd) <= 0 || rnd < 0 || rnd > 1){
                reportf("ERROR! illegal rnd-freq constant %s\n", value);
                exit(0); }
            S.random_var_freq = rnd;

        }else if ((value = hasPrefix(argv[i], "-decay="))){
            double decay;
            if (sscanf(value, "%lf", &decay) <= 0 || decay <= 0 || decay > 1){
                reportf("ERROR! illegal decay constant %s\n", value);
                exit(0); }
            S.var_decay = 1 / decay;

        }else if ((value = hasPrefix(argv[i], "-verbosity="))){
            int verbosity = (int)strtol(value, NULL, 10);
            if (verbosity == 0 && errno == EINVAL){
                reportf("ERROR! illegal verbosity level %s\n", value);
                exit(0); }
            S.verbosity = verbosity;

        }else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0){
            printUsage(argv);
            exit(0);

        }else if (strncmp(argv[i], "-", 1) == 0){
            reportf("ERROR! unknown flag %s\n", argv[i]);
            exit(0);

        }else
            argv[j++] = argv[i];
    }
    argc = j;
    */

    reportf("This is MiniSat 2.0 beta\n");
#if defined(__linux__)
    fpu_control_t oldcw, newcw;
    _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
    reportf("WARNING: for repeatability, setting FPU to use double precision\n");
#endif
    double cpu_time = cpuTime();

    solver = &S;
    signal(SIGINT,SIGINT_handler);
    signal(SIGHUP,SIGINT_handler);

    if (argc == 1)
        reportf("Reading from standard input... Use '-h' or '--help' for help.\n");

    FILE* in = fopen(argv[1], "rb");
    if (in == NULL)
        reportf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);

    reportf("============================[ Problem Statistics ]=============================\n");
    reportf("|                                                                             |\n");

    parse_DIMACS(in, S);
    fclose(in);
    FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;

    double parse_time = cpuTime() - cpu_time;
    reportf("|  Parsing time:         %-12.2f s                                       |\n", parse_time);

    if (!S.simplify()){
        reportf("Solved by unit propagation\n");
        if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
        printf("UNSATISFIABLE\n");
        exit(20);
    }

    bool ret = S.solve();
    printStats(S);
    reportf("\n");
    printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
    if (res != NULL){
        if (ret){
            fprintf(res, "SAT\n");
            for (int i = 0; i < S.nVars(); i++)
                if (S.model[i] != l_Undef)
                    fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
            fprintf(res, " 0\n");
        }else
            fprintf(res, "UNSAT\n");
        fclose(res);
    }

#ifdef NDEBUG
    exit(ret ? 10 : 20);     // (faster than "return", which will invoke the destructor for 'Solver')
#endif
}
<commit_msg>Removing 2nd input file, printing to console by default<commit_after>/******************************************************************************************[Main.C]
MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/

#include <ctime>
#include <cstring>
#include <stdint.h>
#include <errno.h>

#include <signal.h>
#include <zlib.h>

#include "Solver.h"

/*************************************************************************************/
#ifdef _MSC_VER
#include <ctime>

static inline double cpuTime(void) {
    return (double)clock() / CLOCKS_PER_SEC; }
#else

#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>

static inline double cpuTime(void) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
#endif

#if defined(__linux__)
static inline int memReadStat(int field)
{
    char    name[256];
    pid_t pid = getpid();
    sprintf(name, "/proc/%d/statm", pid);
    FILE*   in = fopen(name, "rb");
    if (in == NULL) return 0;
    int     value;
    for (; field >= 0; field--)
        fscanf(in, "%d", &value);
    fclose(in);
    return value;
}
static inline uint64_t memUsed() { return (uint64_t)memReadStat(0) * (uint64_t)getpagesize(); }

#elif defined(__FreeBSD__)
static inline uint64_t memUsed(void) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return ru.ru_maxrss*1024; }

#else
static inline uint64_t memUsed() { return 0; }
#endif

#if defined(__linux__)
#include <fpu_control.h>
#endif

//=================================================================================================
// DIMACS Parser:

#define CHUNK_LIMIT 1048576

class StreamBuffer {
    FILE*  in;
    char    buf[CHUNK_LIMIT];
    int     pos;
    int     size;

    void assureLookahead() {
        if (pos >= size) {
            pos  = 0;
            size = fread(buf, 1, sizeof(buf), in); } }

public:
    StreamBuffer(FILE* i) : in(i), pos(0), size(0) {
        assureLookahead(); }

    int  operator *  () { return (pos >= size) ? EOF : buf[pos]; }
    void operator ++ () { pos++; assureLookahead(); }
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

template<class B>
static void skipWhitespace(B& in) {
    while ((*in >= 9 && *in <= 13) || *in == 32)
        ++in; }

template<class B>
static void skipLine(B& in) {
    for (;;){
        if (*in == EOF || *in == '\0') return;
        if (*in == '\n') { ++in; return; }
        ++in; } }

template<class B>
static int parseInt(B& in) {
    int     val = 0;
    bool    neg = false;
    skipWhitespace(in);
    if      (*in == '-') neg = true, ++in;
    else if (*in == '+') ++in;
    if (*in < '0' || *in > '9') reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
    while (*in >= '0' && *in <= '9')
        val = val*10 + (*in - '0'),
        ++in;
    return neg ? -val : val; }

template<class B>
static void readClause(B& in, Solver& S, vec<Lit>& lits) {
    int     parsed_lit, var;
    lits.clear();
    for (;;){
        parsed_lit = parseInt(in);
        if (parsed_lit == 0) break;
        var = abs(parsed_lit)-1;
        while (var >= S.nVars()) S.newVar();
        lits.push( (parsed_lit > 0) ? Lit(var) : ~Lit(var) );
    }
}

template<class B>
static bool match(B& in, char* str) {
    for (; *str != 0; ++str, ++in)
        if (*str != *in)
            return false;
    return true;
}

template<class B>
static void parse_DIMACS_main(B& in, Solver& S) {
    vec<Lit> lits;
    for (;;){
        skipWhitespace(in);
        if (*in == EOF)
            break;
        else if (*in == 'p'){
            if (match(in, "p cnf")){
                int vars    = parseInt(in);
                int clauses = parseInt(in);
                reportf("|  Number of variables:  %-12d                                         |\n", vars);
                reportf("|  Number of clauses:    %-12d                                         |\n", clauses);
            }else{
                reportf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
            }
        } else if (*in == 'c' || *in == 'p')
            skipLine(in);
        else
            readClause(in, S, lits),
            S.addClause(lits);
    }
}

// Inserts problem into solver.
//
static void parse_DIMACS(FILE* input_stream, Solver& S) {
    StreamBuffer in(input_stream);
    parse_DIMACS_main(in, S); }

//=================================================================================================

void printStats(Solver& solver)
{
    double   cpu_time = cpuTime();
    uint64_t mem_used = memUsed();
    reportf("restarts              : %lld\n", solver.starts);
    reportf("conflicts             : %-12lld   (%.0f /sec)\n", solver.conflicts   , solver.conflicts   /cpu_time);
    reportf("decisions             : %-12lld   (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions   /cpu_time);
    reportf("propagations          : %-12lld   (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
    reportf("conflict literals     : %-12lld   (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
    if (mem_used != 0) reportf("Memory used           : %.2f MB\n", mem_used / 1048576.0);
    reportf("CPU time              : %g s\n", cpu_time);
}

Solver* solver;
static void SIGINT_handler(int signum) {
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    printStats(*solver);
    reportf("\n"); reportf("*** INTERRUPTED ***\n");
    exit(1); }

//=================================================================================================
// Main:

void printUsage(char** argv)
{
    reportf("USAGE: %s [options] <input-file> <result-output-file>\n\n  where input may be either in plain or gzipped DIMACS.\n\n", argv[0]);
    reportf("OPTIONS:\n\n");
    reportf("  -polarity-mode = {true,false,rnd}\n");
    reportf("  -decay         = <num> [ 0 - 1 ]\n");
    reportf("  -rnd-freq      = <num> [ 0 - 1 ]\n");
    reportf("  -verbosity     = {0,1,2}\n");
    reportf("\n");
}

const char* hasPrefix(const char* str, const char* prefix)
{
    int len = strlen(prefix);
    if (strncmp(str, prefix, len) == 0)
        return str + len;
    else
        return NULL;
}

int main(int argc, char** argv)
{
    Solver      S;
    S.verbosity = 1;

    /*int         i, j;
    const char* value;
    for (i = j = 0; i < argc; i++){
        if ((value = hasPrefix(argv[i], "-polarity-mode="))){
            if (strcmp(value, "true") == 0)
                S.polarity_mode = Solver::polarity_true;
            else if (strcmp(value, "false") == 0)
                S.polarity_mode = Solver::polarity_false;
            else if (strcmp(value, "rnd") == 0)
                S.polarity_mode = Solver::polarity_rnd;
            else{
                reportf("ERROR! unknown polarity-mode %s\n", value);
                exit(0); }

        }else if ((value = hasPrefix(argv[i], "-rnd-freq="))){
            double rnd;
            if (sscanf(value, "%lf", &rnd) <= 0 || rnd < 0 || rnd > 1){
                reportf("ERROR! illegal rnd-freq constant %s\n", value);
                exit(0); }
            S.random_var_freq = rnd;

        }else if ((value = hasPrefix(argv[i], "-decay="))){
            double decay;
            if (sscanf(value, "%lf", &decay) <= 0 || decay <= 0 || decay > 1){
                reportf("ERROR! illegal decay constant %s\n", value);
                exit(0); }
            S.var_decay = 1 / decay;

        }else if ((value = hasPrefix(argv[i], "-verbosity="))){
            int verbosity = (int)strtol(value, NULL, 10);
            if (verbosity == 0 && errno == EINVAL){
                reportf("ERROR! illegal verbosity level %s\n", value);
                exit(0); }
            S.verbosity = verbosity;

        }else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0){
            printUsage(argv);
            exit(0);

        }else if (strncmp(argv[i], "-", 1) == 0){
            reportf("ERROR! unknown flag %s\n", argv[i]);
            exit(0);

        }else
            argv[j++] = argv[i];
    }
    argc = j;
    */

    reportf("This is MiniSat 2.0 beta\n");
#if defined(__linux__)
    fpu_control_t oldcw, newcw;
    _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
    reportf("WARNING: for repeatability, setting FPU to use double precision\n");
#endif
    double cpu_time = cpuTime();

    solver = &S;
    FILE* in = fopen(argv[1], "rb");
    reportf("============================[ Problem Statistics ]=============================\n");
    reportf("|                                                                             |\n");

    parse_DIMACS(in, S);
    fclose(in);
    double parse_time = cpuTime() - cpu_time;
    reportf("|  Parsing time:         %-12.2f s                                       |\n", parse_time);

    if (!S.simplify()){
        reportf("Solved by unit propagation\n");
        printf("UNSATISFIABLE\n");
        exit(20);
    }

    bool ret = S.solve();
    printStats(S);
    reportf("\n");
    printf(ret ? "SATISFIABLE\n" : "UNSATISFIABLE\n");
    if (ret){
        printf("v ");
        for (int i = 0; i < S.nVars(); i++)
            if (S.model[i] != l_Undef)
                printf("%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
        printf(" 0\n");
    }else {
        printf("UNSAT\n");
    }

    return (ret ? 10 : 20);     // (faster than "return", which will invoke the destructor for 'Solver')
}
<|endoftext|>