<commit_before>/*************************************************************************
 *
 *  $RCSfile: StorageNativeOutputStream.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 09:41:52 $
 *
 *  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): Ocke Janssen
 *
 *
 ************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif

#include "StorageNativeOutputStream.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/component_context.hxx"

#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.h"
#include "hsqldb/HStorageMap.hxx"

#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"

#include <rtl/logfile.hxx>

using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */

#define ThrowException(env, type, msg) { \
    env->ThrowNew(env->FindClass(type), msg); }

// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    openStream
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream
  (JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)
{
#if OSL_DEBUG_LEVEL > 1
    {
        ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
        sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".output"));
        ::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);
        getStreams()[sOrgName] = fopen( sName.getStr(), "a+" );
    }
#endif
    StorageContainer::registerStream(env,name,key,mode);
}
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII
  (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
    Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,off,len);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;[B)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B
  (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)
{
    Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,0,env->GetArrayLength(buffer));
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    close
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
    Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
    if ( xFlush.is() )
        try
        {
            xFlush->flush();
        }
        catch(Exception&)
        {}

#if OSL_DEBUG_LEVEL > 1
    {
        ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
        sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".output"));
        fclose( getStreams()[sOrgName] );
        getStreams().erase(sOrgName);
    }
#endif
    StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I
  (JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)
{
    Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_writeInt(env,obj_this,name,key,b);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    flush
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    sync
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
    TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(StorageContainer::jstring2ustring(env,key));
    Reference<XTransactedObject> xTrans(aStoragePair.first.first,UNO_QUERY);
    if ( xTrans.is() )
    {
        try
        {
            TStreamMap::iterator aIter = aStoragePair.second.begin();
            TStreamMap::iterator aEnd = aStoragePair.second.end();
            for (;aIter != aEnd ; ++aIter)
            {
                ::boost::shared_ptr<StreamHelper> pHelper = aIter->second;
                Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
                if ( xFlush.is() )
                    try
                    {
                        xFlush->flush();
                    }
                    catch(Exception&)
                    {}
            }
            xTrans->commit();
        }
        catch(Exception& e)
        {
            OSL_ENSURE(0,"Exception catched! : sync();");
            StorageContainer::throwJavaException(e,env);
        }
    }
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba28 (1.3.22); FILE MERGED 2005/03/23 14:58:43 fs 1.3.22.2: #i45314# implement sync as flush, but *without* commit 2005/03/21 12:53:34 fs 1.3.22.1: copying the changes from CWS dba26 herein, since they're needed to fix i45314<commit_after>/*************************************************************************
 *
 *  $RCSfile: StorageNativeOutputStream.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-30 11:52:17 $
 *
 *  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): Ocke Janssen
 *
 *
 ************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif

#include "StorageNativeOutputStream.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/component_context.hxx"

#ifndef CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
#include "accesslog.hxx"
#endif

#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.hxx"
#include "hsqldb/HStorageMap.hxx"

#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"

using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */

#define ThrowException(env, type, msg) { \
    env->ThrowNew(env->FindClass(type), msg); }

// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    openStream
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream
  (JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)
{
#if OSL_DEBUG_LEVEL > 1
    {
        OperationLogFile( env, name, "output" ).logOperation( "openStream" );
        LogFile( env, name, "output" ).create();
    }
#endif
    StorageContainer::registerStream(env,name,key,mode);
}
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;[BII)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII
  (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile( env, name, "output" ).logOperation( "write( byte[], int, int )" );

    DataLogFile aDataLog( env, name, "output" );
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );
#else
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len );
#endif
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;[B)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B
  (JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile( env, name, "output" ).logOperation( "write( byte[] )" );

    DataLogFile aDataLog( env, name, "output" );
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ), &aDataLog );
#else
    write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ) );
#endif
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    close
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile aOpLog( env, name, "output" );
    aOpLog.logOperation( "close" );

    LogFile aDataLog( env, name, "output" );
#endif

    ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
    Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
    if ( xFlush.is() )
        try
        {
            xFlush->flush();
        }
        catch(Exception&)
        {}

#if OSL_DEBUG_LEVEL > 1
    aDataLog.close();
    aOpLog.close();
#endif
    StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    write
 * Signature: (Ljava/lang/String;Ljava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I
  (JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile( env, name, "output" ).logOperation( "write( int )" );

    DataLogFile aDataLog( env, name, "output" );
    write_to_storage_stream( env, obj_this, name, key, b, &aDataLog );
#else
    write_to_storage_stream( env, obj_this, name, key, b );
#endif
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    flush
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile( env, name, "output" ).logOperation( "flush" );
#endif
}
// -----------------------------------------------------------------------------
/*
 * Class:     com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
 * Method:    sync
 * Signature: (Ljava/lang/String;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync
  (JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
    OperationLogFile( env, name, "output" ).logOperation( "sync" );
#endif
    ::boost::shared_ptr< StreamHelper > pStream = StorageContainer::getRegisteredStream( env, name, key );
    Reference< XOutputStream > xFlush = pStream.get() ? pStream->getOutputStream() : Reference< XOutputStream>();
    OSL_ENSURE( xFlush.is(), "StorageNativeOutputStream::sync: could not retrieve an output stream!" );
    if ( xFlush.is() )
    {
        try
        {
            xFlush->flush();
        }
        catch(Exception&)
        {
            OSL_ENSURE( false, "StorageNativeOutputStream::sync: could not flush output stream!" );
        }
    }
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2009
 *
 * School of Computing, University of Utah,
 * Salt Lake City, UT 84112, USA
 *
 * and the Gauss Group
 * http://www.cs.utah.edu/formal_verification
 *
 * See LICENSE for licensing information
 */

/*
 * ISP: MPI Dynamic Verification Tool
 *
 * File:        Transition.hpp
 * Description: Implements handling of a single transition in an interleaving
 * Contact:     isp-dev@cs.utah.edu
 */

#ifndef _CB_HPP
#define _CB_HPP
/*
#include "Envelope.hpp"
#include <vector>
#include <cassert>
*/
/*
 * This implements a single transition
 */
class CB {
public:
    int _pid;
    int _index;
    CB () { }

    CB (int i, int ind) : _pid(i), _index(ind) {
    }
    CB(const CB& c) : _pid(c._pid), _index(c._index){}
    bool operator== (const CB &c) {
        return _pid == c._pid && _index == c._index;
    }
    bool operator!= (const CB &c) {
        return !(*this == c);
    }
    friend bool operator< (const CB &a, const CB &b) {
        return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);
    }
    /*
    CB& operator= (const CB &c) {
        this->_pid = c._pid;
        this->_index = c._index;
        return *this;
    }*/
    std::unique_ptr<CB> Copy() {
        std::unique_ptr<CB> ptr(new CB(*this));
        return std::move(ptr);
    }
};

#endif
<commit_msg>Changed method names to be more consistent.<commit_after>/*
 * Copyright (c) 2008-2009
 *
 * School of Computing, University of Utah,
 * Salt Lake City, UT 84112, USA
 *
 * and the Gauss Group
 * http://www.cs.utah.edu/formal_verification
 *
 * See LICENSE for licensing information
 */

/*
 * ISP: MPI Dynamic Verification Tool
 *
 * File:        Transition.hpp
 * Description: Implements handling of a single transition in an interleaving
 * Contact:     isp-dev@cs.utah.edu
 */

#ifndef _CB_HPP
#define _CB_HPP
/*
#include "Envelope.hpp"
#include <vector>
#include <cassert>
*/
/*
 * This implements a single transition
 */
class CB {
public:
    int _pid;
    int _index;
    CB () { }

    CB (int i, int ind) : _pid(i), _index(ind) {
    }
    CB(const CB& c) : _pid(c._pid), _index(c._index){}
    bool operator== (const CB &c) {
        return _pid == c._pid && _index == c._index;
    }
    bool operator!= (const CB &c) {
        return !(*this == c);
    }
    friend bool operator< (const CB &a, const CB &b) {
        return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);
    }
    /*
    CB& operator= (const CB &c) {
        this->_pid = c._pid;
        this->_index = c._index;
        return *this;
    }*/
    std::unique_ptr<CB> copy() {
        std::unique_ptr<CB> ptr(new CB(*this));
        return std::move(ptr);
    }
};

#endif
<|endoftext|>


<commit_before>#include "UnrealCVPrivate.h"
#include "ViewMode.h"
#include "BufferVisualizationData.h"

/**
FViewMode is a helper class to tweak render options. Important options are
	Tonemapper
	EyeAdaptation
	TemporalAA
	MotionBlur
	Lighting
	Bloom
	ColorGrading
	GammaCorrection
	DepthOfField
	LensFlare
	Vignette
*/

void BasicSetting(FEngineShowFlags& ShowFlags)
{
	ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);
	ShowFlags.SetRendering(true);
	ShowFlags.SetStaticMeshes(true);
	ShowFlags.SetLandscape(true);
	ShowFlags.SetInstancedFoliage(true);
	ShowFlags.SetInstancedGrass(true);
	ShowFlags.SetInstancedStaticMeshes(true);
	ShowFlags.SetSkeletalMeshes(true);
}

void FViewMode::Lit(FEngineShowFlags& ShowFlags)
{
	BasicSetting(ShowFlags);
	ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
	ApplyViewMode(VMI_Lit, true, ShowFlags);
	ShowFlags.SetMaterials(true);
	ShowFlags.SetLighting(true);
	ShowFlags.SetPostProcessing(true);
	// ToneMapper needs to be enabled, otherwise the screen will be very dark
	ShowFlags.SetTonemapper(true);
	// TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.
	// Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail

	// ShowFlags.SetTemporalAA(true);
	ShowFlags.SetTemporalAA(false);
	ShowFlags.SetAntiAliasing(true);
	ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture
}

void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
	// EngineShowFlagOverride()

	// From ShowFlags.cpp
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetMaterials(true);
	ShowFlags.SetVisualizeBuffer(true);

	// ToneMapper needs to be disabled
	ShowFlags.SetTonemapper(false);
	// TemporalAA needs to be disabled, or it will contaminate the following frame
	ShowFlags.SetTemporalAA(false);
}

/** ViewMode showing post process */
void FViewMode::PostProcess(FEngineShowFlags& ShowFlags)
{
	BasicSetting(ShowFlags);
	// These are minimal setting
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetPostProcessMaterial(true);
	// ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal

	GVertexColorViewMode = EVertexColorViewMode::Color;
}

void FViewMode::Wireframe(FEngineShowFlags& ShowFlags)
{
	// ApplyViewMode(VMI_Wireframe, true, ShowFlags);
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetWireframe(true);
}

void FViewMode::VertexColor(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(VMI_Lit, true, ShowFlags);

	// From MeshPaintEdMode.cpp:2942
	ShowFlags.SetMaterials(false);
	ShowFlags.SetLighting(false);
	ShowFlags.SetBSPTriangles(true);
	ShowFlags.SetVertexColors(true);
	ShowFlags.SetPostProcessing(false);
	ShowFlags.SetHMDDistortion(false);
	ShowFlags.SetTonemapper(false); // This won't take effect here

	GVertexColorViewMode = EVertexColorViewMode::Color;
}

void FViewMode::Unlit(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(VMI_Unlit, true, ShowFlags);
	ShowFlags.SetMaterials(false);
	ShowFlags.SetVertexColors(false);
	ShowFlags.SetLightFunctions(false);
	ShowFlags.SetLighting(false);
	ShowFlags.SetAtmosphericFog(false);
}
<commit_msg>Enable materials flag in the ShowFlags, so that the leaves will be accurately displayed in the depth and normal ground truth.<commit_after>#include "UnrealCVPrivate.h"
#include "ViewMode.h"
#include "BufferVisualizationData.h"

/**
FViewMode is a helper class to tweak render options. Important options are
	Tonemapper
	EyeAdaptation
	TemporalAA
	MotionBlur
	Lighting
	Bloom
	ColorGrading
	GammaCorrection
	DepthOfField
	LensFlare
	Vignette
*/

void BasicSetting(FEngineShowFlags& ShowFlags)
{
	ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);
	ShowFlags.SetRendering(true);
	ShowFlags.SetStaticMeshes(true);
	ShowFlags.SetLandscape(true);

	ShowFlags.SetMaterials(true); // Important for the correctness of tree leaves.

	ShowFlags.SetInstancedFoliage(true);
	ShowFlags.SetInstancedGrass(true);
	ShowFlags.SetInstancedStaticMeshes(true);
	ShowFlags.SetSkeletalMeshes(true);

	// ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
	// ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
}

void FViewMode::Lit(FEngineShowFlags& ShowFlags)
{
	BasicSetting(ShowFlags);
	ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
	ApplyViewMode(VMI_Lit, true, ShowFlags);
	ShowFlags.SetMaterials(true);
	ShowFlags.SetLighting(true);
	ShowFlags.SetPostProcessing(true);
	// ToneMapper needs to be enabled, otherwise the screen will be very dark
	ShowFlags.SetTonemapper(true);
	// TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.
	// Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail

	// ShowFlags.SetTemporalAA(true);
	ShowFlags.SetTemporalAA(false);
	ShowFlags.SetAntiAliasing(true);
	ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture
}

void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
	// EngineShowFlagOverride()

	// From ShowFlags.cpp
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetMaterials(true);
	ShowFlags.SetVisualizeBuffer(true);

	// ToneMapper needs to be disabled
	ShowFlags.SetTonemapper(false);
	// TemporalAA needs to be disabled, or it will contaminate the following frame
	ShowFlags.SetTemporalAA(false);
}

/** ViewMode showing post process */
void FViewMode::PostProcess(FEngineShowFlags& ShowFlags)
{
	BasicSetting(ShowFlags);
	// These are minimal setting
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetPostProcessMaterial(true);
	// ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal

	GVertexColorViewMode = EVertexColorViewMode::Color;
}

void FViewMode::Wireframe(FEngineShowFlags& ShowFlags)
{
	// ApplyViewMode(VMI_Wireframe, true, ShowFlags);
	ShowFlags.SetPostProcessing(true);
	ShowFlags.SetWireframe(true);
}

void FViewMode::VertexColor(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(VMI_Lit, true, ShowFlags);

	// From MeshPaintEdMode.cpp:2942
	ShowFlags.SetMaterials(false);
	ShowFlags.SetLighting(false);
	ShowFlags.SetBSPTriangles(true);
	ShowFlags.SetVertexColors(true);
	ShowFlags.SetPostProcessing(false);
	ShowFlags.SetHMDDistortion(false);
	ShowFlags.SetTonemapper(false); // This won't take effect here

	GVertexColorViewMode = EVertexColorViewMode::Color;
}

void FViewMode::Unlit(FEngineShowFlags& ShowFlags)
{
	ApplyViewMode(VMI_Unlit, true, ShowFlags);
	ShowFlags.SetMaterials(false);
	ShowFlags.SetVertexColors(false);
	ShowFlags.SetLightFunctions(false);
	ShowFlags.SetLighting(false);
	ShowFlags.SetAtmosphericFog(false);
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>

#include <string>
#include <cstring>

#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>

namespace asgard {

const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;

struct driver_connector {
    //Buffer
    char write_buffer[buffer_size];
    char receive_buffer[buffer_size];

    // The socket file descriptor
    int socket_fd;

    // The socket addresses
    struct sockaddr_un client_address;
    struct sockaddr_un server_address;
};

bool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){
    // Open the socket
    driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if(driver.socket_fd < 0){
        std::cerr << "asgard:driversystem: socket() failed" << std::endl;
        return false;
    }

    // Init the client address
    memset(&driver.client_address, 0, sizeof(struct sockaddr_un));
    driver.client_address.sun_family = AF_UNIX;
    snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);

    // Unlink the client socket
    unlink(client_socket_path);

    // Bind to client socket
    if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){
        std::cerr << "asgard:driver: bind() failed" << std::endl;
        return false;
    }

    // Init the server address
    memset(&driver.server_address, 0, sizeof(struct sockaddr_un));
    driver.server_address.sun_family = AF_UNIX;
    snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);

    return true;
}

int register_source(driver_connector& driver, const std::string& source_name){
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the source
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto source_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote source: " << source_id << std::endl;

    return source_id;
}

int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the sensor
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto sensor_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;

    return sensor_id;
}

void send_data(driver_connector& driver, int source_id, int sensor_id, double value){
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}

void unregister_sensor(driver_connector& driver, int source_id, int sensor_id){
    // Unregister the sensor, if necessary
    if(sensor_id >= 0){
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
    }
}

void unregister_source(driver_connector& driver, int source_id){
    // Unregister the source, if necessary
    if(source_id >= 0){
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
    }
}

} //end of namespace asgard
<commit_msg>Add revoke_root utility<commit_after>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>

#include <string> #include <cstring>

#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>

namespace asgard {

const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;

struct driver_connector {
    //Buffer
    char write_buffer[buffer_size];
    char receive_buffer[buffer_size];

    // The socket file descriptor
    int socket_fd;

    // The socket addresses
    struct sockaddr_un client_address;
    struct sockaddr_un server_address;
};

bool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){
    // Open the socket
    driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
    if(driver.socket_fd < 0){
        std::cerr << "asgard:driversystem: socket() failed" << std::endl;
        return false;
    }

    // Init the client address
    memset(&driver.client_address, 0, sizeof(struct sockaddr_un));
    driver.client_address.sun_family = AF_UNIX;
    snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);

    // Unlink the client socket
    unlink(client_socket_path);

    // Bind to client socket
    if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){
        std::cerr << "asgard:driver: bind() failed" << std::endl;
        return false;
    }

    // Init the server address
    memset(&driver.server_address, 0, sizeof(struct sockaddr_un));
    driver.server_address.sun_family = AF_UNIX;
    snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);

    return true;
}

int register_source(driver_connector& driver, const std::string& source_name){
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the source
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto source_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote source: " << source_id << std::endl;

    return source_id;
}

int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){
    socklen_t address_length = sizeof(struct sockaddr_un);

    // Register the sensor
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));

    auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
    driver.receive_buffer[bytes_received] = '\0';

    auto sensor_id = atoi(driver.receive_buffer);

    std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;

    return sensor_id;
}

void send_data(driver_connector& driver, int source_id, int sensor_id, double value){
    // Send the data
    auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
    sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}

void unregister_sensor(driver_connector& driver, int source_id, int sensor_id){
    // Unregister the sensor, if necessary
    if(sensor_id >= 0){
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
    }
}

void unregister_source(driver_connector& driver, int source_id){
    // Unregister the source, if necessary
    if(source_id >= 0){
        auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
        sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
    }
}

bool revoke_root(){
    if (getuid() == 0) {
        if (setgid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
            return false;
        }

        if (setuid(1000) != 0){
            std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
            return false;
        }
    }

    if (setuid(0) != -1){
        std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
        return false;
    }

    return true;
}

} //end of namespace asgard
<|endoftext|>


<commit_before>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * adplug.cpp - CAdPlug helper class implementation, by Simon Peter <dn.tlp@gmx.net>
 */

/***** Includes *****/

#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string>

#include "adplug.h"
#include "debug.h"

/***** Replayer includes *****/

#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#include "mkj.h"
#include "dfm.h"
#include "lds.h"
#include "bam.h"
#include "fmc.h"
#include "bmf.h"
#include "flash.h"
#include "hyp.h"
#include "psi.h"
#include "rat.h"
#include "hybrid.h"
#include "mad.h"
#include "adtrack.h"

// These players use C++ templates, which aren't supported by WATCOM C++
#ifndef __WATCOMC__
#include "u6m.h"
#include "rol.h"
#endif

/***** Defines *****/

#define VERSION		"1.3"		// AdPlug library version string

/***** Static variables initializers *****/

const unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};
const unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};

/***** List of all players that come in the standard AdPlug distribution *****/

// WARNING: The order of this list is on purpose! AdPlug tries the players in
// this order, which is to be preserved, because some players take precedence
// above other players.
// The list is terminated with an all-NULL element.
static const struct Players {
  CPlayer *(*factory) (Copl *newopl);
} allplayers[] = {
  {CmidPlayer::factory}, {CksmPlayer::factory},
#ifndef __WATCOMC__
  {CrolPlayer::factory},
#endif
  {CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},
  {CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},
  {Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},
  {CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},
  {CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},
  {CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},
  {CmadLoader::factory},
#ifndef __WATCOMC__
  {Cu6mPlayer::factory},
#endif
  {Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},
  {CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},
  {0}
};

/***** Public methods *****/

CPlayer *CAdPlug::factory(const char *fn, Copl *opl)
{
	ifstream f(fn, ios::in | ios::binary);

	if(!f.is_open()) return 0;
	return factory(f,opl,fn);
}

CPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)
{
  CPlayer *p;
  unsigned int i;

  LogWrite("*** CAdPlug::factory(f,opl,\"%s\") ***\n",fn);

  for(i=0;allplayers[i].factory;i++) {
    LogWrite("Trying: %d\n",i);
    if((p = allplayers[i].factory(opl)))
      if(p->load(f,fn)) {
	LogWrite("got it!\n");
	LogWrite("--- CAdPlug::factory ---\n");
	return p;
      } else {
	delete p;
	f.seekg(0);
      }
  }

  LogWrite("End of list!\n");
  LogWrite("--- CAdPlug::factory ---\n");
  return 0;
}

unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
	float	slength = 0.0f;

	// get song length
	p->rewind(subsong);
	while(p->update() && slength < 600000)	// song length limit: 10 minutes
		slength += 1000/p->getrefresh();
	p->rewind(subsong);

	return (unsigned long)slength;
}

void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
	float pos = 0.0f;

	p->rewind();
	while(pos < ms && p->update())		// seek to new position
		pos += 1000/p->getrefresh();
}

std::string CAdPlug::get_version()
{
  return std::string(VERSION);
}

void CAdPlug::debug_output(std::string filename)
{
  LogFile(filename.c_str());
  LogWrite("CAdPlug::debug_output(\"%s\"): Redirected.\n",filename.c_str());
}
<commit_msg>CFF loader support<commit_after>/*
 * Adplug - Replayer for many OPL2/OPL3 audio file formats.
 * Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * adplug.cpp - CAdPlug helper class implementation, by Simon Peter <dn.tlp@gmx.net>
 */

/***** Includes *****/

#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string>

#include "adplug.h"
#include "debug.h"

/***** Replayer includes *****/

#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#include "mkj.h"
#include "dfm.h"
#include "lds.h"
#include "bam.h"
#include "fmc.h"
#include "bmf.h"
#include "flash.h"
#include "hyp.h"
#include "psi.h"
#include "rat.h"
#include "hybrid.h"
#include "mad.h"
#include "adtrack.h"
#include "cff.h"

// These players use C++ templates, which aren't supported by WATCOM C++
#ifndef __WATCOMC__
#include "u6m.h"
#include "rol.h"
#endif

/***** Defines *****/

#define VERSION		"1.3"		// AdPlug library version string

/***** Static variables initializers *****/

const unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};
const unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};

/***** List of all players that come in the standard AdPlug distribution *****/

// WARNING: The order of this list is on purpose! AdPlug tries the players in
// this order, which is to be preserved, because some players take precedence
// above other players.
// The list is terminated with an all-NULL element.
static const struct Players {
  CPlayer *(*factory) (Copl *newopl);
} allplayers[] = {
  {CmidPlayer::factory}, {CksmPlayer::factory},
#ifndef __WATCOMC__
  {CrolPlayer::factory},
#endif
  {CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},
  {CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},
  {Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},
  {CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},
  {CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},
  {CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},
  {CmadLoader::factory}, {CcffLoader::factory},
#ifndef __WATCOMC__
  {Cu6mPlayer::factory},
#endif
  {Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},
  {CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},
  {0}
};

/***** Public methods *****/

CPlayer *CAdPlug::factory(const char *fn, Copl *opl)
{
	ifstream f(fn, ios::in | ios::binary);

	if(!f.is_open()) return 0;
	return factory(f,opl,fn);
}

CPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)
{
  CPlayer *p;
  unsigned int i;

  LogWrite("*** CAdPlug::factory(f,opl,\"%s\") ***\n",fn);

  for(i=0;allplayers[i].factory;i++) {
    LogWrite("Trying: %d\n",i);
    if((p = allplayers[i].factory(opl)))
      if(p->load(f,fn)) {
	LogWrite("got it!\n");
	LogWrite("--- CAdPlug::factory ---\n");
	return p;
      } else {
	delete p;
	f.seekg(0);
      }
  }

  LogWrite("End of list!\n");
  LogWrite("--- CAdPlug::factory ---\n");
  return 0;
}

unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
	float	slength = 0.0f;

	// get song length
	p->rewind(subsong);
	while(p->update() && slength < 600000)	// song length limit: 10 minutes
		slength += 1000/p->getrefresh();
	p->rewind(subsong);

	return (unsigned long)slength;
}

void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
	float pos = 0.0f;

	p->rewind();
	while(pos < ms && p->update())		// seek to new position
		pos += 1000/p->getrefresh();
}

std::string CAdPlug::get_version()
{
  return std::string(VERSION);
}

void CAdPlug::debug_output(std::string filename)
{
  LogFile(filename.c_str());
  LogWrite("CAdPlug::debug_output(\"%s\"): Redirected.\n",filename.c_str());
}
<|endoftext|>


<commit_before>#include "GurobiSolver.h"

#include <Eigen/Core>
#include "gurobi_c++.h"

#include "Optimization.h"
#include "drake/common/drake_assert.h"

namespace drake {
namespace solvers {

bool GurobiSolver::available() const { return true; }

// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
//    Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
//    sparseA.makeCompressed();
//    error =  GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
//                           sparseA.InnerIndices(), sparseA.OuterStarts(),
//                           sparseA.Values(),sense, b.data(), NULL);
//    return(error);

template <typename DerivedA, typename DerivedB>
int myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase<DerivedA> const& A,
                    Eigen::MatrixBase<DerivedB> const& b, char sense,
                    double sparseness_threshold = 1e-14) {
  int error = 0, nnz = 0;

  std::vector<int> cind(A.cols(), 0);
  std::vector<double> cval(A.cols(), 0.0);

  for (size_t i = 0; i < A.rows(); i++) {
    nnz = 0;
    for (size_t j = 0; j < A.cols(); j++) {
      if (std::abs(A(i, j)) > sparseness_threshold) {
        cval[nnz] = A(i, j);
        cind[nnz++] = j;
      }
    }
    error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);
    if (error) break;
  }
  return error;
}

SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
  // We only process quadratic costs and linear / bounding box
  // constraints

  GRBenv* env = NULL;
  GRBloadenv(&env, NULL);
  // Corresponds to no console or file logging.
  GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);

  DRAKE_ASSERT(prog.generic_costs().empty());
  DRAKE_ASSERT(prog.generic_constraints().empty());

  Eigen::VectorXd solution(prog.num_vars());
  int num_vars = prog.num_vars();

  // bound constraints
  std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
  std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());

  for (auto const& binding : prog.bounding_box_constraints()) {
    auto const& c = binding.constraint();
    const Eigen::VectorXd& lower_bound = c->lower_bound();
    const Eigen::VectorXd& upper_bound = c->upper_bound();
    for (const DecisionVariableView& v : binding.variable_list()) {
      for (size_t k = 0; k < v.size(); k++) {
        const int idx = v.index() + k;
        xlow[idx] = std::max(lower_bound(k), xlow[idx]);
        xupp[idx] = std::min(upper_bound(k), xupp[idx]);
      }
    }
  }

  int error = 0;
  GRBmodel* model = NULL;
  double sparseness_threshold = 1e-14;

  GRBnewmodel(env, &model, "QP", num_vars, NULL, &xlow[0], &xupp[0], NULL,
              NULL);

  int start_row = 0;
  int num_constraint_vars = 0;
  double individual_quadratic_cost_value = 0.0;
  int row_ind = 0, col_ind = 0;

  for (auto const& binding : prog.quadratic_costs()) {
    auto const& c = binding.constraint();

    num_constraint_vars = binding.GetNumElements();

    Eigen::MatrixXd Q = 0.5 * (c->Q());
    Eigen::VectorXd b = c->b();

    // Check for square matrices
    DRAKE_ASSERT(Q.rows() == Q.cols());
    // Check for symmetric matrices
    DRAKE_ASSERT(Q.transpose() == Q);
    // Check for Quadratic and Linear Cost dimensions
    DRAKE_ASSERT(Q.rows() == num_constraint_vars);
    DRAKE_ASSERT(b.cols() == 1);
    DRAKE_ASSERT(b.rows() == num_constraint_vars);

    // adding each Q term (only upper triangular)
    for (size_t i = 0; i < num_constraint_vars; i++) {
      for (size_t j = i; j < num_constraint_vars; j++) {
        if (std::abs(Q(i, j)) > sparseness_threshold) {
          row_ind = i + start_row;
          col_ind = j + start_row;
          // TODO(naveenoid) : Port to batch addition mode of this function
          // by utilising the Upper right (or lower left) triangular matrix.
          // The single element addition method used below is recommended
          // initiall by Gurobi since it has a low cost
          individual_quadratic_cost_value = Q(i, j);
          error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
                                &individual_quadratic_cost_value);
        }
      }
    }
    GRBsetdblattrarray(model, "Obj", start_row, num_constraint_vars, b.data());
    start_row = start_row + Q.rows();
  }

  // TODO(naveenoid) : needs test coverage
  for (auto const& binding : prog.linear_equality_constraints()) {
    auto const& c = binding.constraint();
    myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);
  }

  for (auto const& binding : prog.linear_constraints()) {
    auto const& c = binding.constraint();

    if (c->lower_bound() !=
        -Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,
                                   std::numeric_limits<double>::infinity())) {
      myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,
                      1e-18);
    }
    if (c->upper_bound() !=
        Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,
                                  std::numeric_limits<double>::infinity())) {
      myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);
    }
  }

  SolutionResult result = SolutionResult::kSolutionFound;

  error = GRBoptimize(model);

  int optimstatus;
  double objval;

  if (error) {
    // TODO(naveenoid) : log error message using GRBgeterrormsg(env)
    result = SolutionResult::kInvalidInput;
  } else {
    error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
    error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);

    if (optimstatus != GRB_OPTIMAL) {
      if (optimstatus == GRB_INF_OR_UNBD) {
        result = SolutionResult::kInfeasibleConstraints;
      } else {
        result = SolutionResult::kUnknownError;
      }
    }
  }

  Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);

  GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
  prog.SetDecisionVariableValues(sol_vector);

  prog.SetSolverResult("Gurobi", 0);

  GRBfreemodel(model);
  GRBfreeenv(env);

  return result;
}

}  // namespace drake
}  // namespace solvers
<commit_msg>initialization of some variables<commit_after>#include "GurobiSolver.h"

#include <Eigen/Core>
#include "gurobi_c++.h"

#include "Optimization.h"
#include "drake/common/drake_assert.h"

namespace drake {
namespace solvers {

bool GurobiSolver::available() const { return true; }

// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
//    Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
//    sparseA.makeCompressed();
//    error =  GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
//                           sparseA.InnerIndices(), sparseA.OuterStarts(),
//                           sparseA.Values(),sense, b.data(), NULL);
//    return(error);

template <typename DerivedA, typename DerivedB>
int myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase<DerivedA> const& A,
                    Eigen::MatrixBase<DerivedB> const& b, char sense,
                    double sparseness_threshold = 1e-14) {
  int error = 0, nnz = 0;

  std::vector<int> cind(A.cols(), 0);
  std::vector<double> cval(A.cols(), 0.0);

  for (size_t i = 0; i < A.rows(); i++) {
    nnz = 0;
    for (size_t j = 0; j < A.cols(); j++) {
      if (std::abs(A(i, j)) > sparseness_threshold) {
        cval[nnz] = A(i, j);
        cind[nnz++] = j;
      }
    }
    error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);
    if (error) break;
  }
  return error;
}

SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
  // We only process quadratic costs and linear / bounding box
  // constraints

  GRBenv* env = NULL;
  GRBloadenv(&env, NULL);
  // Corresponds to no console or file logging.
  GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);

  DRAKE_ASSERT(prog.generic_costs().empty());
  DRAKE_ASSERT(prog.generic_constraints().empty());

  Eigen::VectorXd solution(prog.num_vars());
  int num_vars = prog.num_vars();

  // bound constraints
  std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
  std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());

  for (auto const& binding : prog.bounding_box_constraints()) {
    auto const& c = binding.constraint();
    const Eigen::VectorXd& lower_bound = c->lower_bound();
    const Eigen::VectorXd& upper_bound = c->upper_bound();
    for (const DecisionVariableView& v : binding.variable_list()) {
      for (size_t k = 0; k < v.size(); k++) {
        const int idx = v.index() + k;
        xlow[idx] = std::max(lower_bound(k), xlow[idx]);
        xupp[idx] = std::min(upper_bound(k), xupp[idx]);
      }
    }
  }

  int error = 0;
  GRBmodel* model = NULL;
  double sparseness_threshold = 1e-14;

  GRBnewmodel(env, &model, "QP", num_vars, NULL, &xlow[0], &xupp[0], NULL,
              NULL);

  int start_row = 0;
  int num_constraint_vars = 0;
  double individual_quadratic_cost_value = 0.0;
  int row_ind = 0, col_ind = 0;

  for (auto const& binding : prog.quadratic_costs()) {
    auto const& c = binding.constraint();

    num_constraint_vars = binding.GetNumElements();

    Eigen::MatrixXd Q = 0.5 * (c->Q());
    Eigen::VectorXd b = c->b();

    // Check for square matrices
    DRAKE_ASSERT(Q.rows() == Q.cols());
    // Check for symmetric matrices
    DRAKE_ASSERT(Q.transpose() == Q);
    // Check for Quadratic and Linear Cost dimensions
    DRAKE_ASSERT(Q.rows() == num_constraint_vars);
    DRAKE_ASSERT(b.cols() == 1);
    DRAKE_ASSERT(b.rows() == num_constraint_vars);

    // adding each Q term (only upper triangular)
    for (size_t i = 0; i < num_constraint_vars; i++) {
      for (size_t j = i; j < num_constraint_vars; j++) {
        if (std::abs(Q(i, j)) > sparseness_threshold) {
          row_ind = i + start_row;
          col_ind = j + start_row;
          // TODO(naveenoid) : Port to batch addition mode of this function
          // by utilising the Upper right (or lower left) triangular matrix.
          // The single element addition method used below is recommended
          // initiall by Gurobi since it has a low cost
          individual_quadratic_cost_value = Q(i, j);
          error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
                                &individual_quadratic_cost_value);
        }
      }
    }
    GRBsetdblattrarray(model, "Obj", start_row, num_constraint_vars, b.data());
    start_row = start_row + Q.rows();
  }

  // TODO(naveenoid) : needs test coverage
  for (auto const& binding : prog.linear_equality_constraints()) {
    auto const& c = binding.constraint();
    myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);
  }

  for (auto const& binding : prog.linear_constraints()) {
    auto const& c = binding.constraint();

    if (c->lower_bound() !=
        -Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,
                                   std::numeric_limits<double>::infinity())) {
      myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,
                      1e-18);
    }
    if (c->upper_bound() !=
        Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,
                                  std::numeric_limits<double>::infinity())) {
      myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);
    }
  }

  SolutionResult result = SolutionResult::kSolutionFound;

  error = GRBoptimize(model);

  int optimstatus = 0;
  double objval = 0.0;

  if (error) {
    // TODO(naveenoid) : log error message using GRBgeterrormsg(env)
    result = SolutionResult::kInvalidInput;
  } else {
    error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
    error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);

    if (optimstatus != GRB_OPTIMAL) {
      if (optimstatus == GRB_INF_OR_UNBD) {
        result = SolutionResult::kInfeasibleConstraints;
      } else {
        result = SolutionResult::kUnknownError;
      }
    }
  }

  Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);

  GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
  prog.SetDecisionVariableValues(sol_vector);

  prog.SetSolverResult("Gurobi", 0);

  GRBfreemodel(model);
  GRBfreeenv(env);

  return result;
}

}  // namespace drake
}  // namespace solvers
<|endoftext|>


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

#include "xwalk/application/browser/application_protocols.h"

#include <algorithm>
#include <string>
#include <vector>

#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "url/url_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_simple_job.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/application_resource.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/main_document_handler.h"

using content::ResourceRequestInfo;
using xwalk::application::ApplicationData;
using xwalk::application::MainDocumentInfo;
namespace keys = xwalk::application_manifest_keys;

namespace {

net::HttpResponseHeaders* BuildHttpHeaders(
    const std::string& mime_type, const std::string& method,
    const base::FilePath& file_path, const base::FilePath& relative_path,
    bool is_authority_match) {
  std::string raw_headers;
  if (method == "GET") {
    if (relative_path.empty())
      raw_headers.append("HTTP/1.1 400 Bad Request");
    else if (!is_authority_match)
      raw_headers.append("HTTP/1.1 403 Forbidden");
    else if (file_path.empty())
      raw_headers.append("HTTP/1.1 404 Not Found");
    else
      raw_headers.append("HTTP/1.1 200 OK");
  } else {
    raw_headers.append("HTTP/1.1 501 Not Implemented");
  }

  raw_headers.append(1, '\0');
  raw_headers.append("Access-Control-Allow-Origin: *");

  if (!mime_type.empty()) {
    raw_headers.append(1, '\0');
    raw_headers.append("Content-Type: ");
    raw_headers.append(mime_type);
  }

  raw_headers.append(2, '\0');
  return new net::HttpResponseHeaders(raw_headers);
}

class GeneratedMainDocumentJob: public net::URLRequestSimpleJob {
 public:
  GeneratedMainDocumentJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const base::FilePath& relative_path,
      const scoped_refptr<const ApplicationData> application)
    : net::URLRequestSimpleJob(request, network_delegate),
      application_(application),
      mime_type_("text/html"),
      relative_path_(relative_path) {
  }

  // Overridden from URLRequestSimpleJob:
  virtual int GetData(std::string* mime_type,
                      std::string* charset,
                      std::string* data,
                      const net::CompletionCallback& callback) const OVERRIDE {
    *mime_type = mime_type_;
    *charset = "utf-8";
    *data = "<!DOCTYPE html>\n<body>\n";

    MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo(
        application_->GetManifestData(keys::kAppMainKey));
    const std::vector<std::string>& main_scripts = main_info->GetMainScripts();
    for (size_t i = 0; i < main_scripts.size(); ++i) {
      *data += "<script src=\"";
      *data += main_scripts[i];
      *data += "\"></script>\n";
    }
    return net::OK;
  }

  virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
    response_info_.headers = BuildHttpHeaders(mime_type_, "GET", relative_path_,
        relative_path_, true);
    *info = response_info_;
  }

 private:
  virtual ~GeneratedMainDocumentJob() {}

  scoped_refptr<const ApplicationData> application_;
  const std::string mime_type_;
  const base::FilePath relative_path_;
  net::HttpResponseInfo response_info_;
};

void ReadResourceFilePath(
    const xwalk::application::ApplicationResource& resource,
    base::FilePath* file_path) {
  *file_path = resource.GetFilePath();
}

class URLRequestApplicationJob : public net::URLRequestFileJob {
 public:
  URLRequestApplicationJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const scoped_refptr<base::TaskRunner>& file_task_runner,
      const std::string& application_id,
      const base::FilePath& directory_path,
      const base::FilePath& relative_path,
      bool is_authority_match)
      : net::URLRequestFileJob(
          request, network_delegate, base::FilePath(), file_task_runner),
        relative_path_(relative_path),
        is_authority_match_(is_authority_match),
        resource_(application_id, directory_path, relative_path),
        weak_factory_(this) {
  }

  virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
    std::string mime_type;
    GetMimeType(&mime_type);
    std::string method = request()->method();
    response_info_.headers = BuildHttpHeaders(mime_type, method, file_path_,
        relative_path_, is_authority_match_);
    *info = response_info_;
  }

  virtual void Start() OVERRIDE {
    base::FilePath* read_file_path = new base::FilePath;

    bool posted = base::WorkerPool::PostTaskAndReply(
        FROM_HERE,
        base::Bind(&ReadResourceFilePath, resource_,
                   base::Unretained(read_file_path)),
        base::Bind(&URLRequestApplicationJob::OnFilePathRead,
                   weak_factory_.GetWeakPtr(),
                   base::Owned(read_file_path)),
        true /* task is slow */);
    DCHECK(posted);
  }

 private:
  virtual ~URLRequestApplicationJob() {}

  void OnFilePathRead(base::FilePath* read_file_path) {
    file_path_ = *read_file_path;
    if (file_path_.empty())
      NotifyHeadersComplete();
    else
      URLRequestFileJob::Start();
  }

  net::HttpResponseInfo response_info_;
  base::FilePath relative_path_;
  bool is_authority_match_;
  xwalk::application::ApplicationResource resource_;
  base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_;
};

class ApplicationProtocolHandler
    : public net::URLRequestJobFactory::ProtocolHandler {
 public:
  explicit ApplicationProtocolHandler(const ApplicationData* application)
    : application_(application) {
    CHECK(application_);
  }

  virtual ~ApplicationProtocolHandler() {}

  virtual net::URLRequestJob* MaybeCreateJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const OVERRIDE;

 private:
  const ApplicationData* application_;
  DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler);
};

net::URLRequestJob*
ApplicationProtocolHandler::MaybeCreateJob(
    net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
  std::string application_id = request->url().host();

  bool is_authority_match = application_id == application_->ID();
  base::FilePath relative_path =
      xwalk::application::ApplicationURLToRelativeFilePath(request->url());
  base::FilePath directory_path;
  if (is_authority_match)
    directory_path = application_->Path();

  std::string path = request->url().path();
  if (is_authority_match &&
      path.size() > 1 &&
      path.substr(1) == xwalk::application::kGeneratedMainDocumentFilename) {
    return new GeneratedMainDocumentJob(request, network_delegate,
        relative_path, application_);
  }

  return new URLRequestApplicationJob(
      request,
      network_delegate,
      content::BrowserThread::GetBlockingPool()->
      GetTaskRunnerWithShutdownBehavior(
          base::SequencedWorkerPool::SKIP_ON_SHUTDOWN),
      application_id,
      directory_path,
      relative_path,
      is_authority_match);
}

}  // namespace

linked_ptr<net::URLRequestJobFactory::ProtocolHandler>
CreateApplicationProtocolHandler(const ApplicationData* application) {
  return  linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
      new ApplicationProtocolHandler(application));
}
<commit_msg>[Runtime] Add CSP supporting for Crosswalk scheme<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/browser/application_protocols.h"

#include <algorithm>
#include <map>
#include <string>
#include <vector>

#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "url/url_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_simple_job.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/application_resource.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/csp_handler.h"
#include "xwalk/application/common/manifest_handlers/main_document_handler.h"

using content::ResourceRequestInfo;
using xwalk::application::ApplicationData;
using xwalk::application::CSPInfo;
using xwalk::application::MainDocumentInfo;
namespace keys = xwalk::application_manifest_keys;

namespace {

net::HttpResponseHeaders* BuildHttpHeaders(
    const std::string& content_security_policy,
    const std::string& mime_type, const std::string& method,
    const base::FilePath& file_path, const base::FilePath& relative_path,
    bool is_authority_match) {
  std::string raw_headers;
  if (method == "GET") {
    if (relative_path.empty())
      raw_headers.append("HTTP/1.1 400 Bad Request");
    else if (!is_authority_match)
      raw_headers.append("HTTP/1.1 403 Forbidden");
    else if (file_path.empty())
      raw_headers.append("HTTP/1.1 404 Not Found");
    else
      raw_headers.append("HTTP/1.1 200 OK");
  } else {
    raw_headers.append("HTTP/1.1 501 Not Implemented");
  }

  if (!content_security_policy.empty()) {
    raw_headers.append(1, '\0');
    raw_headers.append("Content-Security-Policy: ");
    raw_headers.append(content_security_policy);
  }

  raw_headers.append(1, '\0');
  raw_headers.append("Access-Control-Allow-Origin: *");

  if (!mime_type.empty()) {
    raw_headers.append(1, '\0');
    raw_headers.append("Content-Type: ");
    raw_headers.append(mime_type);
  }

  raw_headers.append(2, '\0');
  return new net::HttpResponseHeaders(raw_headers);
}

class GeneratedMainDocumentJob: public net::URLRequestSimpleJob {
 public:
  GeneratedMainDocumentJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const base::FilePath& relative_path,
      const scoped_refptr<const ApplicationData> application,
      const std::string& content_security_policy)
    : net::URLRequestSimpleJob(request, network_delegate),
      application_(application),
      mime_type_("text/html"),
      relative_path_(relative_path),
      content_security_policy_(content_security_policy) {
  }

  // Overridden from URLRequestSimpleJob:
  virtual int GetData(std::string* mime_type,
                      std::string* charset,
                      std::string* data,
                      const net::CompletionCallback& callback) const OVERRIDE {
    *mime_type = mime_type_;
    *charset = "utf-8";
    *data = "<!DOCTYPE html>\n<body>\n";

    MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo(
        application_->GetManifestData(keys::kAppMainKey));
    const std::vector<std::string>& main_scripts = main_info->GetMainScripts();
    for (size_t i = 0; i < main_scripts.size(); ++i) {
      *data += "<script src=\"";
      *data += main_scripts[i];
      *data += "\"></script>\n";
    }
    return net::OK;
  }

  virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
    response_info_.headers = BuildHttpHeaders(content_security_policy_,
                                              mime_type_, "GET", relative_path_,
                                              relative_path_, true);
    *info = response_info_;
  }

 private:
  virtual ~GeneratedMainDocumentJob() {}

  scoped_refptr<const ApplicationData> application_;
  const std::string mime_type_;
  const base::FilePath relative_path_;
  net::HttpResponseInfo response_info_;
  std::string content_security_policy_;
};

void ReadResourceFilePath(
    const xwalk::application::ApplicationResource& resource,
    base::FilePath* file_path) {
  *file_path = resource.GetFilePath();
}

class URLRequestApplicationJob : public net::URLRequestFileJob {
 public:
  URLRequestApplicationJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate,
      const scoped_refptr<base::TaskRunner>& file_task_runner,
      const std::string& application_id,
      const base::FilePath& directory_path,
      const base::FilePath& relative_path,
      const std::string& content_security_policy,
      bool is_authority_match)
      : net::URLRequestFileJob(
          request, network_delegate, base::FilePath(), file_task_runner),
        relative_path_(relative_path),
        content_security_policy_(content_security_policy),
        is_authority_match_(is_authority_match),
        resource_(application_id, directory_path, relative_path),
        weak_factory_(this) {
  }

  virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
    std::string mime_type;
    GetMimeType(&mime_type);
    std::string method = request()->method();
    response_info_.headers = BuildHttpHeaders(
        content_security_policy_, mime_type, method, file_path_,
        relative_path_, is_authority_match_);
    *info = response_info_;
  }

  virtual void Start() OVERRIDE {
    base::FilePath* read_file_path = new base::FilePath;

    bool posted = base::WorkerPool::PostTaskAndReply(
        FROM_HERE,
        base::Bind(&ReadResourceFilePath, resource_,
                   base::Unretained(read_file_path)),
        base::Bind(&URLRequestApplicationJob::OnFilePathRead,
                   weak_factory_.GetWeakPtr(),
                   base::Owned(read_file_path)),
        true /* task is slow */);
    DCHECK(posted);
  }

 private:
  virtual ~URLRequestApplicationJob() {}

  void OnFilePathRead(base::FilePath* read_file_path) {
    file_path_ = *read_file_path;
    if (file_path_.empty())
      NotifyHeadersComplete();
    else
      URLRequestFileJob::Start();
  }

  net::HttpResponseInfo response_info_;
  base::FilePath relative_path_;
  std::string content_security_policy_;
  bool is_authority_match_;
  xwalk::application::ApplicationResource resource_;
  base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_;
};

class ApplicationProtocolHandler
    : public net::URLRequestJobFactory::ProtocolHandler {
 public:
  explicit ApplicationProtocolHandler(const ApplicationData* application)
    : application_(application) {
    CHECK(application_);
  }

  virtual ~ApplicationProtocolHandler() {}

  virtual net::URLRequestJob* MaybeCreateJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const OVERRIDE;

 private:
  const ApplicationData* application_;
  DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler);
};

net::URLRequestJob*
ApplicationProtocolHandler::MaybeCreateJob(
    net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
  std::string application_id = request->url().host();

  bool is_authority_match = application_id == application_->ID();
  base::FilePath relative_path =
      xwalk::application::ApplicationURLToRelativeFilePath(request->url());
  base::FilePath directory_path;
  if (is_authority_match)
    directory_path = application_->Path();

  std::string content_security_policy;
  const CSPInfo* csp_info = static_cast<CSPInfo*>(
      application_->GetManifestData(keys::kCSPKey));
  if (csp_info) {
    const std::map<std::string, std::vector<std::string> >& policies =
        csp_info->GetDirectives();
    for (std::map<std::string, std::vector<std::string> >::const_iterator it =
             policies.begin(); it != policies.end(); ++it) {
      content_security_policy += base::StringPrintf(
          "%s %s;", (it->first).c_str(), JoinString(it->second, ' ').c_str());
    }
  }

  std::string path = request->url().path();
  if (is_authority_match &&
      path.size() > 1 &&
      path.substr(1) == xwalk::application::kGeneratedMainDocumentFilename) {
    return new GeneratedMainDocumentJob(request, network_delegate,
                                        relative_path, application_,
                                        content_security_policy);
  }

  return new URLRequestApplicationJob(
      request,
      network_delegate,
      content::BrowserThread::GetBlockingPool()->
      GetTaskRunnerWithShutdownBehavior(
          base::SequencedWorkerPool::SKIP_ON_SHUTDOWN),
      application_id,
      directory_path,
      relative_path,
      content_security_policy,
      is_authority_match);
}

}  // namespace

linked_ptr<net::URLRequestJobFactory::ProtocolHandler>
CreateApplicationProtocolHandler(const ApplicationData* application) {
  return  linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
      new ApplicationProtocolHandler(application));
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 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.
 *
 *******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>

namespace miopen {

TensorDescriptor::TensorDescriptor() {}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
    : lens(plens), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
    this->CalculateStrides();
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   std::initializer_list<std::size_t> plens,
                                   std::initializer_list<std::size_t> pstrides)
    : lens(plens), strides(pstrides), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
    : lens(plens, plens + size), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
    this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   const int* plens,
                                   const int* pstrides,
                                   int size)
    : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
}

void TensorDescriptor::CalculateStrides()
{
    strides.clear();
    strides.resize(lens.size(), 0);
    strides.back() = 1;
    std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}

const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
    assert(lens.size() == strides.size());
    return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
    assert(lens.size() == strides.size());
    return std::accumulate(
        lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }

std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
    assert(l.size() <= this->GetSize());
    return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0});
}

std::size_t TensorDescriptor::GetElementSpace() const
{
    std::vector<std::size_t> maxIndices(lens.size());
    std::transform(lens.begin(),
                   lens.end(),
                   std::vector<std::size_t>(lens.size(), 1).begin(),
                   maxIndices.begin(),
                   std::minus<size_t>());
    return std::inner_product(
               maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) +
           1;
}

std::size_t TensorDescriptor::GetNumBytes() const
{
    std::size_t typesize = 0;
    switch(this->type)
    {
    case miopenHalf: typesize  = 2; break;
    case miopenFloat: typesize = 4; break;
    }
    return typesize * this->GetElementSpace();
}

bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
    assert(this->lens.size() == rhs.strides.size());
    return this->type == rhs.type && this->lens == rhs.lens;
}

bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }

std::string TensorDescriptor::ToString() const
{
    std::string result;
    for(auto i : this->lens)
    {
        result += std::to_string(i) + ", ";
    }
    return result.substr(0, result.length() - 2);
}

std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
    return LogRange(stream, t.lens, ", ");
}

} // namespace miopen

// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
    return miopen::deref(tensorDesc).GetIndex(indices);
}
<commit_msg>added back strides in the equality of tensors<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 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.
 *
 *******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>

namespace miopen {

TensorDescriptor::TensorDescriptor() {}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
    : lens(plens), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
    this->CalculateStrides();
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   std::initializer_list<std::size_t> plens,
                                   std::initializer_list<std::size_t> pstrides)
    : lens(plens), strides(pstrides), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
}

TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
    : lens(plens, plens + size), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
    this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
                                   const int* plens,
                                   const int* pstrides,
                                   int size)
    : lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
    if(t != miopenFloat)
    {
        MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
    }
}

void TensorDescriptor::CalculateStrides()
{
    strides.clear();
    strides.resize(lens.size(), 0);
    strides.back() = 1;
    std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}

const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
    assert(lens.size() == strides.size());
    return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
    assert(lens.size() == strides.size());
    return std::accumulate(
        lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }

std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
    assert(l.size() <= this->GetSize());
    return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0});
}

std::size_t TensorDescriptor::GetElementSpace() const
{
    std::vector<std::size_t> maxIndices(lens.size());
    std::transform(lens.begin(),
                   lens.end(),
                   std::vector<std::size_t>(lens.size(), 1).begin(),
                   maxIndices.begin(),
                   std::minus<size_t>());
    return std::inner_product(
               maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) +
           1;
}

std::size_t TensorDescriptor::GetNumBytes() const
{
    std::size_t typesize = 0;
    switch(this->type)
    {
    case miopenHalf: typesize  = 2; break;
    case miopenFloat: typesize = 4; break;
    }
    return typesize * this->GetElementSpace();
}

bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
    assert(this->lens.size() == rhs.strides.size());
    return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides;
}

bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }

std::string TensorDescriptor::ToString() const
{
    std::string result;
    for(auto i : this->lens)
    {
        result += std::to_string(i) + ", ";
    }
    return result.substr(0, result.length() - 2);
}

std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
    return LogRange(stream, t.lens, ", ");
}

} // namespace miopen

// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
    return miopen::deref(tensorDesc).GetIndex(indices);
}
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief format string

	Copyright (C) 2011 Cybozu Labs, Inc., all rights reserved.
*/
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <cybozu/exception.hpp>

namespace cybozu {

std::string format(const char *format, ...)
{
#ifdef _MSC_VER
	va_list args;
	va_start(args, format);
	_locale_t curLoc = _get_current_locale();
	va_start(args, format);
	int size = _vscprintf_l(format, curLoc, args);
	va_end(args);
	if (size < 0 || size >= INT_MAX) throw cybozu::Exception("format:_vscprintf_l");

	std::string str;
	str.resize(size + 1);

	va_start(args, format);
	int ret = _vsprintf_s_l(&str[0], size + 1, format, curLoc, args);
	va_end(args);
	if (ret < 0) throw cybozu::Exception("format:_vsprintf_s_l");
	str.resize(size);
	return str;
#else
	char *p;
	va_list args;
	va_start(args, format);
	int ret = vasprintf(&p, format, args);
	va_end(args);
	if (ret < 0) throw cybozu::Exception("format:vasnprintf");
    try {
		std::string str(p, ret);
		free(p);
		return str;
	} catch (...) {
		free(p);
		throw std::bad_alloc();
	}
#endif
}

} // cybozu
<commit_msg>add vformat<commit_after>#pragma once
/**
	@file
	@brief format string

	Copyright (C) 2011 Cybozu Labs, Inc., all rights reserved.
*/
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <cybozu/exception.hpp>

namespace cybozu {

inline void vformat(std::string& str, const char *format, va_list args)
{
#ifdef _MSC_VER
	va_list args2;
	va_copy(args2, args);
	_locale_t curLoc = _get_current_locale();
	int size = _vscprintf_l(format, curLoc, args);
	if (size < 0 || size >= INT_MAX) throw cybozu::Exception("vformat:_vscprintf_l");

	str.resize(size + 1);

	int ret = _vsprintf_s_l(&str[0], size + 1, format, curLoc, args2);
	if (ret < 0) throw cybozu::Exception("vformat:_vsprintf_s_l");
	str.resize(size);
#else
	char *p;
	int ret = vasprintf(&p, format, args);
	if (ret < 0) throw cybozu::Exception("vformat:vasnprintf");
    try {
		str.assign(p, ret);
		free(p);
	} catch (...) {
		free(p);
		throw std::bad_alloc();
	}
#endif
}

inline void format(std::string& str, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	cybozu::vformat(str, format, args);
	va_end(args);
}

inline std::string format(const char *format, ...)
{
	std::string str;
	va_list args;
	va_start(args, format);
	cybozu::vformat(str, format, args);
	va_end(args);
	return str;
}

} // cybozu
<|endoftext|>