<commit_before>#include "solver_factory.h"

#include <iostream>

#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"

#include "error.h"

namespace cyclus {

// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
    : t_(t),
      tmax_(tmax) { }

OsiSolverInterface* SolverFactory::get() {
  if (t_ == "clp") {
    OsiClpSolverInterface* s = new OsiClpSolverInterface();
    s->getModelPtr()->setMaximumSeconds(tmax_);
    return s;
  } else if (t_ == "cbc") {
    OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
    s->setMaximumSeconds(tmax_);
    return s;
  } else {
    throw ValueError("invalid SolverFactory type '" + t_ + "'");
  }
}

void ReportProg(OsiSolverInterface* si) {
  const double* objs = si->getObjCoefficients();
  const double* clbs = si->getColLower();
  const double* cubs = si->getColUpper();
  int ncol = si->getNumCols();
  std::cout << "Column info\n";
  for (int i = 0; i != ncol; i ++) {
    std::cout << i
              << " obj" << ": " << objs[i]
              << " lb" << ": " << clbs[i]
              << " ub" << ": " << cubs[i]
              << " int" << ": " << std::boolalpha << si->isInteger(i) << '\n';
  }

  const CoinPackedMatrix* m = si->getMatrixByRow();
  const double* rlbs = si->getRowLower();
  const double* rubs = si->getRowUpper();
  int nrow = si->getNumRows();
  std::cout << "Row info\n";
  for (int i = 0; i != nrow; i ++) {
    std::cout << i
              << " lb" << ": " << rlbs[i]
              << " ub" << ": " << rubs[i] << '\n';
  }
  std::cout << "matrix:\n";
  m->dumpMatrix();
}

void SolveProg(OsiSolverInterface* si, bool verbose) {
  if (verbose)
    ReportProg(si);

  si->initialSolve();
  if (HasInt(si)) {
    si->branchAndBound();
  } else {
    OsiClpSolverInterface* cast = dynamic_cast<OsiClpSolverInterface*>(si);
    if (cast) {
      cast->getModelPtr()->primal(); // solve problem with primal alg
    }
  }

  if (verbose) {
    const double* soln = si->getColSolution();
    for (int i = 0; i != si->getNumCols(); i ++) {
      std::cout << "soln " << i << ": " << soln[i] << '\n';
    }
  }
}

bool HasInt(OsiSolverInterface* si) {
  int i = 0;
  for (i = 0; i != si->getNumCols(); i++) {
    if (si->isInteger(i)) {
      return true;
    }
  }
  return false;
}

}  // namespace cyclus
<commit_msg>killed osi cbc warning message<commit_after>#include "solver_factory.h"

#include <iostream>

#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"

#include "error.h"

namespace cyclus {

// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
    : t_(t),
      tmax_(tmax) { }

OsiSolverInterface* SolverFactory::get() {
  if (t_ == "clp") {
    OsiClpSolverInterface* s = new OsiClpSolverInterface();
    s->getModelPtr()->setMaximumSeconds(tmax_);
    return s;
  } else if (t_ == "cbc") {
    OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
    s->setMaximumSeconds(tmax_);
    return s;
  } else {
    throw ValueError("invalid SolverFactory type '" + t_ + "'");
  }
}

void ReportProg(OsiSolverInterface* si) {
  const double* objs = si->getObjCoefficients();
  const double* clbs = si->getColLower();
  const double* cubs = si->getColUpper();
  int ncol = si->getNumCols();
  std::cout << "Column info\n";
  for (int i = 0; i != ncol; i ++) {
    std::cout << i
              << " obj" << ": " << objs[i]
              << " lb" << ": " << clbs[i]
              << " ub" << ": " << cubs[i]
              << " int" << ": " << std::boolalpha << si->isInteger(i) << '\n';
  }

  const CoinPackedMatrix* m = si->getMatrixByRow();
  const double* rlbs = si->getRowLower();
  const double* rubs = si->getRowUpper();
  int nrow = si->getNumRows();
  std::cout << "Row info\n";
  for (int i = 0; i != nrow; i ++) {
    std::cout << i
              << " lb" << ": " << rlbs[i]
              << " ub" << ": " << rubs[i] << '\n';
  }
  std::cout << "matrix:\n";
  m->dumpMatrix();
}

void SolveProg(OsiSolverInterface* si, bool verbose) {
  if (verbose)
    ReportProg(si);

  si->initialSolve();
  if (HasInt(si)) {
    OsiCbcSolverInterface* cast = dynamic_cast<OsiCbcSolverInterface*>(si);
    if (cast)
      cast->getModelPtr()->branchAndBound(); // get rid of warning
    else
      si->branchAndBound();
  } else {
    OsiClpSolverInterface* cast = dynamic_cast<OsiClpSolverInterface*>(si);
    if (cast) {
      cast->getModelPtr()->primal(); // solve problem with primal alg
    }
  }

  if (verbose) {
    const double* soln = si->getColSolution();
    for (int i = 0; i != si->getNumCols(); i ++) {
      std::cout << "soln " << i << ": " << soln[i] << '\n';
    }
  }
}

bool HasInt(OsiSolverInterface* si) {
  int i = 0;
  for (i = 0; i != si->getNumCols(); i++) {
    if (si->isInteger(i)) {
      return true;
    }
  }
  return false;
}

}  // namespace cyclus
<|endoftext|>


<commit_before>//
// StreamFlowC : A C++ coding style to describe hardware structure for stream processing
//

// Copyright (c) 2009 the handy-eda-utils developer(s).
// Distributed under the MIT License.
// (See accompanying file COPYING or copy at
//  http://www.opensource.org/licenses/mit-license.php.)

#include "streamflowc.h"
#include <vector>
#include <string>
#include <cstring>
#include <stdexcept>

namespace streamflowc {

namespace simcontext {

namespace {

struct simcontext_t {
  ::std::vector<const char *> name_hierarchy;
};

simcontext_t *the_simcontext() {
  static simcontext_t *x = new simcontext_t;  // Never deleted.  Do not mind.
  return x;
}

} // anonymous namespace

void push_modulename(const char *name) { the_simcontext()->name_hierarchy.push_back(name); }
void pop_modulename()                  { the_simcontext()->name_hierarchy.pop_back(); }
const char *get_current_basename()     { return the_simcontext()->name_hierarchy.back(); }

const char *get_current_name()
{
  ::std::vector<const char *>& vec = the_simcontext()->name_hierarchy;
  int s = vec.size();
  if (s == 0)  return "";
  int ix = (vec[0] == 0) ? 1 : 0;  // main() may directly instanciate DUT and TestBench unnamed.
  if (ix == 1 && s == 1)  return "";
  int len = 0;
  for (int i=ix; i<s; ++i) {
    len += ((vec[i] != 0) ? ::std::strlen(vec[i]) : 0) + 1;
  }
  char *ans = new char[len];	// Never deleted.  Do not mind.
  int cx = 0;
  for (int i=ix; i<s; ++i) {
    if (vec[i] != 0) {
      len = ::std::strlen(vec[i]);
      ::std::strncpy(&ans[cx], vec[i], len);
      cx += len;
    }
    ans[cx++] = '.';
  }
  // assert(cx == sizeof(ans[]));
  ans[cx-1] = '\0';  // change the last '.' to '\0'
  return ans;
}

} // namespace simcontext

namespace {

void throw_binding_error() __attribute__((__noreturn__));

void throw_binding_error()
{
  if (simcontext::the_simcontext()->name_hierarchy.empty()) {
    throw ::std::logic_error("non peer-to-peer port binding");
  } else {
    const char *instance = simcontext::get_current_name();
    if (instance[0] == '\0') {
      throw ::std::logic_error("non peer-to-peer port binding about the top module");
    } else {
      throw ::std::logic_error(::std::string("non peer-to-peer port binding about ") + instance);
    }
  }
  /*NOTREACHED*/
}

} // anonymous namespace

// portref_base.m_ptr management
//
// value            state           description
// -------------------------------------------------------------------------------------
// 00...0000         this           initialized
// ss...ss01   src<--this           points to source portref_base
// 00...0010         this<--dst     pointed to by someone
// ss...ss11   src<--this<--dst     points to source portref_base, and pointed to by someone
//
// pp...pp00         port           points to the established destination port
// pp...pp10    forwarded_port      forwarded the established destination port to someone

void portref_base::chain(portref_base *src)
{
  if (m_ptr == 0 || m_ptr == 2) {
    m_ptr += reinterpret_cast<__SIZE_TYPE__>(src) + 1;
    __SIZE_TYPE__ sptr = src->m_ptr;
    if (((sptr & 2) != 0) || (sptr != 0 && (sptr & 3) == 0))  throw_binding_error();
    src->m_ptr += 2;
  } else if ((m_ptr & 3) == 0) {
    src->assign(reinterpret_cast<void *>(m_ptr));
    m_ptr += 2;
  } else {
    throw_binding_error();
  }
}

void portref_base::assign(void *dst)
{
  portref_base *p = this;
  __SIZE_TYPE__ ptr = p->m_ptr;
  if (ptr == 0) {
    p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst);
  } else if ((ptr & 3) == 1) {
    p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst) + 2;
    p = reinterpret_cast<portref_base*>(ptr - 1);
    while (true) {
      ptr = p->m_ptr;
      if (ptr == 2) {
        p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst);
        break;
      } else if ((ptr & 3) == 3) {
        p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst) + 2;
        p = reinterpret_cast<portref_base*>(ptr - 3);
      } else {
        throw ::std::logic_error("internal error in streamflowc::potref_base::assign()");
      }
    }
  } else {
    throw_binding_error();
  }
}

} // namespace streamflowc
<commit_msg>ignore empty name in module hierarchy<commit_after>//
// StreamFlowC : A C++ coding style to describe hardware structure for stream processing
//

// Copyright (c) 2009 the handy-eda-utils developer(s).
// Distributed under the MIT License.
// (See accompanying file COPYING or copy at
//  http://www.opensource.org/licenses/mit-license.php.)

#include "streamflowc.h"
#include <vector>
#include <string>
#include <cstring>
#include <stdexcept>

namespace streamflowc {

namespace simcontext {

namespace {

struct simcontext_t {
  ::std::vector<const char *> name_hierarchy;
};

simcontext_t *the_simcontext() {
  static simcontext_t *x = new simcontext_t;  // Never deleted.  Do not mind.
  return x;
}

} // anonymous namespace

void push_modulename(const char *name) { the_simcontext()->name_hierarchy.push_back(name); }
void pop_modulename()                  { the_simcontext()->name_hierarchy.pop_back(); }
const char *get_current_basename()     { return the_simcontext()->name_hierarchy.back(); }

const char *get_current_name()
{
  ::std::vector<const char *>& vec = the_simcontext()->name_hierarchy;
  int n = vec.size();
  int len = 0;
  for (int i=0; i<n; ++i) {
    if (vec[i] != 0)  len += ::std::strlen(vec[i]) + 1;
  }
  if (len == 0)  return "";  // main() may directly instanciate DUT and TestBench unnamed.
  char *ans = new char[len];	// Never deleted.  Do not mind.
  int cx = 0;
  for (int i=0; i<n; ++i) {
    if (vec[i] != 0) {
      len = ::std::strlen(vec[i]);
      ::std::strncpy(&ans[cx], vec[i], len);
      cx += len;
      ans[cx++] = '.';
    }
  }
  // assert(cx == sizeof(ans[]));
  ans[cx-1] = '\0';  // change the last '.' to '\0'
  return ans;
}

} // namespace simcontext

namespace {

void throw_binding_error() __attribute__((__noreturn__));

void throw_binding_error()
{
  if (simcontext::the_simcontext()->name_hierarchy.empty()) {
    throw ::std::logic_error("non peer-to-peer port binding");
  } else {
    const char *instance = simcontext::get_current_name();
    if (instance[0] == '\0') {
      throw ::std::logic_error("non peer-to-peer port binding about the top module");
    } else {
      throw ::std::logic_error(::std::string("non peer-to-peer port binding about ") + instance);
    }
  }
  /*NOTREACHED*/
}

} // anonymous namespace

// portref_base.m_ptr management
//
// value            state           description
// -------------------------------------------------------------------------------------
// 00...0000         this           initialized
// ss...ss01   src<--this           points to source portref_base
// 00...0010         this<--dst     pointed to by someone
// ss...ss11   src<--this<--dst     points to source portref_base, and pointed to by someone
//
// pp...pp00         port           points to the established destination port
// pp...pp10    forwarded_port      forwarded the established destination port to someone

void portref_base::chain(portref_base *src)
{
  if (m_ptr == 0 || m_ptr == 2) {
    m_ptr += reinterpret_cast<__SIZE_TYPE__>(src) + 1;
    __SIZE_TYPE__ sptr = src->m_ptr;
    if (((sptr & 2) != 0) || (sptr != 0 && (sptr & 3) == 0))  throw_binding_error();
    src->m_ptr += 2;
  } else if ((m_ptr & 3) == 0) {
    src->assign(reinterpret_cast<void *>(m_ptr));
    m_ptr += 2;
  } else {
    throw_binding_error();
  }
}

void portref_base::assign(void *dst)
{
  portref_base *p = this;
  __SIZE_TYPE__ ptr = p->m_ptr;
  if (ptr == 0) {
    p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst);
  } else if ((ptr & 3) == 1) {
    p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst) + 2;
    p = reinterpret_cast<portref_base*>(ptr - 1);
    while (true) {
      ptr = p->m_ptr;
      if (ptr == 2) {
        p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst);
        break;
      } else if ((ptr & 3) == 3) {
        p->m_ptr = reinterpret_cast<__SIZE_TYPE__>(dst) + 2;
        p = reinterpret_cast<portref_base*>(ptr - 3);
      } else {
        throw ::std::logic_error("internal error in streamflowc::potref_base::assign()");
      }
    }
  } else {
    throw_binding_error();
  }
}

} // namespace streamflowc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-27 07:16:25 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include "filedlghelper.hrc"

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME sfx

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

const rtl::OUString TILDE = OUString::createFromAscii( "~" );
const sal_Unicode TILDE_SIGN = L'~';

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_CB_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_CB_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_CB_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_CB_READONLY },
    { CHECKBOX_LINK,                            STR_CB_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_CB_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_PB_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_LB_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_LB_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_LB_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_CB_SELECTION },
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );

                // remove '~' signs, if there are two '~' signs
                // in a row we remove only one of them
                if ( aResOUString.indexOf( TILDE ) > -1 )
                {
                    sal_Int32 nStrLen = aResOUString.getLength( );
                    rtl::OUStringBuffer aBuffer( nStrLen );
                    sal_Int32 i = 0;
                    const sal_Unicode* pPos  = aResOUString.getStr( );
                    const sal_Unicode* pNext = aResOUString.getStr( ) + 1;
                    const sal_Unicode* pEnd  = aResOUString.getStr( ) + nStrLen;

                    while( pPos < pEnd )
                    {
                        // we insert the next character only if the current character
                        // in not a '~' or the following character is also a '~'
                        if ( (*pPos != TILDE_SIGN) ||
                             ((*pPos == TILDE_SIGN) && (pNext < pEnd) && (*pNext == TILDE_SIGN)) )
                        {
                            aBuffer.insert( i, *pPos );
                            i++;
                        }

                        pPos++;
                        pNext++;
                    }

                    aResOUString = aBuffer.makeStringAndClear( );
                }
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}<commit_msg>#86986#using svtools resource<commit_after>/*************************************************************************
 *
 *  $RCSfile: resourceprovider.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: tra $ $Date: 2001-06-27 08:13:00 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _RESOURCEPROVIDER_HXX_
#include "resourceprovider.hxx"
#endif

#ifndef _TOOLS_RESMGR_HXX
#include <tools/resmgr.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define RES_NAME svt

// because the label of a listbox is
// a control itself (static text) we
// have defined a control id for this
// label which is the listbox control
// id + 100
#define LB_LABEL_OFFSET 100

const rtl::OUString TILDE = OUString::createFromAscii( "~" );
const sal_Unicode TILDE_SIGN = L'~';

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION + LB_LABEL_OFFSET,        STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE + LB_LABEL_OFFSET,       STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE + LB_LABEL_OFFSET, STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        m_ResMgr = CREATEVERSIONRESMGR( RES_NAME );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        String   aResString;
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
            {
                aResString = String( ResId( aResId, m_ResMgr ) );
                aResOUString = OUString( aResString );

                // remove '~' signs, if there are two '~' signs
                // in a row we remove only one of them
                if ( aResOUString.indexOf( TILDE ) > -1 )
                {
                    sal_Int32 nStrLen = aResOUString.getLength( );
                    rtl::OUStringBuffer aBuffer( nStrLen );
                    sal_Int32 i = 0;
                    const sal_Unicode* pPos  = aResOUString.getStr( );
                    const sal_Unicode* pNext = aResOUString.getStr( ) + 1;
                    const sal_Unicode* pEnd  = aResOUString.getStr( ) + nStrLen;

                    while( pPos < pEnd )
                    {
                        // we insert the next character only if the current character
                        // in not a '~' or the following character is also a '~'
                        if ( (*pPos != TILDE_SIGN) ||
                             ((*pPos == TILDE_SIGN) && (pNext < pEnd) && (*pNext == TILDE_SIGN)) )
                        {
                            aBuffer.insert( i, *pPos );
                            i++;
                        }

                        pPos++;
                        pNext++;
                    }

                    aResOUString = aBuffer.makeStringAndClear( );
                }
            }
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    ResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int32 aId )
{
   return m_pImpl->getResString( aId );
}<|endoftext|>


<commit_before>/* TABBLERO DE SUDOKU
 *
 * Este código sólo muestra el tablero del sudoku y permite moverse en él usando un cursor.
 * Las téclas para moverse son «a» izquierda, «d»  derecha , «w» arriba y «s» abajo (minúsculas).
 * Cada letra implica moverse un espacio. en el tablero hacia alguna de las direcciones. Luego de presionar la tecla
 * en cuestión, se debe presionar «ENTER» para ejecutar el movimiento.
 * Se puede editar cualquier valor en el tablero (o crear uno), dirigiéndose hasta la posición deseada y
 * editar el valor allí con los números del 0 a 9 (el cero es para borrar) y luego «ENTER».
**/

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
// #include <termios.h>

using namespace std;

// CONSTANTES
#define FILAS 9
#define COLUMNAS 9

// las únicas dos funciones que se usan. Su definición está abajo del main.
void menu();
void imprimirTablero(int tablero[FILAS][COLUMNAS], int x, int y); // imprime el tablero
bool verificarElementos(int numero, int siguiente, int array[9]);
int * convertirMatriz (int matriz[3][3]);
bool verificarColumnas(int tablero[9][9]);
bool verificarFilas(int matriz[9][9]);
bool verificarCuadrantes (int matriz[9][9]);

int main ()
{
	int sudoku[FILAS][COLUMNAS] = {
		{1,0,0,0,2,0,5,9,3},
		{8,0,3,6,0,1,0,4,0},
		{4,2,0,3,5,0,0,0,6},
		{9,0,2,5,1,8,0,0,0},
		{0,8,0,0,7,6,9,0,1},
		{5,0,7,0,0,0,6,2,8},
		{0,4,0,1,6,0,7,3,0},
		{0,9,1,7,0,5,4,0,0},
		{0,3,5,0,0,2,0,6,9}
	};

	bool contunuarJuego = verificarCuadrantes(sudoku) && verificarColumnas(sudoku) && verificarFilas(sudoku);

	/* inicializamos la variable para las teclas del movimiento
	 * y para los números del 0 - 9 que se ingresen en el tablero
	 */

	char opcion = 'x'; // solo se eligió inicializar «opcion» con 'x' arbitrariamente
	int posx = 0, posy = 0;

	while (opcion != 'P' && opcion != 'p' && contunuarJuego)
	{
		/* aquí hay que seleccionar (comentar o descomentar alguna de las dos siguientes líneas)
		 * dependiendo del sistema operativo.
		 * Lo que hace estas dos líneas de código es limpiar la terminal luego de cada iteración
		 * del ciclo para dibujar el tablero y los elementos cada vez.
		 */

  		//system("cls"); // descomentar para windows
  		system("clear"); // descomentar para linux

		menu();
		imprimirTablero (sudoku, posx, posy);
		opcion = cin.get();

		switch (opcion)
		{
			case 'a':
				posx--;
				if (posx < 0) posx = 8;
				break;

			case 's':
				posy++;
				if (posy > 8) posy = 0;
				break;

			case 'd':
				posx++;
				if (posx > 8) posx = 0;
				break;

			case 'w':
				posy--;
				if (posy < 0) posy = 8;
				break;

			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
			case '0':
				sudoku[posy][posx] = (int)opcion - '0'; // para editar el número y convertirlo de char a entero
				break;

			case 'P': case 'p': // cuando se presiona «p» o «P» se sale del juego
				cout << "Juego Terminado\n";
				break;
		}
	}

	if (contunuarJuego == false) cout << "¡GANASTE!" << endl;

	return 0;
}

/*** DEFINICIÓN DE LAS FUNCIONES UTILIZADAS EN EL JUEGO ***/

void menu()
{
    for (int i = 0; i < 32; i++) cout << "* ";
	cout << "\n*\tMenú:\t\t\t\t\t\t      *\n*\t\t\t\t\t\t\t      *\n";
	cout << "*  Teclas para el movimiento del cursor (minúsculas):\t      *\n";
	cout << "*  a: «izquierda», w: «arriba», d: «deracha» y s: «abajo»     *\n";
	cout << "*  Presione «ENTER» luego de la tecla para mover el cursor    *\n";
	cout << "*  Para editar los valores del tablero:\t\t\t      *\n";
	cout << "*  1 - 9 para asignar un valor a cada celda\t\t      *\n";
	cout << "*  0 para borrar el valor a cada celda\t\t\t      *\n";
	cout << "*\t\t\t\t\t\t\t      *\n";
	for (int i = 0; i < 32; i++) cout << "* ";
	cout << "\n\n";
}

void imprimirTablero(int tablero[FILAS][COLUMNAS], int x, int y)
{
	int columna, fila; // índices para dibujar el tablero

	for (fila = 0; fila < FILAS; fila++)
	{
		if (fila > 0 && fila % 3 == 0) cout << endl; // cada 3 líneas imprime un salto de línea

		for (columna = 0; columna < COLUMNAS; columna++)
        {
			if(columna > 0 && columna % 3 == 0) cout << "  "; // cada tres columnas imprime dos espacios

			if (fila == y && columna == x)
			{
				if (tablero[fila][columna] != 0) cout << ">" << tablero[fila][columna] << "<"; // cursores
				else cout << ">" << "-" << "<"; // se imprime un «-» cuando el número es cero
			}

			else
			{
				if (tablero[fila][columna] != 0) cout << " " << tablero[fila][columna] << " ";
				else cout << " " << "-" << " ";
			}
		}
		cout << endl; // imprime un salto de línea cuando termina de imprimir cada fila del tablero
	}
}

/* OPERACIONES */

bool verificarElementos(int numero, int siguiente, int array[9])
{
	/* devuelve true si hay elementos iguales */

	if (numero > 7) return false;

	int i = siguiente;

	while (numero <= 7 && i <= 8)
	{
		if ( (array[numero] == 0 || array[i] == 0) || (array[numero] == array[i]) )
		{
			return true;
		}
		i++;
	}

	return verificarElementos(numero +1, siguiente +1, array);
}

int * convertirMatriz (int matriz[3][3])
{
	/* recibe la matriz de los cuadrantes y retorna un vector
	   de 9 componentes a partir de esta, para luego verificar sus elementos
	   con otros métodos
	 */
	int indice = 0;
	int * vector = new int[9];

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			vector[indice] = matriz[i][j];
			indice++;
		}

		if (indice > 9) break;
	}

	return vector;
}

bool verificarColumnas(int tablero[9][9])
{
	// retorna true si hay elementos iguales en alguan columna
	int arr[9];

	for(int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			arr[j] = tablero[j][i];
		}

		return verificarElementos(0, 1, arr);

	}
}

bool verificarCuadrantes (int matriz[9][9])
{
	/* crea un vector de 9 componentes a partir de cada uno de los cuadrantes
	   del tablero de sudoku para luego verificar con alguna función sus elementos.
	   retorna true si hay algún elemento repetido en cada cuadrante.
	*/
	int inicioColumna = 0;
	int finColumna = 3;

	int * array = new int[9];
	int submatriz[3][3];

	for (int veces = 0; veces < 3; veces++)
	{
		/* itera tres veces sobre tres columnas, luego sobre otras tres, y finalmente sobre las últimas 3.
		 mientras tanto, se van obteniendo tres elementos por cada fila */
		int i;
		int inicioFila = 0;
		int finFila = 3;
		int columna;

		for (columna = 0; columna < 3; columna++)
		{
			/* se toman los primeros 3 elementos por iteración de todas las filas  por cada 3 columnas */
			for (i = inicioFila; i < finFila; i++) // inicio y fin de fila van a ir aumentando de 3 en 3
			{
				for (int j = inicioColumna; j < finColumna; j++)
				{
					submatriz[i - inicioFila][j - inicioColumna] = matriz[i][j];
				}
			}

			array = convertirMatriz(submatriz);
			if (verificarElementos(0, 1, array)) return true;

			inicioFila += 3;
			finFila += 3;

			if (finFila > 9) break;
		}

		inicioColumna += 3;
		finColumna += 3;
	}

	return false;
}

bool verificarFilas(int matriz[9][9])
{
	int fila[9];
	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			fila[j] = matriz[i][j];
		}

		verificarElementos(0, 1, fila);
	}
}<commit_msg>bug fixes<commit_after>/* TABBLERO DE SUDOKU
 *
 * Este código sólo muestra el tablero del sudoku y permite moverse en él usando un cursor.
 * Las téclas para moverse son «a» izquierda, «d»  derecha , «w» arriba y «s» abajo (minúsculas).
 * Cada letra implica moverse un espacio. en el tablero hacia alguna de las direcciones. Luego de presionar la tecla
 * en cuestión, se debe presionar «ENTER» para ejecutar el movimiento.
 * Se puede editar cualquier valor en el tablero (o crear uno), dirigiéndose hasta la posición deseada y
 * editar el valor allí con los números del 0 a 9 (el cero es para borrar) y luego «ENTER».
**/

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
// #include <termios.h>

using namespace std;

// CONSTANTES
#define FILAS 9
#define COLUMNAS 9

// las únicas dos funciones que se usan. Su definición está abajo del main.
void menu();
void imprimirTablero(int tablero[FILAS][COLUMNAS], int x, int y); // imprime el tablero
bool verificarElementos(int numero, int siguiente, int array[9]);
int * convertirMatriz (int matriz[3][3]);
bool verificarColumnas(int tablero[9][9]);
bool verificarFilas(int matriz[9][9]);
bool verificarCuadrantes (int matriz[9][9]);

int main ()
{
	int sudoku[FILAS][COLUMNAS] = {
		{1,0,0,0,2,0,5,9,3},
		{8,0,3,6,0,1,0,4,0},
		{4,2,0,3,5,0,0,0,6},
		{9,0,2,5,1,8,0,0,0},
		{0,8,0,0,7,6,9,0,1},
		{5,0,7,0,0,0,6,2,8},
		{0,4,0,1,6,0,7,3,0},
		{0,9,1,7,0,5,4,0,0},
		{0,3,5,0,0,2,0,6,9}
	};

	bool continuarJuego = true;

	/* inicializamos la variable para las teclas del movimiento
	 * y para los números del 0 - 9 que se ingresen en el tablero
	 */

	char opcion = 'x'; // solo se eligió inicializar «opcion» con 'x' arbitrariamente
	int posx = 0, posy = 0;

	while (opcion != 'P' && opcion != 'p' && continuarJuego)
	{
		/* aquí hay que seleccionar (comentar o descomentar alguna de las dos siguientes líneas)
		 * dependiendo del sistema operativo.
		 * Lo que hace estas dos líneas de código es limpiar la terminal luego de cada iteración
		 * del ciclo para dibujar el tablero y los elementos cada vez.
		 */

  		//system("cls"); // descomentar para windows
  		system("clear"); // descomentar para linux

		menu();
		imprimirTablero (sudoku, posx, posy);
		opcion = cin.get();

		switch (opcion)
		{
			case 'a':
				posx--;
				if (posx < 0) posx = 8;
				break;

			case 's':
				posy++;
				if (posy > 8) posy = 0;
				break;

			case 'd':
				posx++;
				if (posx > 8) posx = 0;
				break;

			case 'w':
				posy--;
				if (posy < 0) posy = 8;
				break;

			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
			case '0':
				sudoku[posy][posx] = (int)opcion - '0'; // para editar el número y convertirlo de char a entero
				break;

			case 'P': case 'p': // cuando se presiona «p» o «P» se sale del juego
				cout << "Juego Terminado\n";
				break;
		}
		continuarJuego = verificarCuadrantes(sudoku) && verificarColumnas(sudoku) && verificarFilas(sudoku);
	}

	if (continuarJuego == false) cout << "¡GANASTE!" << endl;

	return 0;
}

/*** DEFINICIÓN DE LAS FUNCIONES UTILIZADAS EN EL JUEGO ***/

void menu()
{
    for (int i = 0; i < 32; i++) cout << "* ";
	cout << "\n*\tMenú:\t\t\t\t\t\t      *\n*\t\t\t\t\t\t\t      *\n";
	cout << "*  Teclas para el movimiento del cursor (minúsculas):\t      *\n";
	cout << "*  a: «izquierda», w: «arriba», d: «deracha» y s: «abajo»     *\n";
	cout << "*  Presione «ENTER» luego de la tecla para mover el cursor    *\n";
	cout << "*  Para editar los valores del tablero:\t\t\t      *\n";
	cout << "*  1 - 9 para asignar un valor a cada celda\t\t      *\n";
	cout << "*  0 para borrar el valor a cada celda\t\t\t      *\n";
	cout << "*\t\t\t\t\t\t\t      *\n";
	for (int i = 0; i < 32; i++) cout << "* ";
	cout << "\n\n";
}

void imprimirTablero(int tablero[FILAS][COLUMNAS], int x, int y)
{
	int columna, fila; // índices para dibujar el tablero

	for (fila = 0; fila < FILAS; fila++)
	{
		if (fila > 0 && fila % 3 == 0) cout << endl; // cada 3 líneas imprime un salto de línea

		for (columna = 0; columna < COLUMNAS; columna++)
        {
			if(columna > 0 && columna % 3 == 0) cout << "  "; // cada tres columnas imprime dos espacios

			if (fila == y && columna == x)
			{
				if (tablero[fila][columna] != 0) cout << ">" << tablero[fila][columna] << "<"; // cursores
				else cout << ">" << "-" << "<"; // se imprime un «-» cuando el número es cero
			}

			else
			{
				if (tablero[fila][columna] != 0) cout << " " << tablero[fila][columna] << " ";
				else cout << " " << "-" << " ";
			}
		}
		cout << endl; // imprime un salto de línea cuando termina de imprimir cada fila del tablero
	}
}

/* OPERACIONES */

bool verificarElementos(int numero, int siguiente, int array[9])
{
	/* devuelve true si hay elementos iguales */

	if (numero > 7) return false;

	int i = siguiente;

	while (numero <= 7 && i <= 8)
	{
		if ( (array[numero] == 0 || array[i] == 0) || (array[numero] == array[i]) )
		{
			return true;
		}
		i++;
	}

	return verificarElementos(numero +1, siguiente +1, array);
}

int * convertirMatriz (int matriz[3][3])
{
	/* recibe la matriz de los cuadrantes y retorna un vector
	   de 9 componentes a partir de esta, para luego verificar sus elementos
	   con otros métodos
	 */
	int indice = 0;
	int * vector = new int[9];

	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			vector[indice] = matriz[i][j];
			indice++;
		}

		if (indice > 9) break;
	}

	return vector;
}

bool verificarColumnas(int tablero[9][9])
{
	// retorna true si hay elementos iguales en alguan columna
	int arr[9];

	for(int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			arr[j] = tablero[j][i];
		}

		return verificarElementos(0, 1, arr);

	}
}

bool verificarCuadrantes (int matriz[9][9])
{
	/* crea un vector de 9 componentes a partir de cada uno de los cuadrantes
	   del tablero de sudoku para luego verificar con alguna función sus elementos.
	   retorna true si hay algún elemento repetido en cada cuadrante.
	*/
	int inicioColumna = 0;
	int finColumna = 3;

	int * array = new int[9];
	int submatriz[3][3];

	for (int veces = 0; veces < 3; veces++)
	{
		/* itera tres veces sobre tres columnas, luego sobre otras tres, y finalmente sobre las últimas 3.
		 mientras tanto, se van obteniendo tres elementos por cada fila */
		int i;
		int inicioFila = 0;
		int finFila = 3;
		int columna;

		for (columna = 0; columna < 3; columna++)
		{
			/* se toman los primeros 3 elementos por iteración de todas las filas  por cada 3 columnas */
			for (i = inicioFila; i < finFila; i++) // inicio y fin de fila van a ir aumentando de 3 en 3
			{
				for (int j = inicioColumna; j < finColumna; j++)
				{
					submatriz[i - inicioFila][j - inicioColumna] = matriz[i][j];
				}
			}

			array = convertirMatriz(submatriz);
			if (verificarElementos(0, 1, array)) return true;

			inicioFila += 3;
			finFila += 3;

			if (finFila > 9) break;
		}

		inicioColumna += 3;
		finColumna += 3;
	}

	return false;
}

bool verificarFilas(int matriz[9][9])
{
	int fila[9];
	for (int i = 0; i < 9; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			fila[j] = matriz[i][j];
		}

		verificarElementos(0, 1, fila);
	}
}<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2016 Mike Hansen
 *
 * 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.
 */

/**
 *  \file   spectrum-util.hpp
 *  \date   Sep 29, 2016
 *  \author mike
 */

#ifndef SPECTRUM_UTIL_HPP_
#define SPECTRUM_UTIL_HPP_

#include "types.hpp"

namespace paladin {

/**
 * @brief sorting a spectrum in a variety of ways
 * @param s reference to a spectrum object which is sorted in place
 * @param sortStr a string indicating the type of sort (see below)
 *
 * Sort strings:
 * - SM: smallest by magnitude
 * - LM: largest by magnitude
 * - SR: smallest real part
 * - LR: largest real part
 * - SI: smallest imaginary part
 * - LI: largest imaginary part
 */
void sort_spectrum(SpectrumT& s, const std::string sortStr) {
  struct EigenSorter {
    virtual ~EigenSorter() {}
    virtual bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (std::norm(L) > std::norm(R));
    }
  };
  struct LReal : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (L.real() > R.real());
    }
  };
  struct SReal : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (L.real() < R.real());
    }
  };
  struct LImag : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (L.imag() > R.imag());
    }
  };
  struct SImag : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (L.imag() < R.imag());
    }
  };
  struct LMag : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (std::norm(L) > std::norm(R));
    }
  };
  struct SMag : public EigenSorter {
    bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
      return (std::norm(L) < std::norm(R));
    }
  };

  std::unique_ptr<EigenSorter> sorter;
  if (sortStr == "SM") {
    sorter = paladin::make_unique<SMag>();
  } else if (sortStr == "LM") {
    sorter = paladin::make_unique<LMag>();
  } else if (sortStr == "SR") {
    sorter = paladin::make_unique<SReal>();
  } else if (sortStr == "LR") {
    sorter = paladin::make_unique<LReal>();
  } else if (sortStr == "SI") {
    sorter = paladin::make_unique<SImag>();
  } else if (sortStr == "LI") {
    sorter = paladin::make_unique<LImag>();
  } else {
    sorter = paladin::make_unique<LMag>();
  }
  std::sort(s.begin(), s.end(), *sorter);
}

/**
 * @brief print the spectrum to stdout
 * @param s const reference to a spectrum object
 */
void show_spectrum(const SpectrumT& s) {
  int idx = -1;
  for (auto eig : s) {
    ++idx;
    std::cout << "lambda_" << idx << " = " << eig.real() << " + " << eig.imag()
              << "j" << '\n';
  }
}

/**
 * @brief write the spectrum to a file
 * @param s const reference to a spectrum object
 * @param realout ofstream reference to the file
 *
 * This writes the spectrum to a file in two space-separated columns,
 * with the real part in the first and imaginary part in the second
 *
 * realpart_0 imagpart_0
 * realpart_1 imagpart_1
 * .
 * .
 * .
 */
void write_spectrum(const SpectrumT& s, std::ofstream&& eigsout) {
  for (auto eig : s) {
    eigsout << eig.real() << " " << eig.imag() << '\n';
  }
}

}  // namespace paladin

#endif /* SPECTRUM_UTIL_HPP_ */
<commit_msg>- move struct from local to global for intel compiler<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2016 Mike Hansen
 *
 * 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.
 */

/**
 *  \file   spectrum-util.hpp
 *  \date   Sep 29, 2016
 *  \author mike
 */

#ifndef SPECTRUM_UTIL_HPP_
#define SPECTRUM_UTIL_HPP_

#include "types.hpp"

namespace paladin {

struct EigenSorter {
  virtual ~EigenSorter() {}
  virtual bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (std::norm(L) > std::norm(R));
  }
};
struct LReal : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (L.real() > R.real());
  }
};
struct SReal : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (L.real() < R.real());
  }
};
struct LImag : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (L.imag() > R.imag());
  }
};
struct SImag : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (L.imag() < R.imag());
  }
};
struct LMag : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (std::norm(L) > std::norm(R));
  }
};
struct SMag : public EigenSorter {
  bool operator()(const EigenvalueT& L, const EigenvalueT& R) const {
    return (std::norm(L) < std::norm(R));
  }
};

/**
 * @brief sorting a spectrum in a variety of ways
 * @param s reference to a spectrum object which is sorted in place
 * @param sortStr a string indicating the type of sort (see below)
 *
 * Sort strings:
 * - SM: smallest by magnitude
 * - LM: largest by magnitude
 * - SR: smallest real part
 * - LR: largest real part
 * - SI: smallest imaginary part
 * - LI: largest imaginary part
 */
void sort_spectrum(SpectrumT& s, const std::string sortStr) {

  std::unique_ptr<EigenSorter> sorter;
  if (sortStr == "SM") {
    sorter = paladin::make_unique<SMag>();
  } else if (sortStr == "LM") {
    sorter = paladin::make_unique<LMag>();
  } else if (sortStr == "SR") {
    sorter = paladin::make_unique<SReal>();
  } else if (sortStr == "LR") {
    sorter = paladin::make_unique<LReal>();
  } else if (sortStr == "SI") {
    sorter = paladin::make_unique<SImag>();
  } else if (sortStr == "LI") {
    sorter = paladin::make_unique<LImag>();
  } else {
    sorter = paladin::make_unique<LMag>();
  }
  std::sort(s.begin(), s.end(), *sorter);
}

/**
 * @brief print the spectrum to stdout
 * @param s const reference to a spectrum object
 */
void show_spectrum(const SpectrumT& s) {
  int idx = -1;
  for (auto eig : s) {
    ++idx;
    std::cout << "lambda_" << idx << " = " << eig.real() << " + " << eig.imag()
              << "j" << '\n';
  }
}

/**
 * @brief write the spectrum to a file
 * @param s const reference to a spectrum object
 * @param realout ofstream reference to the file
 *
 * This writes the spectrum to a file in two space-separated columns,
 * with the real part in the first and imaginary part in the second
 *
 * realpart_0 imagpart_0
 * realpart_1 imagpart_1
 * .
 * .
 * .
 */
void write_spectrum(const SpectrumT& s, std::ofstream&& eigsout) {
  for (auto eig : s) {
    eigsout << eig.real() << " " << eig.imag() << '\n';
  }
}

}  // namespace paladin

#endif /* SPECTRUM_UTIL_HPP_ */
<|endoftext|>


<commit_before>/***************************************************************************
 *  io/wincall_file.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2005-2006 Roman Dementiev <dementiev@ira.uka.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <stxxl/bits/io/wincall_file.h>

#if STXXL_HAVE_WINCALL_FILE

#include <stxxl/bits/io/request_impl_basic.h>
#include <stxxl/bits/common/debug.h>

#include <windows.h>

__STXXL_BEGIN_NAMESPACE

void wincall_file::serve(const request * req) throw (io_error)
{
    scoped_mutex_lock fd_lock(fd_mutex);
    assert(req->get_file() == this);
    offset_type offset = req->get_offset();
    void * buffer = req->get_buffer();
    size_type bytes = req->get_size();
    request::request_type type = req->get_type();

    if (bytes > 32 * 1024 * 1024) {
        STXXL_ERRMSG("Using a block size larger than 32 MiB may not work with the " << io_type() << " filetype");
    }

    HANDLE handle = file_des;
    LARGE_INTEGER desired_pos;
    desired_pos.QuadPart = offset;
    if (!SetFilePointerEx(handle, desired_pos, NULL, FILE_BEGIN))
    {
        stxxl_win_lasterror_exit("SetFilePointerEx in wincall_request::serve()" <<
                                 " offset=" << offset <<
                                 " this=" << this <<
                                 " buffer=" << buffer <<
                                 " bytes=" << bytes <<
                                 " type=" << ((type == request::READ) ? "READ" : "WRITE"),
                                 io_error);
    }
    else
    {
        stats::scoped_read_write_timer read_write_timer(bytes, type == request::WRITE);

        if (type == request::READ)
        {
            STXXL_DEBUGMON_DO(io_started(buffer));
            DWORD NumberOfBytesRead = 0;
            if (!ReadFile(handle, buffer, bytes, &NumberOfBytesRead, NULL))
            {
                stxxl_win_lasterror_exit("ReadFile" <<
                                         " this=" << this <<
                                         " offset=" << offset <<
                                         " buffer=" << buffer <<
                                         " bytes=" << bytes <<
                                         " type=" << ((type == request::READ) ? "READ" : "WRITE") <<
                                         " NumberOfBytesRead= " << NumberOfBytesRead,
                                         io_error);
            } else if (NumberOfBytesRead != bytes) {
                stxxl_win_lasterror_exit(" partial read: missing " << (bytes - NumberOfBytesRead) << " out of " << bytes << " bytes",
                                         io_error);
            }

            STXXL_DEBUGMON_DO(io_finished(buffer));
        }
        else
        {
            STXXL_DEBUGMON_DO(io_started(buffer));

            DWORD NumberOfBytesWritten = 0;
            if (!WriteFile(handle, buffer, bytes, &NumberOfBytesWritten, NULL))
            {
                stxxl_win_lasterror_exit("WriteFile" <<
                                         " this=" << this <<
                                         " offset=" << offset <<
                                         " buffer=" << buffer <<
                                         " bytes=" << bytes <<
                                         " type=" << ((type == request::READ) ? "READ" : "WRITE") <<
                                         " NumberOfBytesWritten= " << NumberOfBytesWritten,
                                         io_error);
            } else if (NumberOfBytesRead != bytes) {
                stxxl_win_lasterror_exit(" partial write: missing " << (bytes - NumberOfBytesWritten) << " out of " << bytes << " bytes",
                                         io_error);
            }

            STXXL_DEBUGMON_DO(io_finished(buffer));
        }
    }
}

const char * wincall_file::io_type() const
{
    return "wincall";
}

__STXXL_END_NAMESPACE

#endif  // #if STXXL_HAVE_WINCALL_FILE
// vim: et:ts=4:sw=4
<commit_msg>try again to fix partial read/write error message in wincall_file<commit_after>/***************************************************************************
 *  io/wincall_file.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2005-2006 Roman Dementiev <dementiev@ira.uka.de>
 *
 *  Distributed under the Boost Software License, Version 1.0.
 *  (See accompanying file LICENSE_1_0.txt or copy at
 *  http://www.boost.org/LICENSE_1_0.txt)
 **************************************************************************/

#include <stxxl/bits/io/wincall_file.h>

#if STXXL_HAVE_WINCALL_FILE

#include <stxxl/bits/io/request_impl_basic.h>
#include <stxxl/bits/common/debug.h>

#include <windows.h>

__STXXL_BEGIN_NAMESPACE

void wincall_file::serve(const request * req) throw (io_error)
{
    scoped_mutex_lock fd_lock(fd_mutex);
    assert(req->get_file() == this);
    offset_type offset = req->get_offset();
    void * buffer = req->get_buffer();
    size_type bytes = req->get_size();
    request::request_type type = req->get_type();

    if (bytes > 32 * 1024 * 1024) {
        STXXL_ERRMSG("Using a block size larger than 32 MiB may not work with the " << io_type() << " filetype");
    }

    HANDLE handle = file_des;
    LARGE_INTEGER desired_pos;
    desired_pos.QuadPart = offset;
    if (!SetFilePointerEx(handle, desired_pos, NULL, FILE_BEGIN))
    {
        stxxl_win_lasterror_exit("SetFilePointerEx in wincall_request::serve()" <<
                                 " offset=" << offset <<
                                 " this=" << this <<
                                 " buffer=" << buffer <<
                                 " bytes=" << bytes <<
                                 " type=" << ((type == request::READ) ? "READ" : "WRITE"),
                                 io_error);
    }
    else
    {
        stats::scoped_read_write_timer read_write_timer(bytes, type == request::WRITE);

        if (type == request::READ)
        {
            STXXL_DEBUGMON_DO(io_started(buffer));
            DWORD NumberOfBytesRead = 0;
            if (!ReadFile(handle, buffer, bytes, &NumberOfBytesRead, NULL))
            {
                stxxl_win_lasterror_exit("ReadFile" <<
                                         " this=" << this <<
                                         " offset=" << offset <<
                                         " buffer=" << buffer <<
                                         " bytes=" << bytes <<
                                         " type=" << ((type == request::READ) ? "READ" : "WRITE") <<
                                         " NumberOfBytesRead= " << NumberOfBytesRead,
                                         io_error);
            } else if (NumberOfBytesRead != bytes) {
                stxxl_win_lasterror_exit(" partial read: missing " << (bytes - NumberOfBytesRead) << " out of " << bytes << " bytes",
                                         io_error);
            }

            STXXL_DEBUGMON_DO(io_finished(buffer));
        }
        else
        {
            STXXL_DEBUGMON_DO(io_started(buffer));

            DWORD NumberOfBytesWritten = 0;
            if (!WriteFile(handle, buffer, bytes, &NumberOfBytesWritten, NULL))
            {
                stxxl_win_lasterror_exit("WriteFile" <<
                                         " this=" << this <<
                                         " offset=" << offset <<
                                         " buffer=" << buffer <<
                                         " bytes=" << bytes <<
                                         " type=" << ((type == request::READ) ? "READ" : "WRITE") <<
                                         " NumberOfBytesWritten= " << NumberOfBytesWritten,
                                         io_error);
            } else if (NumberOfBytesWritten != bytes) {
                stxxl_win_lasterror_exit(" partial write: missing " << (bytes - NumberOfBytesWritten) << " out of " << bytes << " bytes",
                                         io_error);
            }

            STXXL_DEBUGMON_DO(io_finished(buffer));
        }
    }
}

const char * wincall_file::io_type() const
{
    return "wincall";
}

__STXXL_END_NAMESPACE

#endif  // #if STXXL_HAVE_WINCALL_FILE
// vim: et:ts=4:sw=4
<|endoftext|>


<commit_before><commit_msg>Add support for ISO 2022 SS2 code.<commit_after><|endoftext|>


<commit_before><commit_msg>Angle style param should respect numeric value from JS Function (#1826)<commit_after><|endoftext|>


<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//

#include <ctime>

#include "chrono/core/ChFileutils.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChBodyEasy.h"
#include "chrono/lcp/ChLcpIterativeMINRES.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_fea/ChElementShellANCF.h"
#include "chrono_fea/ChMesh.h"
#include "chrono_fea/ChLinkPointFrame.h"
#include "chrono_fea/ChLinkDirFrame.h"

using namespace chrono;
using namespace fea;

double step_size = 1e-3;
double sim_time = 0.5;

int main(int argc, char* argv[]) {
    // If no command line arguments, run in "performance" mode and only report run time.
    // Otherwise, generate output files to verify correctness.
    bool output = (argc > 1);

    if (output) {
        GetLog() << "Output file: ../TEST_SHELL_ANCF/tip_position.txt\n";
    } else {
        GetLog() << "Running in performance test mode.\n";
    }

    // --------------------------
    // Create the physical system
    // --------------------------
    ChSystem my_system;

    my_system.Set_G_acc(ChVector<>(0, 0, -9.81));

    // Create a mesh, that is a container for groups
    // of elements and their referenced nodes.
    ChSharedPtr<ChMesh> my_mesh(new ChMesh);
    int numFlexBody = 1;
    // Geometry of the plate
    double plate_lenght_x = 1;
    double plate_lenght_y = 0.01;
    double plate_lenght_z = 0.1;  // small thickness
    // Specification of the mesh
    int numDiv_x = 10;
    int numDiv_y = 1;
    int numDiv_z = 1;
    int N_x = numDiv_x + 1;
    int N_y = numDiv_y + 1;
    int N_z = numDiv_z + 1;
    // Number of elements in the z direction is considered as 1
    int TotalNumElements = numDiv_x * numDiv_y;
    //(1+1) is the number of nodes in the z direction
    int TotalNumNodes = (numDiv_x + 1) * (numDiv_y + 1);  // Or *(numDiv_z+1) for multilayer
    // For uniform mesh
    double dx = plate_lenght_x / numDiv_x;
    double dy = plate_lenght_y / numDiv_y;
    double dz = plate_lenght_z / numDiv_z;
    int MaxMNUM = 0;
    int MTYPE = 0;
    int MaxLayNum = 0;

    // There is a limitation now as follows
    //  Max #element is 1000;
    //  Max #Layer   is 75
    //  Only Orthotropic material
    ChMatrixDynamic<double> COORDFlex(TotalNumNodes, 6);
    ChMatrixDynamic<double> VELCYFlex(TotalNumNodes, 6);
    ChMatrixDynamic<int> NumNodes(TotalNumElements, 4);
    ChMatrixDynamic<int> LayNum(TotalNumElements, 1);
    ChMatrixDynamic<int> NDR(TotalNumNodes, 6);
    ChMatrixDynamic<double> ElemLengthXY(TotalNumElements, 2);
    ChMatrixNM<double, 10, 12> MPROP;
    ChMatrixNM<int, 10, 7> MNUM;
    ChMatrixNM<int, 10, 1> NumLayer;

    // ChMatrixNM<double> LayPROP(10, 7, 2);
    double LayPROP[10][7][2];

    // ------------
    // Element data
    // ------------
    for (int i = 0; i < TotalNumElements; i++) {
        // All the elements blong to the same layer, e.g layer number 1.
        LayNum(i, 0) = 1;
        // Node number of the 4 nodes which creates element i.
        // The nodes are distributed this way. First in the x direction for constant y when max x is reached go to the
        // next level for y by doing the same   distribution but for y+1 and keep doing until y limit is riched. Node
        // number start from 1.
        NumNodes(i, 0) = (i / (numDiv_x)) * (N_x) + i % numDiv_x;
        NumNodes(i, 1) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1;
        NumNodes(i, 2) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + N_x;
        NumNodes(i, 3) = (i / (numDiv_x)) * (N_x) + i % numDiv_x + 1 + N_x;

        // Element length is a fixed number in both direction. (uniform distribution of nodes in both directions)
        ElemLengthXY(i, 0) = dx;
        ElemLengthXY(i, 1) = dz;

        if (MaxLayNum < LayNum(i, 0)) {
            MaxLayNum = LayNum(i, 0);
        }
    }

    // -----------------------
    // NDR,COORDFlex,VELCYFlex
    // -----------------------

    for (int i = 0; i < TotalNumNodes; i++) {
        // If the node is the first node from the left side fix the x,y,z degree of freedom+ d/dx, d/dy,d/dz as well. 1
        // for constrained 0 for ...
        //-The NDR array is used to define the degree of freedoms that are constrained in the 6 variable explained
        // above.
        NDR(i, 0) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
        NDR(i, 1) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
        NDR(i, 2) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
        NDR(i, 3) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
        NDR(i, 4) = (i % (numDiv_x + 1) == 0) ? 1 : 0;
        NDR(i, 5) = (i % (numDiv_x + 1) == 0) ? 1 : 0;

        //-COORDFlex are the initial coordinates for each node,
        // the first three are the position and the last three are the slope coordinates for the tangent vector.
        // Note that i starts from 0 but nodes starts from 1
        COORDFlex(i, 0) = (i % (numDiv_x + 1)) * dx;
        COORDFlex(i, 1) = (i) / ((numDiv_x + 1) * (numDiv_y + 1)) * dy;
        COORDFlex(i, 2) = (i / (numDiv_x + 1)) % (numDiv_y + 1) * dz;
        COORDFlex(i, 3) = 0;
        COORDFlex(i, 4) = 1;
        COORDFlex(i, 5) = 0;

        //-VELCYFlex iss essentially the same as COORDFlex, but for the initial velocity instead of position.
        // let's assume zero initilal velocity for nodes in the
        VELCYFlex(i, 0) = 0;
        VELCYFlex(i, 1) = 0;
        VELCYFlex(i, 2) = 0;
        VELCYFlex(i, 3) = 0;
        VELCYFlex(i, 4) = 0;
        VELCYFlex(i, 5) = 0;
    }

    // ----------
    // Layer Data
    // ----------
    for (int i = 0; i < MaxLayNum; i++) {
        NumLayer(i, 0) = i + 1;
        // For each layer define some properties
        // For multilayer problem the user should modify the following loop as they would like
        for (int j = 0; j < NumLayer(i, 0); j++) {
            LayPROP[i][j][0] = dy;  // Layerheight
            LayPROP[i][j][1] = 0;   // PlyAngle
            MNUM[i][j] = 1;         // Material_ID
            if (MaxMNUM < MNUM(i, j))
                MaxMNUM = MNUM(i, j);
        }
    }

    // -------------
    // Material Data
    // -------------
    for (int i = 0; i < MaxMNUM; i++) {
        MTYPE = 2;

        if (MTYPE == 1) {
            MPROP(i, 0) = 500;      // Density [kg/m3]
            MPROP(i, 1) = 2.1E+07;  // H(m)
            MPROP(i, 2) = 2.1E+07;  // E(Pa)/nu
            MPROP(i, 3) = 2.1E+07;  // G(Pa)
        } else if (MTYPE == 2) {
            MPROP(i, 0) = 500;      // Density [kg/m3]
            MPROP(i, 1) = 2.1E+07;  // Ex
            MPROP(i, 2) = 2.1E+07;  // Ey
            MPROP(i, 3) = 2.1E+07;  // Ez
            // Additional information for the Type 2 of Material.
            MPROP(i, 4) = 0.3;            // nuxy
            MPROP(i, 5) = 0.3;            // nuxz
            MPROP(i, 6) = 0.3;            // nuyz
            MPROP(i, 7) = 8.0769231E+06;  // Gxy
            MPROP(i, 8) = 8.0769231E+06;  // Gxz
            MPROP(i, 9) = 8.0769231E+06;  // Gyz
        }
    }

    int i = 0;
    while (i < TotalNumNodes) {
        ChSharedPtr<ChNodeFEAxyzD> node(
            new ChNodeFEAxyzD(ChVector<>(COORDFlex(i, 0), COORDFlex(i, 1), COORDFlex(i, 2)),
                              ChVector<>(COORDFlex(i, 3), COORDFlex(i, 4), COORDFlex(i, 5))));
        node->SetMass(0.0);
        my_mesh->AddNode(node);
        if (NDR(i, 0) == 1 && NDR(i, 1) == 1 && NDR(i, 2) == 1 && NDR(i, 3) == 1 && NDR(i, 4) == 1 && NDR(i, 5) == 1) {
            node->SetFixed(true);
        }
        i++;
    }

    ChSharedPtr<ChNodeFEAxyzD> nodetip(my_mesh->GetNode(TotalNumNodes - 1).DynamicCastTo<ChNodeFEAxyzD>());

    int elemcount = 0;
    while (elemcount < TotalNumElements) {
        ChSharedPtr<ChElementShellANCF> element(new ChElementShellANCF);
        // Save material data into InertFlexVec(98x1) at each layer
        ChMatrixNM<double, 98, 1> InertFlexVec;
        InertFlexVec.Reset();
        double TotalThickness;  // element thickness
        TotalThickness = 0.0;
        int i = elemcount;
        for (int j = 0; j < NumLayer(LayNum(i, 0) - 1, 0); j++) {
            int ij = 14 * j;
            InertFlexVec(ij) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][0];  // Density
            InertFlexVec(ij + 1) = ElemLengthXY(i, 0);                   // EL
            InertFlexVec(ij + 2) = ElemLengthXY(i, 1);                   // EW
            InertFlexVec(ij + 3) = LayPROP[LayNum(i, 0) - 1][j][0];      // Thickness per layer
            TotalThickness += InertFlexVec(ij + 3);
            InertFlexVec(ij + 4) = LayPROP[LayNum(i, 0) - 1][j][1];           // Fiber angle
            InertFlexVec(ij + 5) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][1];   // Ex
            InertFlexVec(ij + 6) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][2];   // Ey
            InertFlexVec(ij + 7) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][3];   // Ez
            InertFlexVec(ij + 8) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][4];   // nuxy
            InertFlexVec(ij + 9) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][5];   // nuxz
            InertFlexVec(ij + 10) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][6];  // nuyz
            InertFlexVec(ij + 11) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][7];  // Gxy
            InertFlexVec(ij + 12) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][8];  // Gxz
            InertFlexVec(ij + 13) = MPROP[MNUM[LayNum(i, 0) - 1][j] - 1][9];  // Gyz
        }

        ChMatrixNM<double, 7, 2> GaussZRange;
        GaussZRange.Reset();
        double CurrentHeight = 0.0;
        for (int j = 0; j < NumLayer(LayNum(i, 0) - 1, 0); j++) {
            double AA = (CurrentHeight / TotalThickness - 0.5) * 2.0;
            CurrentHeight += LayPROP[LayNum(i, 0) - 1][j][0];
            double AAA = (CurrentHeight / TotalThickness - 0.5) * 2.0;
            GaussZRange(j, 0) = AA;
            GaussZRange(j, 1) = AAA;
        }

        element->SetInertFlexVec(InertFlexVec);
        element->SetGaussZRange(GaussZRange);
        element->SetNodes(my_mesh->GetNode(NumNodes[elemcount][0]).DynamicCastTo<ChNodeFEAxyzD>(),
                          my_mesh->GetNode(NumNodes[elemcount][1]).DynamicCastTo<ChNodeFEAxyzD>(),
                          my_mesh->GetNode(NumNodes[elemcount][2]).DynamicCastTo<ChNodeFEAxyzD>(),
                          my_mesh->GetNode(NumNodes[elemcount][3]).DynamicCastTo<ChNodeFEAxyzD>());
        element->SetNumLayers(NumLayer(LayNum(i, 0) - 1, 0));
        element->SetThickness(TotalThickness);
        element->SetAlphaDamp(0.00);

        element->Setdt(0.001);                     // dt to calculate DampingCoefficient
        element->SetGravityOn(true);               // turn gravity on/off
        ChMatrixNM<double, 35, 1> StockAlpha_EAS;  // StockAlpha(5*7,1): Max #Layer is 7
        StockAlpha_EAS.Reset();
        element->SetStockAlpha(StockAlpha_EAS);
        my_mesh->AddElement(element);
        elemcount++;
    }
    // Switch off mesh class gravity (ANCF shell elements have a custom implementation)
    my_mesh->SetAutomaticGravity(false);

    // Remember to add the mesh to the system!
    my_system.Add(my_mesh);

    // Perform a dynamic time integration:
    my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_MINRES);
    ChLcpIterativeMINRES* msolver = (ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed();
    msolver->SetDiagonalPreconditioning(true);
    my_system.SetIterLCPmaxItersSpeed(100);
    my_system.SetTolForce(1e-10);

    my_system.SetIntegrationType(ChSystem::INT_HHT);
    ChSharedPtr<ChTimestepperHHT> mystepper = my_system.GetTimestepper().DynamicCastTo<ChTimestepperHHT>();
    mystepper->SetAlpha(-0.2);
    mystepper->SetMaxiters(100);
    mystepper->SetTolerance(1e-5);
    mystepper->SetTolerance(1e-5);
    mystepper->SetMode(ChTimestepperHHT::POSITION);
    mystepper->SetScaling(true);

    // Mark completion of system construction
    my_system.SetupInitial();

    // ---------------
    // Simulation loop
    // ---------------

    if (output) {
        // Create output directory (if it does not already exist).
        if (ChFileutils::MakeDirectory("../TEST_SHELL_ANCF") < 0) {
            GetLog() << "Error creating directory ../TEST_SHELL_ANCF\n";
            return 1;
        }

        // Initialize the output stream and set precision.
        utils::CSV_writer out("\t");

        out.stream().setf(std::ios::scientific | std::ios::showpos);
        out.stream().precision(6);

        // Simulate to final time, while saving position of tip node.
        while (my_system.GetChTime() < sim_time) {
            my_system.DoStepDynamics(step_size);
            out << my_system.GetChTime() << nodetip->GetPos() << std::endl;
        }

        // Write results to output file.
        out.write_to_file("../TEST_SHELL_ANCF/tip_position.txt");
    } else {
        // Initialize total number of iterations and timer.
        int Iterations = 0;
        double start = std::clock();

        // Simulate to final time, while accumulating number of iterations.
        while (my_system.GetChTime() < sim_time) {
            my_system.DoStepDynamics(step_size);
            Iterations += mystepper->GetNumIterations();
        }

        // Report run time and total number of iterations.
        double duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
        GetLog() << "Simulation Time: " << duration << "   Number of iterations: " << Iterations << "\n";
    }

    return 0;
}
<commit_msg>Update test to reflect changes to ChElementShellANCF API<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2013 Project Chrono
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//

#include <ctime>

#include "chrono/core/ChFileutils.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChBodyEasy.h"
#include "chrono/lcp/ChLcpIterativeMINRES.h"
#include "chrono/utils/ChUtilsInputOutput.h"

#include "chrono_fea/ChElementShellANCF.h"
#include "chrono_fea/ChMesh.h"
#include "chrono_fea/ChLinkPointFrame.h"
#include "chrono_fea/ChLinkDirFrame.h"

using namespace chrono;
using namespace fea;

double step_size = 1e-3;
double sim_time = 0.1;

int main(int argc, char* argv[]) {
    // If no command line arguments, run in "performance" mode and only report run time.
    // Otherwise, generate output files to verify correctness.
    bool output = (argc > 1);
    if (output) {
        GetLog() << "Output file: ../TEST_SHELL_ANCF/tip_position.txt\n";
    } else {
        GetLog() << "Running in performance test mode.\n";
    }

    // --------------------------
    // Create the physical system
    // --------------------------
    ChSystem my_system;

    my_system.Set_G_acc(ChVector<>(0, 0, -9.81));

    // Create a mesh, that is a container for groups
    // of elements and their referenced nodes.
    ChSharedPtr<ChMesh> my_mesh(new ChMesh);
    // Geometry of the plate
    double plate_lenght_x = 1;
    double plate_lenght_y = 0.01;
    double plate_lenght_z = 0.1;  // small thickness
    // Specification of the mesh
    int numDiv_x = 10;
    int numDiv_y = 1;
    int numDiv_z = 1;
    int N_x = numDiv_x + 1;
    int N_y = numDiv_y + 1;
    int N_z = numDiv_z + 1;
    // Number of elements in the z direction is considered as 1
    int TotalNumElements = numDiv_x * numDiv_y;
    //(1+1) is the number of nodes in the z direction
    int TotalNumNodes = (numDiv_x + 1) * (numDiv_y + 1);  // Or *(numDiv_z+1) for multilayer
    // Element dimensions (uniform grid)
    double dx = plate_lenght_x / numDiv_x;
    double dy = plate_lenght_y / numDiv_y;
    double dz = plate_lenght_z / numDiv_z;

    // Create and add the nodes

    for (int i = 0; i < TotalNumNodes; i++) {
        // Parametric location and direction of nodal coordinates
        double loc_x = (i % (numDiv_x + 1)) * dx;
        double loc_y = (i) / ((numDiv_x + 1) * (numDiv_y + 1)) * dy;
        double loc_z = (i / (numDiv_x + 1)) % (numDiv_y + 1) * dz;
        double dir_x = 0;
        double dir_y = 1;
        double dir_z = 0;

        // Create the node
        ChSharedPtr<ChNodeFEAxyzD> node(
            new ChNodeFEAxyzD(ChVector<>(loc_x, loc_y, loc_z), ChVector<>(dir_x, dir_y, dir_z)));
        node->SetMass(0);
        // Fix all nodes along the axis X=0
        if (i % (numDiv_x + 1) == 0)
            node->SetFixed(true);

        // Add node to mesh
        my_mesh->AddNode(node);
    }

    // ?? Do we need to declare nodes by dynamic casting ???

    // Create an isotropic material
    // Only one layer
    double rho = 500;
    double E = 2.1e7;
    double nu = 0.3;
    ChSharedPtr<ChMaterialShellANCF> mat(new ChMaterialShellANCF(rho, E, nu));

    // Create the elements
    for (int i = 0; i < TotalNumElements; i++) {
        // Definition of nodes forming an element
        int node0 = (i / (numDiv_x)) * (N_x) + i % numDiv_x;
        int node1 = (i / (numDiv_x)) * (N_x)+i % numDiv_x + 1;
        int node2 = (i / (numDiv_x)) * (N_x)+i % numDiv_x + N_x;
        int node3 = (i / (numDiv_x)) * (N_x)+i % numDiv_x + 1 + N_x;

        // Create the element and set its nodes.
        ChSharedPtr<ChElementShellANCF> element(new ChElementShellANCF);
        element->SetNodes(my_mesh->GetNode(node0).DynamicCastTo<ChNodeFEAxyzD>(),
            my_mesh->GetNode(node1).DynamicCastTo<ChNodeFEAxyzD>(),
            my_mesh->GetNode(node2).DynamicCastTo<ChNodeFEAxyzD>(),
            my_mesh->GetNode(node3).DynamicCastTo<ChNodeFEAxyzD>());

        // Element length is a fixed number in both direction. (uniform distribution of nodes in both directions)
        element->SetDimensions(dx, dz);
        // Single layer
        element->AddLayer(dy, 0 * CH_C_DEG_TO_RAD, mat); // Thickness: dy;  Ply angle: 0.
        // Set other element properties
        element->SetAlphaDamp(0.0);   // Structural damping for this
        element->SetGravityOn(true);  // element calculates its own gravitational load
        // Add element to mesh
        my_mesh->AddElement(element);
    }

    // Switch off mesh class gravity (ANCF shell elements have a custom implementation)
    my_mesh->SetAutomaticGravity(false);

    // Mark completion of system construction
    my_system.SetupInitial();

    ChSharedPtr<ChNodeFEAxyzD> nodetip(my_mesh->GetNode(TotalNumNodes - 1).DynamicCastTo<ChNodeFEAxyzD>());

    // Switch off mesh class gravity (ANCF shell elements have a custom implementation)
    my_mesh->SetAutomaticGravity(false);

    // Remember to add the mesh to the system!
    my_system.Add(my_mesh);

    // Perform a dynamic time integration:
    my_system.SetLcpSolverType(ChSystem::LCP_ITERATIVE_MINRES);
    ChLcpIterativeMINRES* msolver = (ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed();
    msolver->SetDiagonalPreconditioning(true);
    my_system.SetIterLCPmaxItersSpeed(100);
    my_system.SetTolForce(1e-10);

    my_system.SetIntegrationType(ChSystem::INT_HHT);
    ChSharedPtr<ChTimestepperHHT> mystepper = my_system.GetTimestepper().DynamicCastTo<ChTimestepperHHT>();
    mystepper->SetAlpha(-0.2);
    mystepper->SetMaxiters(100);
    mystepper->SetTolerance(1e-5);
    mystepper->SetTolerance(1e-5);
    mystepper->SetMode(ChTimestepperHHT::POSITION);
    mystepper->SetScaling(true);

    // Mark completion of system construction
    my_system.SetupInitial();

    // ---------------
    // Simulation loop
    // ---------------

    if (output) {
        // Create output directory (if it does not already exist).
        if (ChFileutils::MakeDirectory("../TEST_SHELL_ANCF") < 0) {
            GetLog() << "Error creating directory ../TEST_SHELL_ANCF\n";
            return 1;
        }

        // Initialize the output stream and set precision.
        utils::CSV_writer out("\t");

        out.stream().setf(std::ios::scientific | std::ios::showpos);
        out.stream().precision(6);

        // Simulate to final time, while saving position of tip node.
        while (my_system.GetChTime() < sim_time) {
            my_system.DoStepDynamics(step_size);
            out << my_system.GetChTime() << nodetip->GetPos() << std::endl;
        }

        // Write results to output file.
        out.write_to_file("../TEST_SHELL_ANCF/tip_position.txt");
    } else {
        // Initialize total number of iterations and timer.
        int Iterations = 0;
        double start = std::clock();

        // Simulate to final time, while accumulating number of iterations.
        while (my_system.GetChTime() < sim_time) {
            my_system.DoStepDynamics(step_size);
            Iterations += mystepper->GetNumIterations();
        }

        // Report run time and total number of iterations.
        double duration = (std::clock() - start) / (double)CLOCKS_PER_SEC;
        GetLog() << "Simulation Time: " << duration << "   Number of iterations: " << Iterations << "\n";
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "unit_test.h"
#include <cachelot/io_buffer.h>
#include <cstdlib>

namespace {

using namespace cachelot;

BOOST_AUTO_TEST_SUITE(test_io_buffer)

BOOST_AUTO_TEST_CASE(test_io_buffer_basic) {
    io_buffer buf(0, 16);
    BOOST_CHECK_EQUAL(0, buf.capacity());
    static const char pattern[] = "Test string";
    char * ptr = buf.begin_write(sizeof(pattern));
    std::sprintf(ptr, pattern);
    buf.complete_write(sizeof(pattern));
    BOOST_CHECK_EQUAL(buf.non_read(), sizeof(pattern));
    bytes read = buf.try_read_until(bytes::from_literal("\0"));
    BOOST_CHECK_EQUAL(read.length(), sizeof(pattern));
    BOOST_CHECK(std::memcmp(read.begin(), pattern, sizeof(pattern) - 1) == 0);
    BOOST_CHECK_THROW(buf.begin_write(17), std::length_error);
    buf.discard_all();
    BOOST_CHECK_EQUAL(buf.non_read(), 0);
    ptr = buf.begin_write(16);
    std::memset(ptr, 'X', 16);
    buf.complete_write(16);
    read = buf.try_read_until(bytes::from_literal("XXXXXXXXXXXXXXXX"));
    BOOST_CHECK_EQUAL(read.length(), 16);
}

BOOST_AUTO_TEST_SUITE_END()

} // anonymouse namespace

<commit_msg>io_buffer discard_written test<commit_after>#include "unit_test.h"
#include <cachelot/io_buffer.h>
#include <cstdlib>

namespace {

using namespace cachelot;

BOOST_AUTO_TEST_SUITE(test_io_buffer)

BOOST_AUTO_TEST_CASE(test_io_buffer_basic) {
    io_buffer buf(0, 16);
    BOOST_CHECK_EQUAL(0, buf.capacity());
    static const char pattern[] = "Test string";
    // write test pattern
    char * ptr = buf.begin_write(sizeof(pattern));
    std::sprintf(ptr, pattern);
    buf.complete_write(sizeof(pattern));
    BOOST_CHECK_EQUAL(buf.non_read(), sizeof(pattern));
    // read from buffer
    bytes read = buf.try_read_until(bytes::from_literal("\0"));
    BOOST_CHECK_EQUAL(read.length(), sizeof(pattern));
    BOOST_CHECK(std::memcmp(read.begin(), pattern, sizeof(pattern) - 1) == 0);
    BOOST_CHECK_THROW(buf.begin_write(17), std::length_error);
    // reset buffer
    buf.discard_all();
    BOOST_CHECK_EQUAL(buf.non_read(), 0);
    // write 16 bytes of nothing and discard it immediately
    ptr = buf.begin_write(16);
    buf.complete_write(16);
    buf.discard_written();
    // write 16 bytes of 'X'
    ptr = buf.begin_write(16);
    std::memset(ptr, 'X', 16);
    buf.complete_write(16);
    // read and check
    read = buf.try_read_until(bytes::from_literal("XXXXXXXXXXXXXXXX"));
    BOOST_CHECK_EQUAL(read.length(), 16);
}

BOOST_AUTO_TEST_SUITE_END()

} // anonymouse namespace

<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_EXCEPTIONS_HH
#define DUNE_STUFF_COMMON_EXCEPTIONS_HH

#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/deprecated.hh>

#ifdef DUNE_THROW
# undef DUNE_THROW
#endif

/**
 *  \brief Macro to throw a colorfull exception.
 *
 *  Example:
\code
#include <dune/stuff/common/exceptions.hh>

if (a.size() != b.size())
  DUNE_THROW(Exceptions::shapes_do_not_match,
             "size of a (" << a.size() << ") does not match the size of b (" << b.size() << ")!");
\endcode
 *  This macro is essentially copied from dune-common with added color functionality and rank information.
 *  \param  E Exception class, derived from Dune::Exception.
 *  \param  m Message in ostream notation.
 *  \see Dune::Exception
 */
#define DUNE_THROW(E, m) \
  do { \
    const std::string th__red = "\033[31m"; \
    const std::string th__brown = "\033[33m"; \
    const std::string th__clear = "\033[0m"; \
    E th__ex; \
    std::ostringstream th__msg; \
    th__msg << m; \
    std::ostringstream th__out; \
    th__out << th__red << # E << th__clear; \
    if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
      th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
    th__out << "\n"; \
    th__out << th__brown << "[" << th__clear; \
    th__out << th__red << __func__ << th__clear; \
    th__out << th__brown << "|" << th__clear; \
    th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
    if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
      th__ex.message(th__out.str()); \
    throw th__ex; \
  } while (0)
// DUNE_THROW

#define DUNE_THROW_COLORFULLY(E, m) \
  do { \
    const std::string th__red __attribute__((deprecated)) /* use DUNE_THROW instead! */ = "\033[31m"; \
    const std::string th__brown = "\033[33m"; \
    const std::string th__clear = "\033[0m"; \
    E th__ex; \
    std::ostringstream th__msg; \
    th__msg << m; \
    std::ostringstream th__out; \
    th__out << th__red << # E << th__clear; \
    if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
      th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
    th__out << "\n"; \
    th__out << th__brown << "[" << th__clear; \
    th__out << th__red << __func__ << th__clear; \
    th__out << th__brown << "|" << th__clear; \
    th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
    if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
      th__ex.message(th__out.str()); \
    throw th__ex; \
  } while (0)
// DUNE_THROW_COLORFULLY

namespace Dune {
namespace Stuff {
namespace Exceptions {

class CRTP_check_failed : public Dune::Exception {};

class shapes_do_not_match : public Dune::Exception {};

class index_out_of_range : public Dune::Exception {};

class you_are_using_this_wrong : public Dune::Exception {};

class wrong_input_given : public you_are_using_this_wrong {};

class requirements_not_met: public you_are_using_this_wrong {};

class configuration_error : public Dune::Exception {};

class conversion_error : public Dune::Exception {};

class results_are_not_as_expected : public Dune::Exception {};

class internal_error : public Dune::Exception {};

class external_error : public Dune::Exception {};

class linear_solver_failed : public Dune::Exception {};

class you_have_to_implement_this : public Dune::NotImplemented {};

} // namespace Exceptions
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_EXCEPTIONS_HH
<commit_msg>[common.exceptions] removes deprecated DUNE_THROW_COLORFULLY<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_EXCEPTIONS_HH
#define DUNE_STUFF_COMMON_EXCEPTIONS_HH

#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/deprecated.hh>

#ifdef DUNE_THROW
# undef DUNE_THROW
#endif

/**
 *  \brief Macro to throw a colorfull exception.
 *
 *  Example:
\code
#include <dune/stuff/common/exceptions.hh>

if (a.size() != b.size())
  DUNE_THROW(Exceptions::shapes_do_not_match,
             "size of a (" << a.size() << ") does not match the size of b (" << b.size() << ")!");
\endcode
 *  This macro is essentially copied from dune-common with added color functionality and rank information.
 *  \param  E Exception class, derived from Dune::Exception.
 *  \param  m Message in ostream notation.
 *  \see Dune::Exception
 */
#define DUNE_THROW(E, m) \
  do { \
    const std::string th__red = "\033[31m"; \
    const std::string th__brown = "\033[33m"; \
    const std::string th__clear = "\033[0m"; \
    E th__ex; \
    std::ostringstream th__msg; \
    th__msg << m; \
    std::ostringstream th__out; \
    th__out << th__red << # E << th__clear; \
    if (Dune::MPIHelper::getCollectiveCommunication().size() > 1) \
      th__out << " (on rank " << Dune::MPIHelper::getCollectiveCommunication().rank() << ")"; \
    th__out << "\n"; \
    th__out << th__brown << "[" << th__clear; \
    th__out << th__red << __func__ << th__clear; \
    th__out << th__brown << "|" << th__clear; \
    th__out << __FILE__ << th__brown << ":" << th__clear << th__red << __LINE__ << th__clear << th__brown << "]" << th__clear; \
    if (!th__msg.str().empty()) th__out << "\n" << th__brown << "=>" << th__clear << " " << th__msg.str(); \
      th__ex.message(th__out.str()); \
    throw th__ex; \
  } while (0)
// DUNE_THROW

namespace Dune {
namespace Stuff {
namespace Exceptions {

class CRTP_check_failed : public Dune::Exception {};

class shapes_do_not_match : public Dune::Exception {};

class index_out_of_range : public Dune::Exception {};

class you_are_using_this_wrong : public Dune::Exception {};

class wrong_input_given : public you_are_using_this_wrong {};

class requirements_not_met: public you_are_using_this_wrong {};

class configuration_error : public Dune::Exception {};

class conversion_error : public Dune::Exception {};

class results_are_not_as_expected : public Dune::Exception {};

class internal_error : public Dune::Exception {};

class external_error : public Dune::Exception {};

class linear_solver_failed : public Dune::Exception {};

class you_have_to_implement_this : public Dune::NotImplemented {};

} // namespace Exceptions
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_EXCEPTIONS_HH
<|endoftext|>


<commit_before><commit_msg>Update particle-functions.cpp<commit_after><|endoftext|>


<commit_before>#include "sfml_screen.h"

#include "../../util/log.h"

SFMLScreen::SFMLScreen(uint _magnification, bool _whole_framebuffer) :
    magnification(_magnification),
    whole_framebuffer(_whole_framebuffer),
    logical_width(whole_framebuffer ? FRAMEBUFFER_SIZE : GAMEBOY_WIDTH),
    logical_height(whole_framebuffer ? FRAMEBUFFER_SIZE : GAMEBOY_HEIGHT),
    width(logical_width*magnification),
    height(logical_height*magnification),
    pixel_size(magnification),
    window(sf::VideoMode(width, height), "Emulator", sf::Style::Titlebar | sf::Style::Close)
{
    image.create(width, height);
    window.setFramerateLimit(60);
    window.setVerticalSyncEnabled(true);
}

void SFMLScreen::draw(const FrameBuffer& buffer, const uint scroll_x, const uint scroll_y, const BGPalette& bg_palette) {
    window.clear(sf::Color::White);

    sf::Event event;

    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed) {
            window.close();
        }
    }

    set_pixels(buffer, scroll_x, scroll_y, bg_palette);
    texture.loadFromImage(image);
    sprite.setTexture(texture, true);

    window.draw(sprite);

    window.display();
}

void SFMLScreen::set_pixels(const FrameBuffer& buffer, const uint scroll_x, const uint scroll_y, const BGPalette& bg_palette) {
    for (uint y = 0; y < logical_height; y++) {
        for (uint x = 0; x < logical_width; x++) {
            uint y_in_framebuffer = (scroll_y + y) % FRAMEBUFFER_SIZE;
            uint x_in_framebuffer = (scroll_x + x) % FRAMEBUFFER_SIZE;

            if (whole_framebuffer) {
                y_in_framebuffer = y;
                x_in_framebuffer = x;
            }

            Color color = get_color(buffer.get_pixel(x_in_framebuffer, y_in_framebuffer), bg_palette);
            sf::Color pixel_color = get_real_color(color);

            set_large_pixel(x, y, pixel_color);
        }
    }
}

void SFMLScreen::set_large_pixel(uint x, uint y, sf::Color color) {
    for (unsigned w = 0; w < pixel_size; w++) {
        for (unsigned h = 0; h < pixel_size; h++) {
            image.setPixel(x * pixel_size + w, y * pixel_size + h, color);
        }
    }
}

Color SFMLScreen::get_color(GBColor color, const BGPalette& bg_palette) {
    switch (color) {
        case GBColor::Color0: return bg_palette.color0;
        case GBColor::Color1: return bg_palette.color1;
        case GBColor::Color2: return bg_palette.color2;
        case GBColor::Color3: return bg_palette.color3;
    }
}

sf::Color SFMLScreen::get_real_color(Color color) {
    switch (color) {
        case Color::White: return sf::Color(255, 255, 255);
        case Color::LightGray: return sf::Color(170, 170, 170);
        case Color::DarkGray: return sf::Color( 85,  85,  85);
        case Color::Black: return sf::Color(  0,   0,   0);
    }
}

bool SFMLScreen::is_open() {
    return window.isOpen();
}
<commit_msg>Consolidate whole_framebuffer test in SFMLScreen<commit_after>#include "sfml_screen.h"

#include "../../util/log.h"

SFMLScreen::SFMLScreen(uint _magnification, bool _whole_framebuffer) :
    magnification(_magnification),
    whole_framebuffer(_whole_framebuffer),
    logical_width(whole_framebuffer ? FRAMEBUFFER_SIZE : GAMEBOY_WIDTH),
    logical_height(whole_framebuffer ? FRAMEBUFFER_SIZE : GAMEBOY_HEIGHT),
    width(logical_width*magnification),
    height(logical_height*magnification),
    pixel_size(magnification),
    window(sf::VideoMode(width, height), "Emulator", sf::Style::Titlebar | sf::Style::Close)
{
    image.create(width, height);
    window.setFramerateLimit(60);
    window.setVerticalSyncEnabled(true);
}

void SFMLScreen::draw(const FrameBuffer& buffer, const uint scroll_x, const uint scroll_y, const BGPalette& bg_palette) {
    window.clear(sf::Color::White);

    sf::Event event;

    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed) {
            window.close();
        }
    }

    set_pixels(buffer, scroll_x, scroll_y, bg_palette);
    texture.loadFromImage(image);
    sprite.setTexture(texture, true);

    window.draw(sprite);

    window.display();
}

void SFMLScreen::set_pixels(const FrameBuffer& buffer, const uint scroll_x, const uint scroll_y, const BGPalette& bg_palette) {
    for (uint y = 0; y < logical_height; y++) {
        for (uint x = 0; x < logical_width; x++) {
            uint y_in_framebuffer = whole_framebuffer ? y : (scroll_y + y) % FRAMEBUFFER_SIZE;
            uint x_in_framebuffer = whole_framebuffer ? x : (scroll_x + x) % FRAMEBUFFER_SIZE;

            Color color = get_color(buffer.get_pixel(x_in_framebuffer, y_in_framebuffer), bg_palette);
            sf::Color pixel_color = get_real_color(color);

            set_large_pixel(x, y, pixel_color);
        }
    }
}

void SFMLScreen::set_large_pixel(uint x, uint y, sf::Color color) {
    for (unsigned w = 0; w < pixel_size; w++) {
        for (unsigned h = 0; h < pixel_size; h++) {
            image.setPixel(x * pixel_size + w, y * pixel_size + h, color);
        }
    }
}

Color SFMLScreen::get_color(GBColor color, const BGPalette& bg_palette) {
    switch (color) {
        case GBColor::Color0: return bg_palette.color0;
        case GBColor::Color1: return bg_palette.color1;
        case GBColor::Color2: return bg_palette.color2;
        case GBColor::Color3: return bg_palette.color3;
    }
}

sf::Color SFMLScreen::get_real_color(Color color) {
    switch (color) {
        case Color::White: return sf::Color(255, 255, 255);
        case Color::LightGray: return sf::Color(170, 170, 170);
        case Color::DarkGray: return sf::Color( 85,  85,  85);
        case Color::Black: return sf::Color(  0,   0,   0);
    }
}

bool SFMLScreen::is_open() {
    return window.isOpen();
}
<|endoftext|>