<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_STARMATH_INC_PARSE_HXX
#define INCLUDED_STARMATH_INC_PARSE_HXX

#include <vcl/svapp.hxx>

#include <set>

#include "types.hxx"
#include "token.hxx"
#include "error.hxx"
#include "node.hxx"

#include <boost/noncopyable.hpp>

class SmParser : boost::noncopyable
{
    OUString        m_aBufferString;
    SmToken         m_aCurToken;
    SmNodeStack     m_aNodeStack;
    SmErrDescList   m_aErrDescList;
    int             m_nCurError;
    LanguageType    m_nLang;
    sal_Int32       m_nBufferIndex,
                    m_nTokenIndex;
    sal_Int32       m_Row,
                    m_nColOff;
    bool            bImportSymNames,
                    m_bExportSymNames;

    // map of used symbols (used to reduce file size by exporting only actually used symbols)
    std::set< OUString >   m_aUsedSymbols;

    //! locale where '.' is decimal separator!
    ::com::sun::star::lang::Locale m_aDotLoc;

protected:
#if OSL_DEBUG_LEVEL > 1
    bool            IsDelimiter( const OUString &rTxt, sal_Int32 nPos );
#endif
    void            NextToken();
    sal_Int32       GetTokenIndex() const   { return m_nTokenIndex; }
    void            Replace( sal_Int32 nPos, sal_Int32 nLen, const OUString &rText );

    inline bool     TokenInGroup( sal_uLong nGroup );

    // grammar
    void    Table();
    void    Line();
    void    Expression();
    void    Relation();
    void    Sum();
    void    Product();
    void    SubSup(sal_uLong nActiveGroup);
    void    OpSubSup();
    void    Power();
    void    Blank();
    void    Term(bool bGroupNumberIdent);
    void    Escape();
    void    Operator();
    void    Oper();
    void    UnOper();
    void    Align();
    void    FontAttribut();
    void    Attribut();
    void    Font();
    void    FontSize();
    void    Color();
    void    Brace();
    void    Bracebody(bool bIsLeftRight);
    void    Function();
    void    Binom();
    void    Stack();
    void    Matrix();
    void    Special();
    void    GlyphSpecial();
    // end of grammar

    LanguageType    GetLanguage() const { return m_nLang; }
    void            SetLanguage( LanguageType nNewLang ) { m_nLang = nNewLang; }

    void    Error(SmParseError Error);

    void    ClearUsedSymbols()                              { m_aUsedSymbols.clear(); }
    void    AddToUsedSymbols( const OUString &rSymbolName ) { m_aUsedSymbols.insert( rSymbolName ); }

public:
                 SmParser();

    /** Parse rBuffer to formula tree */
    SmNode      *Parse(const OUString &rBuffer);
    /** Parse rBuffer to formula subtree that constitutes an expression */
    SmNode      *ParseExpression(const OUString &rBuffer);

    const OUString & GetText() const { return m_aBufferString; };

    bool        IsImportSymbolNames() const        { return bImportSymNames; }
    void        SetImportSymbolNames(bool bVal)    { bImportSymNames = bVal; }
    bool        IsExportSymbolNames() const        { return m_bExportSymNames; }
    void        SetExportSymbolNames(bool bVal)    { m_bExportSymNames = bVal; }

    size_t      AddError(SmParseError Type, SmNode *pNode);
    const SmErrorDesc*  NextError();
    const SmErrorDesc*  PrevError();
    const SmErrorDesc*  GetError(size_t i = size_t(-1) );
    static const SmTokenTableEntry* GetTokenTableEntry( const OUString &rName );
    bool    IsUsedSymbol( const OUString &rSymbolName ) const { return m_aUsedSymbols.find( rSymbolName ) != m_aUsedSymbols.end(); }
    std::set< OUString >   GetUsedSymbols() const      { return m_aUsedSymbols; }
};

inline bool SmParser::TokenInGroup( sal_uLong nGroup)
{
    return (m_aCurToken.nGroup & nGroup) ? true : false;
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Omit unused default value<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#ifndef INCLUDED_STARMATH_INC_PARSE_HXX
#define INCLUDED_STARMATH_INC_PARSE_HXX

#include <vcl/svapp.hxx>

#include <set>

#include "types.hxx"
#include "token.hxx"
#include "error.hxx"
#include "node.hxx"

#include <boost/noncopyable.hpp>

class SmParser : boost::noncopyable
{
    OUString        m_aBufferString;
    SmToken         m_aCurToken;
    SmNodeStack     m_aNodeStack;
    SmErrDescList   m_aErrDescList;
    int             m_nCurError;
    LanguageType    m_nLang;
    sal_Int32       m_nBufferIndex,
                    m_nTokenIndex;
    sal_Int32       m_Row,
                    m_nColOff;
    bool            bImportSymNames,
                    m_bExportSymNames;

    // map of used symbols (used to reduce file size by exporting only actually used symbols)
    std::set< OUString >   m_aUsedSymbols;

    //! locale where '.' is decimal separator!
    ::com::sun::star::lang::Locale m_aDotLoc;

protected:
#if OSL_DEBUG_LEVEL > 1
    bool            IsDelimiter( const OUString &rTxt, sal_Int32 nPos );
#endif
    void            NextToken();
    sal_Int32       GetTokenIndex() const   { return m_nTokenIndex; }
    void            Replace( sal_Int32 nPos, sal_Int32 nLen, const OUString &rText );

    inline bool     TokenInGroup( sal_uLong nGroup );

    // grammar
    void    Table();
    void    Line();
    void    Expression();
    void    Relation();
    void    Sum();
    void    Product();
    void    SubSup(sal_uLong nActiveGroup);
    void    OpSubSup();
    void    Power();
    void    Blank();
    void    Term(bool bGroupNumberIdent);
    void    Escape();
    void    Operator();
    void    Oper();
    void    UnOper();
    void    Align();
    void    FontAttribut();
    void    Attribut();
    void    Font();
    void    FontSize();
    void    Color();
    void    Brace();
    void    Bracebody(bool bIsLeftRight);
    void    Function();
    void    Binom();
    void    Stack();
    void    Matrix();
    void    Special();
    void    GlyphSpecial();
    // end of grammar

    LanguageType    GetLanguage() const { return m_nLang; }
    void            SetLanguage( LanguageType nNewLang ) { m_nLang = nNewLang; }

    void    Error(SmParseError Error);

    void    ClearUsedSymbols()                              { m_aUsedSymbols.clear(); }
    void    AddToUsedSymbols( const OUString &rSymbolName ) { m_aUsedSymbols.insert( rSymbolName ); }

public:
                 SmParser();

    /** Parse rBuffer to formula tree */
    SmNode      *Parse(const OUString &rBuffer);
    /** Parse rBuffer to formula subtree that constitutes an expression */
    SmNode      *ParseExpression(const OUString &rBuffer);

    const OUString & GetText() const { return m_aBufferString; };

    bool        IsImportSymbolNames() const        { return bImportSymNames; }
    void        SetImportSymbolNames(bool bVal)    { bImportSymNames = bVal; }
    bool        IsExportSymbolNames() const        { return m_bExportSymNames; }
    void        SetExportSymbolNames(bool bVal)    { m_bExportSymNames = bVal; }

    size_t      AddError(SmParseError Type, SmNode *pNode);
    const SmErrorDesc*  NextError();
    const SmErrorDesc*  PrevError();
    const SmErrorDesc*  GetError(size_t i);
    static const SmTokenTableEntry* GetTokenTableEntry( const OUString &rName );
    bool    IsUsedSymbol( const OUString &rSymbolName ) const { return m_aUsedSymbols.find( rSymbolName ) != m_aUsedSymbols.end(); }
    std::set< OUString >   GetUsedSymbols() const      { return m_aUsedSymbols; }
};

inline bool SmParser::TokenInGroup( sal_uLong nGroup)
{
    return (m_aCurToken.nGroup & nGroup) ? true : false;
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// -------------------------------------------------------------------
// Copyright 2014 nil authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above
//    copyright notice, this list of conditions and the following
//    disclaimer in the documentation and/or other materials provided
//    with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``AS
// IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// NAMESPACE EWALENA AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and
// documentation are those of the authors and should not be
// interpreted as representing official policies, either expressed or
// implied, of the nil authors.
// -------------------------------------------------------------------

#include "../include/nil/geometry_function.h"

namespace nil
{

  namespace GeometryFunction
  {

    template <int dim, typename ValueType>
    double
    HyperCube<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
				      const unsigned int                   /* component */) const
    {
      double is_in_hyper_cube = 0.;

      switch (dim)
	{

	case 1:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	case 2:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_) &&
		(p[1]<=right_) && (p[1]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	case 3:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_) &&
		(p[1]<=right_) && (p[1]>=left_) &&
		(p[2]<=right_) && (p[2]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_hyper_cube;
    }

    template <int dim, typename ValueType>
    double
    HyperBall<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
				      const unsigned int                   /* component */) const
    {
      double is_in_hyper_ball = 0.;

      const double distance = p.distance (center_);

      if (distance<=radius_)
	is_in_hyper_ball = 1.;

      return is_in_hyper_ball;
    }

    template <int dim, typename ValueType>
    double
    HalfHyperBall<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					  const unsigned int                   /* component */) const
    {
      double is_in_half_hyper_ball = 0.;

      // This is the distance to the center that refers to a
      // hyper-ball.
      const double distance = p.distance (center_);

      switch (dim)
	{

	case 2:
	  // check if we are in the upper half of the half
	  // hyper-ball. In 2d this happens if the 2-axis of the point
	  // is above or on the z-axis of the center
	  if ((p[1]>=center_[1]) &&
	      (distance<=radius_))
	      is_in_half_hyper_ball = 1.;

	  break;

	case 3:

	  // check if we are in the upper half of the half
	  // hyper-ball. In 3d this happens if the 3-axis of the point
	  // is above or on the z-axis of the center
	  if ((p[2]>=center_[2]) &&
	      (distance<=radius_))
	      is_in_half_hyper_ball = 1.;

	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      if (distance<=radius_)
	is_in_half_hyper_ball = 1.;

      return is_in_half_hyper_ball;
    }

    template <int dim, typename ValueType>
    double
    SquarePyramid<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					  const unsigned int                   /* component */) const
    {
      double is_in_square_pyramid = 0.;

      switch (dim)
	{
	case 3:

	  // Project the coordinate onto the first quadrant by using
	  // and work with its absolute value.
	  AssertThrow (false, dealii::ExcNotImplemented ());
	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_square_pyramid;
    }

    template <int dim, typename ValueType>
    double
    HexagonalPyramid<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					     const unsigned int                   /* component */) const
    {
      double is_in_hexagonal_pyramid = 0.;

      switch (dim)
	{
	case 3:

	  // Project the coordinate onto the first quadrant by using
	  // and work with its absolute value.
	  AssertThrow (false, dealii::ExcNotImplemented ());
	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_hexagonal_pyramid;
    }

  } // name GeometryDescription

} // namespace nil

// -------------- Explicit Instantiations -------------------------------

#include "geometry_function.inst"
<commit_msg>Bug fix.<commit_after>// -------------------------------------------------------------------
// Copyright 2014 nil authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above
//    copyright notice, this list of conditions and the following
//    disclaimer in the documentation and/or other materials provided
//    with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``AS
// IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// NAMESPACE EWALENA AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and
// documentation are those of the authors and should not be
// interpreted as representing official policies, either expressed or
// implied, of the nil authors.
// -------------------------------------------------------------------

#include "../include/nil/geometry_function.h"

namespace nil
{

  namespace GeometryFunction
  {

    template <int dim, typename ValueType>
    double
    HyperCube<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
				      const unsigned int                   /* component */) const
    {
      double is_in_hyper_cube = 0.;

      switch (dim)
	{

	case 1:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	case 2:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_) &&
		(p[1]<=right_) && (p[1]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	case 3:
	  {
	    if ((p[0]<=right_) && (p[0]>=left_) &&
		(p[1]<=right_) && (p[1]>=left_) &&
		(p[2]<=right_) && (p[2]>=left_))
	      is_in_hyper_cube = 1.;
	    break;
	  }

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_hyper_cube;
    }

    template <int dim, typename ValueType>
    double
    HyperBall<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
				      const unsigned int                   /* component */) const
    {
      double is_in_hyper_ball = 0.;

      const double distance = p.distance (center_);

      if (distance<=radius_)
	is_in_hyper_ball = 1.;

      return is_in_hyper_ball;
    }

    template <int dim, typename ValueType>
    double
    HalfHyperBall<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					  const unsigned int                   /* component */) const
    {
      double is_in_half_hyper_ball = 0.;

      // This is the distance to the center that refers to a
      // hyper-ball.
      const double distance = p.distance (center_);

      switch (dim)
	{

	case 2:
	  // check if we are in the upper half of the half
	  // hyper-ball. In 2d this happens if the 2-axis of the point
	  // is above or on the z-axis of the center
	  if ((p[1]>=center_[1]) &&
	      (distance<=radius_))
	    is_in_half_hyper_ball = 1.;

	  break;

	case 3:

	  // check if we are in the upper half of the half
	  // hyper-ball. In 3d this happens if the 3-axis of the point
	  // is above or on the z-axis of the center
	  if ((p[2]>=center_[2]) &&
	      (distance<=radius_))
	    is_in_half_hyper_ball = 1.;

	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_half_hyper_ball;
    }

    template <int dim, typename ValueType>
    double
    SquarePyramid<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					  const unsigned int                   /* component */) const
    {
      double is_in_square_pyramid = 0.;

      switch (dim)
	{
	case 3:

	  // Project the coordinate onto the first quadrant by using
	  // and work with its absolute value.
	  AssertThrow (false, dealii::ExcNotImplemented ());
	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_square_pyramid;
    }

    template <int dim, typename ValueType>
    double
    HexagonalPyramid<dim, ValueType>::value (const dealii::Point<dim, ValueType> &p,
					     const unsigned int                   /* component */) const
    {
      double is_in_hexagonal_pyramid = 0.;

      switch (dim)
	{
	case 3:

	  // Project the coordinate onto the first quadrant by using
	  // and work with its absolute value.
	  AssertThrow (false, dealii::ExcNotImplemented ());
	  break;

	default:
	  AssertThrow (false, dealii::ExcNotImplemented ());
	}

      return is_in_hexagonal_pyramid;
    }

  } // name GeometryDescription

} // namespace nil

// -------------- Explicit Instantiations -------------------------------

#include "geometry_function.inst"
<|endoftext|>


<commit_before>#include "SymbolFile.h"
#include "SymbolType.h"
#include "FileHelper.h"

#include <sprite2/SymType.h>
#include <gum/SymbolFile.h>

namespace ee
{

SINGLETON_DEFINITION(SymbolFile);

static const char* TAG_GEN = "gen";

SymbolFile::SymbolFile()
{
	Regist(SYM_ANIS,		"anis");
	Regist(SYM_FONTBLANK,	"fontblank");
	Regist(SYM_FREETYPE,	"freetype");
	Regist(SYM_SCRIPTS,		"scripts");
	Regist(SYM_P3DINV,		"p3dinv");
	Regist(SYM_EJOY2D,		"ejoy2d");
	Regist(SYM_TERRAIN2D,	"terrain2d");
	Regist(SYM_SHADOW,		"shadow");
	Regist(SYM_UI,			"ui");
	Regist(SYM_PSD,			"psd");
	Regist(SYM_UIWND,		"uiwnd");

	Regist(s2::SYM_SCALE9,		"scale9");
	Regist(s2::SYM_ICON,		"icon");
	Regist(s2::SYM_TEXTURE,		"texture");
	Regist(s2::SYM_TEXTBOX,		"text");
	Regist(s2::SYM_COMPLEX,		"complex");
	Regist(s2::SYM_ANIMATION,	"anim");
	Regist(s2::SYM_PARTICLE3D,	"particle");
	Regist(s2::SYM_PARTICLE2D,	"particle2d");
	Regist(s2::SYM_SHAPE,		"shape");
	Regist(s2::SYM_MESH,		"mesh");
	Regist(s2::SYM_MASK,		"mask");
	Regist(s2::SYM_TRAIL,		"trail");
	Regist(s2::SYM_SKELETON,	"skeleton");
}

int SymbolFile::Type(const std::string& filepath) const
{
	int type = gum::SymbolFile::Instance()->Type(filepath);
	if (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {
		return type;
	}

	int pos = filepath.rfind('.');
	std::string ext = filepath.substr(pos + 1);
	if (ext == "json")
	{
		const std::string filename = filepath.substr(0, filepath.find_last_of('.'));
		int pos = filename.find_last_of('_');
		if (pos == -1) {
			return s2::SYM_UNKNOWN;
		}

		std::string tag = filename.substr(pos + 1);
		pos = tag.find(TAG_GEN);
		if (pos != std::string::npos) {
			tag = tag.substr(0, pos - 1);
		}

		std::map<std::string, int>::const_iterator itr = m_tag2type.find(tag);
		if (itr != m_tag2type.end()) {
			return itr->second;
		} else {
			return s2::SYM_UNKNOWN;
		}
	}
	else if (ext == "lua")
	{
		const std::string name = filepath.substr(0, filepath.find_last_of('.'));
		if (name.find('_') == -1) {
			return s2::SYM_UNKNOWN;
		}
		const std::string json_ext = name.substr(name.find_last_of('_') + 1);
		if (json_ext == "scripts") {
			return SYM_SCRIPTS;
		} else {
			return s2::SYM_UNKNOWN;
		}
	}
	else if (ext == "ttf")
	{
		return SYM_FREETYPE;
	}
	else
	{
		std::string filename = FileHelper::GetFilename(filepath);
		if (filename == SYM_GROUP_TAG) {
			return s2::SYM_COMPLEX;
		}
	}

	return s2::SYM_UNKNOWN;
}

const std::string& SymbolFile::Tag(int type) const
{
	const std::string& tag = gum::SymbolFile::Instance()->Tag(type);
	if (tag != gum::SymbolFile::UNKNOWN_TAG) {
		return tag;
	}

	std::map<int, std::string>::const_iterator itr = m_type2tag.find(type);
	if (itr != m_type2tag.end()) {
		return itr->second;
	} else {
		return gum::SymbolFile::UNKNOWN_TAG;
	}
}

void SymbolFile::Regist(int type, const std::string& tag)
{
	m_type2tag.insert(std::make_pair(type, tag));
	m_tag2type.insert(std::make_pair(tag, type));
}

}<commit_msg>[ADDED] open spine sym<commit_after>#include "SymbolFile.h"
#include "SymbolType.h"
#include "FileHelper.h"

#include <sprite2/SymType.h>
#include <gum/SymbolFile.h>

#include <json/json.h>

#include <fstream>

namespace ee
{

SINGLETON_DEFINITION(SymbolFile);

static const char* TAG_GEN = "gen";

SymbolFile::SymbolFile()
{
	Regist(SYM_ANIS,		"anis");
	Regist(SYM_FONTBLANK,	"fontblank");
	Regist(SYM_FREETYPE,	"freetype");
	Regist(SYM_SCRIPTS,		"scripts");
	Regist(SYM_P3DINV,		"p3dinv");
	Regist(SYM_EJOY2D,		"ejoy2d");
	Regist(SYM_TERRAIN2D,	"terrain2d");
	Regist(SYM_SHADOW,		"shadow");
	Regist(SYM_UI,			"ui");
	Regist(SYM_PSD,			"psd");
	Regist(SYM_UIWND,		"uiwnd");

	Regist(s2::SYM_SCALE9,		"scale9");
	Regist(s2::SYM_ICON,		"icon");
	Regist(s2::SYM_TEXTURE,		"texture");
	Regist(s2::SYM_TEXTBOX,		"text");
	Regist(s2::SYM_COMPLEX,		"complex");
	Regist(s2::SYM_ANIMATION,	"anim");
	Regist(s2::SYM_PARTICLE3D,	"particle");
	Regist(s2::SYM_PARTICLE2D,	"particle2d");
	Regist(s2::SYM_SHAPE,		"shape");
	Regist(s2::SYM_MESH,		"mesh");
	Regist(s2::SYM_MASK,		"mask");
	Regist(s2::SYM_TRAIL,		"trail");
	Regist(s2::SYM_SKELETON,	"skeleton");
}

int SymbolFile::Type(const std::string& filepath) const
{
	int type = gum::SymbolFile::Instance()->Type(filepath);
	if (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {
		return type;
	}

	int pos = filepath.rfind('.');
	std::string ext = filepath.substr(pos + 1);
	if (ext == "json")
	{
		const std::string filename = filepath.substr(0, filepath.find_last_of('.'));
		int pos = filename.find_last_of('_');
		if (pos == -1) {
			return s2::SYM_UNKNOWN;
		}

		std::string tag = filename.substr(pos + 1);
		pos = tag.find(TAG_GEN);
		if (pos != std::string::npos) {
			tag = tag.substr(0, pos - 1);
		}

		std::map<std::string, int>::const_iterator itr = m_tag2type.find(tag);
		if (itr != m_tag2type.end()) {
			return itr->second;
		}

		Json::Value val;
		Json::Reader reader;
		std::locale::global(std::locale(""));
		std::ifstream fin(filepath.c_str());
		std::locale::global(std::locale("C"));
		reader.parse(fin, val);
		fin.close();

		if (val.isMember("skeleton") && !val["skeleton"].isArray() && val["skeleton"].isMember("spine")) {
			return s2::SYM_ANIM2;
		}

		return s2::SYM_UNKNOWN;
	}
	else if (ext == "lua")
	{
		const std::string name = filepath.substr(0, filepath.find_last_of('.'));
		if (name.find('_') == -1) {
			return s2::SYM_UNKNOWN;
		}
		const std::string json_ext = name.substr(name.find_last_of('_') + 1);
		if (json_ext == "scripts") {
			return SYM_SCRIPTS;
		} else {
			return s2::SYM_UNKNOWN;
		}
	}
	else if (ext == "ttf")
	{
		return SYM_FREETYPE;
	}
	else
	{
		std::string filename = FileHelper::GetFilename(filepath);
		if (filename == SYM_GROUP_TAG) {
			return s2::SYM_COMPLEX;
		}
	}

	return s2::SYM_UNKNOWN;
}

const std::string& SymbolFile::Tag(int type) const
{
	const std::string& tag = gum::SymbolFile::Instance()->Tag(type);
	if (tag != gum::SymbolFile::UNKNOWN_TAG) {
		return tag;
	}

	std::map<int, std::string>::const_iterator itr = m_type2tag.find(type);
	if (itr != m_type2tag.end()) {
		return itr->second;
	} else {
		return gum::SymbolFile::UNKNOWN_TAG;
	}
}

void SymbolFile::Regist(int type, const std::string& tag)
{
	m_type2tag.insert(std::make_pair(type, tag));
	m_tag2type.insert(std::make_pair(tag, type));
}

}<|endoftext|>


<commit_before>#include "SelectShapesOP.h"
#include "Rect.h"
#include "MultiShapesImpl.h"
#include "ShapeSelection.h"
#include "EditPanelImpl.h"
#include "EditCMPT.h"
#include "DrawSelectedShapeVisitor.h"
#include "shape_msg.h"
#include "panel_msg.h"
#include "FetchAllVisitor.h"

namespace ee
{

SelectShapesOP::SelectShapesOP(wxWindow* wnd, EditPanelImpl* stage, MultiShapesImpl* shapes_impl,
							   EditCMPT* callback/* = NULL*/)
	: DrawRectangleOP(wnd, stage)
	, m_callback(callback)
	, m_shape_impl(shapes_impl)
	, m_bDraggable(true)
{
	m_selection = shapes_impl->GetShapeSelection();
	m_selection->Retain();

	m_first_pos.SetInvalid();
}

SelectShapesOP::~SelectShapesOP()
{
	clearClipboard();

 	m_selection->Clear();
 	m_selection->Release();
}

bool SelectShapesOP::OnKeyDown(int keyCode)
{
	if (DrawRectangleOP::OnKeyDown(keyCode)) return true;

	if (keyCode == WXK_DELETE)
	{
		m_shape_impl->ClearSelectedShape();
		Clear();
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'x' || keyCode == 'X'))
	{
		PasteToSelection();
		m_shape_impl->ClearSelectedShape();
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))
	{
		clearClipboard();

		std::vector<Shape*> shapes;
		m_selection->Traverse(FetchAllVisitor<Shape>(shapes));
		for (size_t i = 0, n = shapes.size(); i < n; ++i)
			m_clipboard.push_back(shapes[i]->Clone());
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'v' || keyCode == 'V'))
	{
		for (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {
			InsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());
		}
	}

	return false;
}

bool SelectShapesOP::OnMouseLeftDown(int x, int y)
{
	m_bDraggable = true;

	m_move_last_pos.SetInvalid();

	Vector pos = m_stage->TransPosScrToProj(x, y);
	Shape* selected = m_shape_impl->QueryShapeByPos(pos);
	if (selected)
	{
		if (m_stage->GetKeyState(WXK_CONTROL))
		{
			if (m_selection->IsExist(selected)) {
				m_selection->Remove(selected);
			} else {
				m_selection->Add(selected);
			}
			SelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);
		}
		else
		{
			if (!m_selection->IsExist(selected))
			{
				m_selection->Clear();
				m_selection->Add(selected);
				SelectShapeSJ::Instance()->Select(selected, m_shape_impl);
			} else {
				m_move_last_pos = pos;
			}
		}
		m_first_pos.SetInvalid();

		if (m_callback)
			m_callback->UpdateControlValue();
	}
	else
	{
		DrawRectangleOP::OnMouseLeftDown(x, y);
		m_first_pos = pos;
		if (m_stage->GetKeyState(WXK_CONTROL))
			m_bDraggable = false;
		else
			m_selection->Clear();
	}

	return false;
}

bool SelectShapesOP::OnMouseLeftUp(int x, int y)
{
	if (DrawRectangleOP::OnMouseLeftUp(x, y)) return true;

	m_bDraggable = true;

	if (m_first_pos.IsValid())
	{
		Rect rect(m_first_pos, m_stage->TransPosScrToProj(x, y));
		std::vector<Shape*> shapes;
		m_shape_impl->QueryShapesByRect(rect, shapes);
		for (size_t i = 0, n = shapes.size(); i < n; ++i)
			m_selection->Add(shapes[i]);

		SelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);

		m_first_pos.SetInvalid();

		if (m_callback) {
			m_callback->UpdateControlValue();
		}
	}

	SetCanvasDirtySJ::Instance()->SetDirty();

	return false;
}

bool SelectShapesOP::OnMouseDrag(int x, int y)
{
	if (DrawRectangleOP::OnMouseDrag(x, y)) return true;

	if (!m_selection->IsEmpty() && m_move_last_pos.IsValid()) {
		Vector pos = m_stage->TransPosScrToProj(x, y);
		m_selection->Traverse(TranslateVisitor(pos - m_move_last_pos));
		m_move_last_pos = pos;
	}

	return !m_bDraggable;
}

bool SelectShapesOP::OnDraw() const
{
	if (DrawRectangleOP::OnDraw()) return true;

	m_selection->Traverse(DrawSelectedShapeVisitor());

	return false;
}

bool SelectShapesOP::Clear()
{
	if (DrawRectangleOP::Clear()) return true;

	clearClipboard();
	m_selection->Clear();
	m_first_pos.SetInvalid();

	return false;
}

void SelectShapesOP::clearClipboard()
{
 	for (size_t i = 0, n = m_clipboard.size(); i < n; ++i)
 		m_clipboard[i]->Release();
 	m_clipboard.clear();
}

void SelectShapesOP::PasteToSelection() const
{
	std::vector<Shape*> shapes;
	m_selection->Traverse(FetchAllVisitor<Shape>(shapes));
	for (size_t i = 0, n = shapes.size(); i < n; ++i) {
		m_clipboard.push_back(shapes[i]->Clone());
	}
}

void SelectShapesOP::CopyFromSelection()
{
	for (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {
		InsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());
	}
}

//////////////////////////////////////////////////////////////////////////
// class TranslateSpriteState::TranslateVisitor
//////////////////////////////////////////////////////////////////////////

void SelectShapesOP::TranslateVisitor::
Visit(Object* object, bool& next)
{
	Shape* shape = static_cast<Shape*>(object);
	shape->Translate(m_offset);
	next = true;
}

}<commit_msg>[CHANGED] close move shape<commit_after>#include "SelectShapesOP.h"
#include "Rect.h"
#include "MultiShapesImpl.h"
#include "ShapeSelection.h"
#include "EditPanelImpl.h"
#include "EditCMPT.h"
#include "DrawSelectedShapeVisitor.h"
#include "shape_msg.h"
#include "panel_msg.h"
#include "FetchAllVisitor.h"

namespace ee
{

SelectShapesOP::SelectShapesOP(wxWindow* wnd, EditPanelImpl* stage, MultiShapesImpl* shapes_impl,
							   EditCMPT* callback/* = NULL*/)
	: DrawRectangleOP(wnd, stage)
	, m_callback(callback)
	, m_shape_impl(shapes_impl)
	, m_bDraggable(true)
{
	m_selection = shapes_impl->GetShapeSelection();
	m_selection->Retain();

	m_first_pos.SetInvalid();
}

SelectShapesOP::~SelectShapesOP()
{
	clearClipboard();

 	m_selection->Clear();
 	m_selection->Release();
}

bool SelectShapesOP::OnKeyDown(int keyCode)
{
	if (DrawRectangleOP::OnKeyDown(keyCode)) return true;

	if (keyCode == WXK_DELETE)
	{
		m_shape_impl->ClearSelectedShape();
		Clear();
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'x' || keyCode == 'X'))
	{
		PasteToSelection();
		m_shape_impl->ClearSelectedShape();
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))
	{
		clearClipboard();

		std::vector<Shape*> shapes;
		m_selection->Traverse(FetchAllVisitor<Shape>(shapes));
		for (size_t i = 0, n = shapes.size(); i < n; ++i)
			m_clipboard.push_back(shapes[i]->Clone());
	}
	else if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'v' || keyCode == 'V'))
	{
		for (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {
			InsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());
		}
	}

	return false;
}

bool SelectShapesOP::OnMouseLeftDown(int x, int y)
{
	m_bDraggable = true;

	m_move_last_pos.SetInvalid();

	Vector pos = m_stage->TransPosScrToProj(x, y);
	Shape* selected = m_shape_impl->QueryShapeByPos(pos);
	if (selected)
	{
		if (m_stage->GetKeyState(WXK_CONTROL))
		{
			if (m_selection->IsExist(selected)) {
				m_selection->Remove(selected);
			} else {
				m_selection->Add(selected);
			}
			SelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);
		}
		else
		{
			if (!m_selection->IsExist(selected))
			{
				m_selection->Clear();
				m_selection->Add(selected);
				SelectShapeSJ::Instance()->Select(selected, m_shape_impl);
			} else {
				m_move_last_pos = pos;
			}
		}
		m_first_pos.SetInvalid();

		if (m_callback)
			m_callback->UpdateControlValue();
	}
	else
	{
		DrawRectangleOP::OnMouseLeftDown(x, y);
		m_first_pos = pos;
		if (m_stage->GetKeyState(WXK_CONTROL))
			m_bDraggable = false;
		else
			m_selection->Clear();
	}

	return false;
}

bool SelectShapesOP::OnMouseLeftUp(int x, int y)
{
	if (DrawRectangleOP::OnMouseLeftUp(x, y)) return true;

	m_bDraggable = true;

	if (m_first_pos.IsValid())
	{
		Rect rect(m_first_pos, m_stage->TransPosScrToProj(x, y));
		std::vector<Shape*> shapes;
		m_shape_impl->QueryShapesByRect(rect, shapes);
		for (size_t i = 0, n = shapes.size(); i < n; ++i)
			m_selection->Add(shapes[i]);

		SelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);

		m_first_pos.SetInvalid();

		if (m_callback) {
			m_callback->UpdateControlValue();
		}
	}

	SetCanvasDirtySJ::Instance()->SetDirty();

	return false;
}

bool SelectShapesOP::OnMouseDrag(int x, int y)
{
	if (DrawRectangleOP::OnMouseDrag(x, y)) return true;

//	// no need to move shape?
// 	if (!m_selection->IsEmpty() && m_move_last_pos.IsValid()) {
// 		Vector pos = m_stage->TransPosScrToProj(x, y);
// 		m_selection->Traverse(TranslateVisitor(pos - m_move_last_pos));
// 		m_move_last_pos = pos;
// 	}

	return !m_bDraggable;
}

bool SelectShapesOP::OnDraw() const
{
	if (DrawRectangleOP::OnDraw()) return true;

	m_selection->Traverse(DrawSelectedShapeVisitor());

	return false;
}

bool SelectShapesOP::Clear()
{
	if (DrawRectangleOP::Clear()) return true;

	clearClipboard();
	m_selection->Clear();
	m_first_pos.SetInvalid();

	return false;
}

void SelectShapesOP::clearClipboard()
{
 	for (size_t i = 0, n = m_clipboard.size(); i < n; ++i)
 		m_clipboard[i]->Release();
 	m_clipboard.clear();
}

void SelectShapesOP::PasteToSelection() const
{
	std::vector<Shape*> shapes;
	m_selection->Traverse(FetchAllVisitor<Shape>(shapes));
	for (size_t i = 0, n = shapes.size(); i < n; ++i) {
		m_clipboard.push_back(shapes[i]->Clone());
	}
}

void SelectShapesOP::CopyFromSelection()
{
	for (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {
		InsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());
	}
}

//////////////////////////////////////////////////////////////////////////
// class TranslateSpriteState::TranslateVisitor
//////////////////////////////////////////////////////////////////////////

void SelectShapesOP::TranslateVisitor::
Visit(Object* object, bool& next)
{
	Shape* shape = static_cast<Shape*>(object);
	shape->Translate(m_offset);
	next = true;
}

}<|endoftext|>


<commit_before>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "vld.h"
#ifdef _WIN32
#include <winsock2.h>
#endif
#include "ServiceAcceptor.h"
#include "stringtools.h"
#include "ServiceWorker.h"
#include <memory.h>

#include "Interface/Mutex.h"
#include "Interface/Condition.h"
#include "Interface/Service.h"

namespace
{
	bool prepareSocket(SOCKET s)
	{
#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)
		fcntl(s, F_SETFD, fcntl(s, F_GETFD, 0) | FD_CLOEXEC);
#endif

		int optval = 1;
		int rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));
		if (rc == SOCKET_ERROR)
		{
			Server->Log("Failed setting SO_REUSEADDR", LL_ERROR);
			return false;
		}

#ifdef __APPLE__
		optval = 1;
		setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));
#endif
		return true;
	}
}

CServiceAcceptor::CServiceAcceptor(IService * pService, std::string pName, unsigned short port, int pMaxClientsPerThread, IServer::BindTarget bindTarget)
	: maxClientsPerThread(pMaxClientsPerThread), s_v6(SOCKET_ERROR)
{
	name=pName;
	service=pService;
	exitpipe=Server->createMemoryPipe();
	do_exit=false;
	has_error=false;
#ifndef _WIN32
	pipe(xpipe);
#endif

	int rc;
#ifdef _WIN32
	WSADATA wsadata;
	rc = WSAStartup(MAKEWORD(2,2), &wsadata);
	if(rc == SOCKET_ERROR)	return;
#endif

	int type = SOCK_STREAM;
#if !defined(_WIN32) && defined(SOCK_CLOEXEC)
	type |= SOCK_CLOEXEC;
#endif
	s=socket(AF_INET,type,0);
	if(s<1)
	{
		Server->Log(name+": Creating SOCKET failed",LL_ERROR);
		has_error=true;
		return;
	}

	if (!prepareSocket(s))
	{
		has_error = true;
		return;
	}

	sockaddr_in addr;

	memset(&addr, 0, sizeof(sockaddr_in));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(port);
	switch(bindTarget)
	{
	case IServer::BindTarget_All:
		addr.sin_addr.s_addr= htonl(INADDR_ANY);
		break;
	case IServer::BindTarget_Localhost:
		addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
		break;
	}

	rc=bind(s,(sockaddr*)&addr,sizeof(addr));
	if(rc==SOCKET_ERROR)
	{
		Server->Log(name+": Failed binding socket to port "+convert(port)+". Another instance of this application may already be active and bound to this port.",LL_ERROR);
		has_error=true;
		return;
	}

	listen(s, 10000);

	if (Server->getServerParameter("disable_ipv6").empty())
	{
		s_v6 = socket(AF_INET6, type, 0);
		if (s_v6 < 1)
		{
			Server->Log(name + ": Creating v6 SOCKET failed", LL_ERROR);
			has_error = true;
			return;
		}

		if (!prepareSocket(s_v6))
		{
			has_error = true;
			return;
		}

		int optval = 1;
		setsockopt(s_v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));

		sockaddr_in6 addr;

		memset(&addr, 0, sizeof(addr));
		addr.sin6_family = AF_INET6;
		addr.sin6_port = htons(port);
		switch (bindTarget)
		{
		case IServer::BindTarget_All:
			addr.sin6_addr = in6addr_any;
			break;
		case IServer::BindTarget_Localhost:
			addr.sin6_addr= in6addr_loopback;
			break;
		}

		rc = bind(s_v6, (sockaddr*)&addr, sizeof(addr));
		if (rc == SOCKET_ERROR)
		{
			Server->Log(name + ": Failed binding ipv6 socket to port " + convert(port) + ". Another instance of this application may already be active and bound to this port.", LL_ERROR);
			has_error = true;
			return;
		}

		listen(s_v6, 10000);
	}

	Server->Log(name+": Server started up successfully!",LL_INFO);
}

CServiceAcceptor::~CServiceAcceptor()
{
	if(has_error)
		return;

	do_exit=true;
#ifndef _WIN32
	char ch=0;
	write(xpipe[1], &ch, 1);
#endif
	closesocket(s);
	if (s_v6 != SOCKET_ERROR)
		closesocket(s_v6);
	for(size_t i=0;i<workers.size();++i)
	{
		workers[i]->stop();
	}
	size_t c=0;
	Server->Log("c=0/"+convert(workers.size()+1));
	while(c<workers.size()+1)
	{
		std::string r;
		exitpipe->Read(&r);
		if(r=="ok")
		{
			++c;
			Server->Log("c="+convert(c)+"/"+convert(workers.size()+1));
		}
	}
	Server->destroy(exitpipe);
	for(size_t i=0;i<workers.size();++i)
	{
		delete workers[i];
	}

	delete service;
}

void CServiceAcceptor::operator()(void)
{
	if(has_error)
		return;

	while(do_exit==false)
	{
#ifdef _WIN32
		fd_set fdset;
		FD_ZERO(&fdset);
		if(s!=SOCKET_ERROR)
			FD_SET(s, &fdset);
		if (s_v6 != SOCKET_ERROR)
			FD_SET(s_v6, &fdset);
		SOCKET maxs = (std::max)(s, s_v6) + 1;

		timeval lon;
		lon.tv_sec=100;
		lon.tv_usec=0;

		_i32 rc=select((int)maxs, &fdset, 0, 0, &lon);
#else
		pollfd conn[3];
		conn[0].fd= s !=SOCKET_ERROR ? s: s_v6;
		conn[0].events=POLLIN;
		conn[0].revents=0;
		conn[1].fd=xpipe[0];
		conn[1].events=POLLIN;
		conn[1].revents=0;
		conn[2].revents = 0;

		nfds_t num_fds = 2;

		if (s_v6 != SOCKET_ERROR
			&& s != SOCKET_ERROR)
		{
			num_fds = 3;
			conn[2].fd = s_v6;
			conn[2].events = POLLIN;
		}

		int rc = poll(conn, 2, 100*1000);
#endif
		if(rc>=0)
		{
			for (size_t n = 0; n < 2; ++n)
			{
#ifdef _WIN32
				SOCKET accept_socket = n == 0 ? s : s_v6;
				if (accept_socket == SOCKET_ERROR)
					continue;
				if (!FD_ISSET(accept_socket, &fdset))
					continue;
#else
				if (conn[n].revents == 0)
					continue;
				SOCKET accept_socket = conn[n].fd;
#endif
				if (do_exit)
					break;

				union
				{
					sockaddr_in naddr_v4;
					sockaddr_in6 naddr_v6;
				} naddr;
				socklen_t addrsize;
				if (accept_socket == s_v6)
					addrsize = sizeof(naddr.naddr_v6);
				else
					addrsize = sizeof(naddr.naddr_v4);

				sockaddr* paddr = (sockaddr*)&naddr;
				SOCKET ns= ACCEPT_CLOEXEC(accept_socket, paddr, &addrsize);
				if(ns!=SOCKET_ERROR)
				{
#ifdef __APPLE__
					int optval = 1;
					setsockopt(ns, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));
#endif
					//Server->Log(name+": New Connection incomming "+convert(Server->getTimeMS())+" s: "+convert((int)ns), LL_DEBUG);

	#ifdef _WIN32
					int window_size=Server->getSendWindowSize();
					if(window_size>0)
						setsockopt(ns, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, sizeof(window_size));

					window_size = Server->getRecvWindowSize();
					if(window_size>0)
						setsockopt(ns, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, sizeof(window_size));
	#endif
					char buf[100];
					const char* endpoint = inet_ntop(paddr->sa_family,
						accept_socket == s_v6 ? (void*)&naddr.naddr_v6.sin6_addr : (void*)&naddr.naddr_v4.sin_addr,
						buf, sizeof(buf));

					AddToWorker(ns, endpoint!=NULL ? endpoint : "");
				}
			}
		}
		else
		{
			Server->Log("Select error in CServiceAcceptor Thread.", LL_ERROR);
			break;
		}
	}
	Server->Log("ServiceAcceptor finished", LL_DEBUG);
	exitpipe->Write("ok");
}

void CServiceAcceptor::AddToWorker(SOCKET pSocket, const std::string& endpoint)
{
	for(size_t i=0;i<workers.size();++i)
	{
		if( workers[i]->getAvailableSlots()>0 )
		{
			workers[i]->AddClient(pSocket, endpoint);
			return;
		}
	}

	Server->Log(name+": No available slots... starting new Worker", LL_DEBUG);

	CServiceWorker *nw=new CServiceWorker(service, name, exitpipe, maxClientsPerThread);
	workers.push_back(nw);

	Server->createThread(nw, name+": worker");

	nw->AddClient( pSocket, endpoint );
}
<commit_msg>Fix polling with ipv6 socket<commit_after>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "vld.h"
#ifdef _WIN32
#include <winsock2.h>
#endif
#include "ServiceAcceptor.h"
#include "stringtools.h"
#include "ServiceWorker.h"
#include <memory.h>

#include "Interface/Mutex.h"
#include "Interface/Condition.h"
#include "Interface/Service.h"

namespace
{
	bool prepareSocket(SOCKET s)
	{
#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)
		fcntl(s, F_SETFD, fcntl(s, F_GETFD, 0) | FD_CLOEXEC);
#endif

		int optval = 1;
		int rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));
		if (rc == SOCKET_ERROR)
		{
			Server->Log("Failed setting SO_REUSEADDR", LL_ERROR);
			return false;
		}

#ifdef __APPLE__
		optval = 1;
		setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));
#endif
		return true;
	}
}

CServiceAcceptor::CServiceAcceptor(IService * pService, std::string pName, unsigned short port, int pMaxClientsPerThread, IServer::BindTarget bindTarget)
	: maxClientsPerThread(pMaxClientsPerThread), s_v6(SOCKET_ERROR)
{
	name=pName;
	service=pService;
	exitpipe=Server->createMemoryPipe();
	do_exit=false;
	has_error=false;
#ifndef _WIN32
	pipe(xpipe);
#endif

	int rc;
#ifdef _WIN32
	WSADATA wsadata;
	rc = WSAStartup(MAKEWORD(2,2), &wsadata);
	if(rc == SOCKET_ERROR)	return;
#endif

	int type = SOCK_STREAM;
#if !defined(_WIN32) && defined(SOCK_CLOEXEC)
	type |= SOCK_CLOEXEC;
#endif
	s=socket(AF_INET,type,0);
	if(s<1)
	{
		Server->Log(name+": Creating SOCKET failed",LL_ERROR);
		has_error=true;
		return;
	}

	if (!prepareSocket(s))
	{
		has_error = true;
		return;
	}

	sockaddr_in addr;

	memset(&addr, 0, sizeof(sockaddr_in));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(port);
	switch(bindTarget)
	{
	case IServer::BindTarget_All:
		addr.sin_addr.s_addr= htonl(INADDR_ANY);
		break;
	case IServer::BindTarget_Localhost:
		addr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
		break;
	}

	rc=bind(s,(sockaddr*)&addr,sizeof(addr));
	if(rc==SOCKET_ERROR)
	{
		Server->Log(name+": Failed binding socket to port "+convert(port)+". Another instance of this application may already be active and bound to this port.",LL_ERROR);
		has_error=true;
		return;
	}

	listen(s, 10000);

	if (Server->getServerParameter("disable_ipv6").empty())
	{
		s_v6 = socket(AF_INET6, type, 0);
		if (s_v6 < 1)
		{
			Server->Log(name + ": Creating v6 SOCKET failed", LL_ERROR);
			has_error = true;
			return;
		}

		if (!prepareSocket(s_v6))
		{
			has_error = true;
			return;
		}

		int optval = 1;
		setsockopt(s_v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));

		sockaddr_in6 addr;

		memset(&addr, 0, sizeof(addr));
		addr.sin6_family = AF_INET6;
		addr.sin6_port = htons(port);
		switch (bindTarget)
		{
		case IServer::BindTarget_All:
			addr.sin6_addr = in6addr_any;
			break;
		case IServer::BindTarget_Localhost:
			addr.sin6_addr= in6addr_loopback;
			break;
		}

		rc = bind(s_v6, (sockaddr*)&addr, sizeof(addr));
		if (rc == SOCKET_ERROR)
		{
			Server->Log(name + ": Failed binding ipv6 socket to port " + convert(port) + ". Another instance of this application may already be active and bound to this port.", LL_ERROR);
			has_error = true;
			return;
		}

		listen(s_v6, 10000);
	}

	Server->Log(name+": Server started up successfully!",LL_INFO);
}

CServiceAcceptor::~CServiceAcceptor()
{
	if(has_error)
		return;

	do_exit=true;
#ifndef _WIN32
	char ch=0;
	write(xpipe[1], &ch, 1);
#endif
	closesocket(s);
	if (s_v6 != SOCKET_ERROR)
		closesocket(s_v6);
	for(size_t i=0;i<workers.size();++i)
	{
		workers[i]->stop();
	}
	size_t c=0;
	Server->Log("c=0/"+convert(workers.size()+1));
	while(c<workers.size()+1)
	{
		std::string r;
		exitpipe->Read(&r);
		if(r=="ok")
		{
			++c;
			Server->Log("c="+convert(c)+"/"+convert(workers.size()+1));
		}
	}
	Server->destroy(exitpipe);
	for(size_t i=0;i<workers.size();++i)
	{
		delete workers[i];
	}

	delete service;
}

void CServiceAcceptor::operator()(void)
{
	if(has_error)
		return;

	while(do_exit==false)
	{
#ifdef _WIN32
		fd_set fdset;
		FD_ZERO(&fdset);
		if(s!=SOCKET_ERROR)
			FD_SET(s, &fdset);
		if (s_v6 != SOCKET_ERROR)
			FD_SET(s_v6, &fdset);
		SOCKET maxs = (std::max)(s, s_v6) + 1;

		timeval lon;
		lon.tv_sec=100;
		lon.tv_usec=0;

		_i32 rc=select((int)maxs, &fdset, 0, 0, &lon);
#else
		pollfd conn[3];
		conn[0].fd= s !=SOCKET_ERROR ? s: s_v6;
		conn[0].events=POLLIN;
		conn[0].revents=0;
		conn[1].fd=xpipe[0];
		conn[1].events=POLLIN;
		conn[1].revents=0;
		conn[2].revents = 0;

		nfds_t num_fds = 2;

		if (s_v6 != SOCKET_ERROR
			&& s != SOCKET_ERROR)
		{
			num_fds = 3;
			conn[2].fd = s_v6;
			conn[2].events = POLLIN;
		}

		int rc = poll(conn, num_fds, 100*1000);
#endif
		if(rc>=0)
		{
			for (size_t n = 0; n < 2; ++n)
			{
#ifdef _WIN32
				SOCKET accept_socket = n == 0 ? s : s_v6;
				if (accept_socket == SOCKET_ERROR)
					continue;
				if (!FD_ISSET(accept_socket, &fdset))
					continue;
#else
				if (conn[n].revents == 0)
					continue;
				SOCKET accept_socket = conn[n].fd;
#endif
				if (do_exit)
					break;

				union
				{
					sockaddr_in naddr_v4;
					sockaddr_in6 naddr_v6;
				} naddr;
				socklen_t addrsize;
				if (accept_socket == s_v6)
					addrsize = sizeof(naddr.naddr_v6);
				else
					addrsize = sizeof(naddr.naddr_v4);

				sockaddr* paddr = (sockaddr*)&naddr;
				SOCKET ns= ACCEPT_CLOEXEC(accept_socket, paddr, &addrsize);
				if(ns!=SOCKET_ERROR)
				{
#ifdef __APPLE__
					int optval = 1;
					setsockopt(ns, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));
#endif
					//Server->Log(name+": New Connection incomming "+convert(Server->getTimeMS())+" s: "+convert((int)ns), LL_DEBUG);

	#ifdef _WIN32
					int window_size=Server->getSendWindowSize();
					if(window_size>0)
						setsockopt(ns, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, sizeof(window_size));

					window_size = Server->getRecvWindowSize();
					if(window_size>0)
						setsockopt(ns, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, sizeof(window_size));
	#endif
					char buf[100];
					const char* endpoint = inet_ntop(paddr->sa_family,
						accept_socket == s_v6 ? (void*)&naddr.naddr_v6.sin6_addr : (void*)&naddr.naddr_v4.sin_addr,
						buf, sizeof(buf));

					AddToWorker(ns, endpoint!=NULL ? endpoint : "");
				}
			}
		}
		else
		{
			Server->Log("Select error in CServiceAcceptor Thread.", LL_ERROR);
			break;
		}
	}
	Server->Log("ServiceAcceptor finished", LL_DEBUG);
	exitpipe->Write("ok");
}

void CServiceAcceptor::AddToWorker(SOCKET pSocket, const std::string& endpoint)
{
	for(size_t i=0;i<workers.size();++i)
	{
		if( workers[i]->getAvailableSlots()>0 )
		{
			workers[i]->AddClient(pSocket, endpoint);
			return;
		}
	}

	Server->Log(name+": No available slots... starting new Worker", LL_DEBUG);

	CServiceWorker *nw=new CServiceWorker(service, name, exitpipe, maxClientsPerThread);
	workers.push_back(nw);

	Server->createThread(nw, name+": worker");

	nw->AddClient( pSocket, endpoint );
}
<|endoftext|>


<commit_before>
# include <Siv3D.hpp>
# include "Test/Siv3DTest.hpp"

void Main()
{
	RunTest();

	Log << Range(0, 100).sum();

	Log << Range(0_big, 100_big).sum();

	Log << step(Vec2(10,10), 5, Vec2(0.5,0.5));

	Log << step(Vec2(10,10), 5, Vec2(0.5,0.5)).sum();

	Log << step(String(L""), 5, L'.');

	Log << step(String(L""), 5, L'.').sum();

	/////////////////////////////////////////////////
	//
	//	Range
	//
	/////////////////////////////////////////////////

	// 0～100 の範囲
	Log << L"# Range(0, 100)";
	Log << Range(0, 100);

	// 0～100 の合計
	Log << L"# Range(0, 100).sum()";
	Log << Range(0, 100).sum();

	// 1/1 + 1/2 + 1/3 + 1/4 + ... + 1/10000 の合計
	Log << L"# Range(1, 10000).map(Divides(1.0, none)).sum())";
	Log << 18_dp << Range(10000, 1, -1).map(Divides(1.0, none)).sum();
	Log << Range(10000, 1, -1).map(Divides<BigFloat>(1.0, none)).sum();
	Log << L"9.78760603604438226417847790485160533485926294557769171838946095668160202494315950680012512729008088259135976018399338...";

	// 0～100 のうち 20 未満の個数
	Log << L"# Range(0, 100).count_if(LessThan(20))";
	Log << Range(0, 100).count_if(LessThan(20));

	// 0～10 の範囲の奇数
	Log << L"# Range(0, 10).filter(IsOdd)";
	Log << Range(0, 10).filter(IsOdd);

	// 100 の階乗
	Log << L"# Range(1, 100).reduce1(Multiplies<BigInt>())";
	Log << Range(1, 100).reduce1(Multiplies<BigInt>());

	// FizzBuzz
	Log << L"#FizzBuzz";
	Log << Range(1, 20).map([](auto n) { return n % 15 == 0 ? L"FizzBuzz" : n % 3 == 0 ? L"Fizz" : n % 5 == 0 ? L"Buzz" : Format(n); });

	// フィボナッチ数列
	BigInt a = 0, b = 1;
	Log << L"# Fibbonaci";
	Log << a << L'\n' << b;
	Range(1, 100).map([&a, &b](auto) { a = std::exchange(b, a + b); return b; }).each(Log);

	/////////////////////////////////////////////////
	//
	//	InfiniteList
	//
	/////////////////////////////////////////////////

	// 無限リスト
	Log << L"# InfiniteList";
	Log << InfiniteList().take(5);
	Log << InfiniteList(0, 0.01).take_while([](auto v) { return v * v < 0.1; });
	InfiniteList<BigInt>(L"1000000000000000000000000000000000000000000000000000000"_big, 100).take(5).each(Log);

	// 111122223333 以上の素数を近い順に 5 つ探す
	Log << InfiniteList(111122223333).filter(IsPrime).take(5);

	/////////////////////////////////////////////////
	//
	//	Array
	//
	/////////////////////////////////////////////////

	// 0〜9 の数をシャッフル
	Log << L"# Range(0, 9).asArray().shuffle()";
	Log << Range(0, 9).asArray().shuffle();

	// 4 人にポーカーの札を配る
	Log << Iota(13 * 4).map([](int32 n) { return Format(L"♦♣♥♠"[n / 13], (n % 13 + 1)); }).asArray().shuffle().take(20).chunk(5);

	while (System::Update())
	{
		if (KeyQ.down() && System::ShowMessageBox(L"アプリを終了します。", MessageBoxButtons::OKCancel)
			== MessageBoxSelection::OK)
		{
			break;
		}
	}
}
<commit_msg>remove test<commit_after>
# include <Siv3D.hpp>
# include "Test/Siv3DTest.hpp"

void Main()
{
	RunTest();

	Log << Range(0, 100).sum();

	Log << Range(0_big, 100_big).sum();

	Log << step(Vec2(10,10), 5, Vec2(0.5,0.5));

	Log << step(Vec2(10,10), 5, Vec2(0.5,0.5)).sum();

	Log << step(String(L""), 5, L'.');

	Log << step(String(L""), 5, L'.').sum();

	while (System::Update())
	{
		if (KeyQ.down() && System::ShowMessageBox(L"アプリを終了します。", MessageBoxButtons::OKCancel)
			== MessageBoxSelection::OK)
		{
			break;
		}
	}
}
<|endoftext|>


<commit_before>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>

#include "dep_selector_to_gecode.h"

#include <limits>
#include <iostream>
#include <vector>

#define DEBUG

using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;
const int VersionProblem::MIN_TRUST_LEVEL = 0;
const int VersionProblem::MAX_TRUST_LEVEL = 10;

VersionProblem::VersionProblem(int packageCount)
  : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount),
    disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),
    disabled_package_weights(new int[packageCount])
{
  for (int i = 0; i < packageCount; i++)
    disabled_package_weights[i] = MAX_TRUST_LEVEL;
}

VersionProblem::VersionProblem(bool share, VersionProblem & s)
  : MinimizeSpace(share, s), size(s.size),
    finalized(s.finalized), cur_package(s.cur_package),
    disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),
    disabled_package_weights(NULL)
{
  package_versions.update(*this, share, s.package_versions);
  disabled_package_variables.update(*this, share, s.disabled_package_variables);
  total_disabled.update(*this, share, s.total_disabled);
}

// Support for gecode
Space* VersionProblem::copy(bool share)
{
  return new VersionProblem(share,*this);
}

VersionProblem::~VersionProblem()
{
  delete[] disabled_package_weights;
}

int VersionProblem::Size()
{
  return size;
}

int VersionProblem::PackageCount()
{
  return cur_package;
}

int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
  if (cur_package == size) {
    return -1;
  }

#ifdef DEBUG
  std::cout << cur_package << '/' << size << ":" << minVersion << ", " << maxVersion << ", " << currentVersion << std::endl;
  std::cout.flush();
#endif // DEBUG
  int index = cur_package;
  cur_package++;
  //  IntVar version(*this, minVersion, maxVersion);
  package_versions[index] = IntVar(*this, minVersion, maxVersion);
  return index;
}

bool
VersionProblem::AddVersionConstraint(int packageId, int version,
				     int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
  BoolVar version_match(*this, 0, 1);
  BoolVar depend_match(*this, 0, 1);
  BoolVar predicated_depend_match(*this, 0, 1);

#ifdef DEBUG
  std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
  std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
  std::cout.flush();
#endif // DEBUG

  //version_flags << version_match;
  // Constrain pred to reify package @ version
  rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
  // Add the predicated version constraints imposed on dependent package

  // package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match
  dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);

  // disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
  // rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);

  rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
  rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}

void
VersionProblem::MarkPackageSuspicious(int packageId, int trustLevel)
{
  disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));
}

void VersionProblem::Finalize()
{
#ifdef DEBUG
  std::cout << "Finalization Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  finalized = true;

  // Setup constraint for cost
  //  linear(*this, disabled_package_weights, disabled_package_variables,  IRT_EQ, total_disabled);
  IntArgs package_weights(size, disabled_package_weights);
  //IntArgs package_weights = IntArgs::create(size, 1, 0);

#ifdef DEBUG
  std::cout << "Package weights " << package_weights << std::endl;
#endif DEBUG
  linear(*this, package_weights, disabled_package_variables,  IRT_EQ, total_disabled);
  // linear(*this, disabled_package_variables,  IRT_EQ, total_disabled);

  // Assign a dummy variable to elements greater than actually used.
  for (int i = cur_package; i < size; i++) {
    package_versions[i] = IntVar(*this, -1, -1);
    disabled_package_variables[i] = BoolVar(*this, 1, 1);
  }
#ifdef DEBUG
  std::cout << "Adding branching" << std::endl;
  std::cout.flush();
#endif // DEBUG
  branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
  branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
  branch(*this, total_disabled, INT_VAL_MIN);
#ifdef DEBUG
  std::cout << "Finalization Done" << std::endl;
  std::cout.flush();
#endif // DEBUG
}

IntVar VersionProblem::cost(void) const {
  return total_disabled;
}

IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
  if (packageId < cur_package) {
    return package_versions[packageId];
  } else {
#ifdef DEBUG
    std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
    std::cout.flush();
#endif //DEBUG
    //    return 0;
  }
}

int VersionProblem::GetPackageVersion(int packageId)
{
  IntVar & var = GetPackageVersionVar(packageId);
  if (1 == var.size()) return var.val();
  return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
  return disabled_package_variables[packageId].val() == 1;
}

int VersionProblem::GetAFC(int packageId)
{
  return GetPackageVersionVar(packageId).afc();
}

int VersionProblem::GetMax(int packageId)
{
  return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
  return GetPackageVersionVar(packageId).min();
}

int VersionProblem::GetDisabledVariableCount()
{
  if (total_disabled.min() == total_disabled.max()) {
    return total_disabled.min();
  } else {
    return UNRESOLVED_VARIABLE;
  }
}

// Utility
void VersionProblem::Print(std::ostream & out)
{
  out << "Version problem dump: " << cur_package << "/" << size << " packages used/allocated" << std::endl;
  out << "Total Disabled variables: " << total_disabled.min() << " - " << total_disabled.max() << std::endl;
  for (int i = 0; i < cur_package; i++) {
    out << "\t";
    PrintPackageVar(out, i);
    out << std::endl;
  }
  out.flush();
}

// TODO: Validate package ids !

void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
  // Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
  IntVar & var = GetPackageVersionVar(packageId);
  out << "PackageId: " << packageId <<  " Sltn: " << var.min() << " - " << var.max() << " afc: " << var.afc();

  out << " disabled: ";
  if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {
    out << disabled_package_variables[packageId].min();
  } else {
    out << disabled_package_variables[packageId].min() << " - " << disabled_package_variables[packageId].max();
  }
}

bool VersionProblem::CheckPackageId(int id)
{
  return (id < size);
}

VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
  problem->Finalize();
  problem->status();
#ifdef DEBUG
  std::cout << "Before solve" << std::endl;
  problem->Print(std::cout);
#endif //DEBUG

  Restart<VersionProblem> solver(problem);

  // std::cout << solver.statistics();

  if (VersionProblem * solution = solver.next())
    {
#ifdef DEBUG
      std::cout << "Solution:" << std::endl;
      solution->Print(std::cout);
#endif //DEBUG

      return solution;
    }
  return 0;
}

//
//
//

//
// Version Problem
//
//
//
//
<commit_msg>Add more debug stats.  Solve to optimality rather that halting early.<commit_after>#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>
#include <gecode/gist.hh>
#include <gecode/search.hh>

#include "dep_selector_to_gecode.h"

#include <limits>
#include <iostream>
#include <vector>

#define DEBUG

using namespace Gecode;
const int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;
const int VersionProblem::MIN_TRUST_LEVEL = 0;
const int VersionProblem::MAX_TRUST_LEVEL = 10;

VersionProblem::VersionProblem(int packageCount)
  : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount),
    disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),
    disabled_package_weights(new int[packageCount])
{
  for (int i = 0; i < packageCount; i++)
    disabled_package_weights[i] = MAX_TRUST_LEVEL;
}

VersionProblem::VersionProblem(bool share, VersionProblem & s)
  : MinimizeSpace(share, s), size(s.size),
    finalized(s.finalized), cur_package(s.cur_package),
    disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),
    disabled_package_weights(NULL)
{
  package_versions.update(*this, share, s.package_versions);
  disabled_package_variables.update(*this, share, s.disabled_package_variables);
  total_disabled.update(*this, share, s.total_disabled);
}

// Support for gecode
Space* VersionProblem::copy(bool share)
{
  return new VersionProblem(share,*this);
}

VersionProblem::~VersionProblem()
{
  delete[] disabled_package_weights;
}

int VersionProblem::Size()
{
  return size;
}

int VersionProblem::PackageCount()
{
  return cur_package;
}

int
VersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion)
{
  if (cur_package == size) {
    return -1;
  }

#ifdef DEBUG
  std::cout << cur_package << '/' << size << ":" << minVersion << ", " << maxVersion << ", " << currentVersion << std::endl;
  std::cout.flush();
#endif // DEBUG
  int index = cur_package;
  cur_package++;
  //  IntVar version(*this, minVersion, maxVersion);
  package_versions[index] = IntVar(*this, minVersion, maxVersion);
  return index;
}

bool
VersionProblem::AddVersionConstraint(int packageId, int version,
				     int dependentPackageId, int minDependentVersion, int maxDependentVersion)
{
  BoolVar version_match(*this, 0, 1);
  BoolVar depend_match(*this, 0, 1);
  BoolVar predicated_depend_match(*this, 0, 1);

#ifdef DEBUG
  std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
  std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
  std::cout.flush();
#endif // DEBUG

  //version_flags << version_match;
  // Constrain pred to reify package @ version
  rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
  // Add the predicated version constraints imposed on dependent package

  // package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match
  dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);

  // disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match
  // rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);

  rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
  rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
}

void
VersionProblem::MarkPackageSuspicious(int packageId, int trustLevel)
{
  disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));
}

void VersionProblem::Finalize()
{
#ifdef DEBUG
  std::cout << "Finalization Started" << std::endl;
  std::cout.flush();
#endif // DEBUG
  finalized = true;

  // Setup constraint for cost
  //  linear(*this, disabled_package_weights, disabled_package_variables,  IRT_EQ, total_disabled);
  IntArgs package_weights(size, disabled_package_weights);
  //IntArgs package_weights = IntArgs::create(size, 1, 0);

#ifdef DEBUG
  std::cout << "Package weights " << package_weights << std::endl;
#endif DEBUG
  linear(*this, package_weights, disabled_package_variables,  IRT_EQ, total_disabled);
  // linear(*this, disabled_package_variables,  IRT_EQ, total_disabled);

  // Assign a dummy variable to elements greater than actually used.
  for (int i = cur_package; i < size; i++) {
    package_versions[i] = IntVar(*this, -1, -1);
    disabled_package_variables[i] = BoolVar(*this, 1, 1);
  }
#ifdef DEBUG
  std::cout << "Adding branching" << std::endl;
  std::cout.flush();
#endif // DEBUG
  branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
  branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
  branch(*this, total_disabled, INT_VAL_MIN);
#ifdef DEBUG
  std::cout << "Finalization Done" << std::endl;
  std::cout.flush();
#endif // DEBUG
}

IntVar VersionProblem::cost(void) const {
  return total_disabled;
}

IntVar & VersionProblem::GetPackageVersionVar(int packageId)
{
  if (packageId < cur_package) {
    return package_versions[packageId];
  } else {
#ifdef DEBUG
    std::cout << "Bad package Id " << packageId << " >= " << cur_package << std::endl;
    std::cout.flush();
#endif //DEBUG
    //    return 0;
  }
}

int VersionProblem::GetPackageVersion(int packageId)
{
  IntVar & var = GetPackageVersionVar(packageId);
  if (1 == var.size()) return var.val();
  return UNRESOLVED_VARIABLE;
}
bool VersionProblem::GetPackageDisabledState(int packageId)
{
  return disabled_package_variables[packageId].val() == 1;
}

int VersionProblem::GetAFC(int packageId)
{
  return GetPackageVersionVar(packageId).afc();
}

int VersionProblem::GetMax(int packageId)
{
  return GetPackageVersionVar(packageId).max();
}
int VersionProblem::GetMin(int packageId)
{
  return GetPackageVersionVar(packageId).min();
}

int VersionProblem::GetDisabledVariableCount()
{
  if (total_disabled.min() == total_disabled.max()) {
    return total_disabled.min();
  } else {
    return UNRESOLVED_VARIABLE;
  }
}

// Utility
void VersionProblem::Print(std::ostream & out)
{
  out << "Version problem dump: " << cur_package << "/" << size << " packages used/allocated" << std::endl;
  out << "Total Disabled variables: " << total_disabled.min() << " - " << total_disabled.max() << std::endl;
  for (int i = 0; i < cur_package; i++) {
    out << "\t";
    PrintPackageVar(out, i);
    out << std::endl;
  }
  out.flush();
}

// TODO: Validate package ids !

void VersionProblem::PrintPackageVar(std::ostream & out, int packageId)
{
  // Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.
  IntVar & var = GetPackageVersionVar(packageId);
  out << "PackageId: " << packageId <<  " Sltn: " << var.min() << " - " << var.max() << " afc: " << var.afc();

  out << " disabled: ";
  if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {
    out << disabled_package_variables[packageId].min();
  } else {
    out << disabled_package_variables[packageId].min() << " - " << disabled_package_variables[packageId].max();
  }
}

bool VersionProblem::CheckPackageId(int id)
{
  return (id < size);
}

VersionProblem * VersionProblem::Solve(VersionProblem * problem)
{
  problem->Finalize();
  problem->status();
#ifdef DEBUG
  std::cout << "Before solve" << std::endl;
  problem->Print(std::cout);
#endif //DEBUG

  BAB<VersionProblem> solver(problem);

  VersionProblem *best_solution = NULL;
  while (VersionProblem *solution = solver.next())
    {
      if (best_solution != NULL)
	{
	  delete best_solution;
	}
      best_solution = solution;
#ifdef DEBUG
      const Search::Statistics & stats = solver.statistics();
      std::cout << "Solver stats: Prop:" << stats.propagate << " Fail:" << stats.fail << " Node:" << stats.node;
      std::cout << " Depth:" << stats.depth << " memory:" << stats.memory << std::endl;
      //      std::cout << stats << std::endl;
      std::cout << "Solution:" << std::endl;
      solution->Print(std::cout);
#endif //DEBUG
    }
  return best_solution;
}

//
//
//

//
// Version Problem
//
//
//
//
<|endoftext|>


<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include "../shell.h"
#include <thread>
#include <asyncply/run.h>

class ChannelTest : testing::Test { };

using cmd = cu::pipeline<int>;

cmd::link generator()
{
	return [](cmd::in&, cmd::out& yield)
	{
		for (auto& s : {100, 200, 300})
		{
			std::cout << "I am generator and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link1()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link1 and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link2()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link2 and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link3()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link3 and push " << s << std::endl;
			yield(s);
		}
	};
}

TEST(ChannelTest, pipeline)
{
	cmd(generator(), link1(), link2(), link3());
}

TEST(ChannelTest, goroutines_consumer)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 7);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));

	// https://play.golang.org/
	/*
package main

import "fmt"

func worker(done chan int) {
    for i := 0; i < 50; i++ {
        fmt.Println("----> send ", i, " [PRE]")
	done <- i
        fmt.Println("----> send ", i, " [POST]")
    }
}

func main() {
    done := make(chan int, 8)
    go worker(done)
    for i := 0; i < 50; i++ {
	j := <- done
	fmt.Println("recv ", j, "  <---- ")
    }
}
	*/

	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_unbuffered)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_buffered_one)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 1);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_buffered_two)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 2);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(CoroTest, TestScheduler)
{
	cu::scheduler sch;
	cu::semaphore person1(sch);
	cu::semaphore person2(sch);
	cu::semaphore other(sch);
	// person2
	sch.spawn([&](auto& yield) {
		std::cout << "Hola person1" << std::endl;
		person2.notify(yield);
		//
		person1.wait(yield);
		std::cout << "que tal ?" << std::endl;
		person2.notify(yield);
		//
		person1.wait(yield);
		std::cout << "me alegro" << std::endl;
		person2.notify(yield);
		//
		other.notify(yield);
	});
	// person1
	sch.spawn([&](auto& yield) {
		//
		person2.wait(yield);
		std::cout << "Hola person2" << std::endl;
		person1.notify(yield);
		//
		person2.wait(yield);
		std::cout << "bien!" << std::endl;
		person1.notify(yield);
		//
		person2.wait(yield);
		std::cout << "y yo ^^" << std::endl;
		//
		other.notify(yield);
	});
	// other
	sch.spawn([&](auto& yield) {
		//
		other.wait(yield);
		other.wait(yield);
		std::cout << "parar!!! tengo algo importante" << std::endl;
	});
	sch.run_until_complete();
}
<commit_msg>Update test_channel.cpp<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include "../shell.h"
#include <thread>
#include <asyncply/run.h>

class ChannelTest : testing::Test { };

using cmd = cu::pipeline<int>;

cmd::link generator()
{
	return [](cmd::in&, cmd::out& yield)
	{
		for (auto& s : {100, 200, 300})
		{
			std::cout << "I am generator and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link1()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link1 and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link2()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link2 and push " << s << std::endl;
			yield(s);
		}
	};
}

cmd::link link3()
{
	return [](cmd::in& source, cmd::out& yield)
	{
		for (auto& s : source)
		{
			std::cout << "I am link3 and push " << s << std::endl;
			yield(s);
		}
	};
}

TEST(ChannelTest, pipeline)
{
	cmd(generator(), link1(), link2(), link3());
}

TEST(ChannelTest, goroutines_consumer)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 7);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));

	// https://play.golang.org/
	/*
package main

import "fmt"

func worker(done chan int) {
    for i := 0; i < 50; i++ {
        fmt.Println("----> send ", i, " [PRE]")
	done <- i
        fmt.Println("----> send ", i, " [POST]")
    }
}

func main() {
    done := make(chan int, 8)
    go worker(done)
    for i := 0; i < 50; i++ {
	j := <- done
	fmt.Println("recv ", j, "  <---- ")
    }
}
	*/

	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_unbuffered)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch);
	go.connect(cu::quote("__^-^__"));
	go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_buffered_one)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 1);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(ChannelTest, goroutines_consumer_buffered_two)
{
	cu::scheduler sch;
	cu::channel<std::string> go(sch, 2);
	// go.connect(cu::quote("__^-^__"));
	// go.connect(cu::quote("__\o/__"));
	sch.spawn([&](auto& yield) {
		for(;;)
		{
			auto data = go.get(yield);
 			if(data)
 			{
 				std::cout << "recv " << *data << " <----" << std::endl;
 			}
 			else
	 		{
			 	std::cout << "channel closed" << std::endl;
 				break;
 			}
		}
	});
	sch.spawn([&](auto& yield) {
		for(int i=0; i<50; ++i)
		{
			std::cout << "----> send " << i << " [PRE]" << std::endl;
			go(yield, std::to_string(i));
			std::cout << "----> send " << i << " [POST]" << std::endl;
		}
		go.close(yield);
	});
	sch.run_until_complete();
}

TEST(CoroTest, TestScheduler)
{
	cu::scheduler sch;
	cu::semaphore person1(sch);
	cu::semaphore person2(sch);
	cu::semaphore other(sch);
	// person2
	sch.spawn([&](auto& yield) {
		std::cout << "Hola person1" << std::endl;
		person2.notify(yield);
		//
		person1.wait(yield);
		std::cout << "que tal ?" << std::endl;
		person2.notify(yield);
		//
		person1.wait(yield);
		std::cout << "me alegro" << std::endl;
		person2.notify(yield);
		//
		other.notify(yield);
	});
	// person1
	sch.spawn([&](auto& yield) {
		//
		person2.wait(yield);
		std::cout << "Hola person2" << std::endl;
		person1.notify(yield);
		//
		person2.wait(yield);
		std::cout << "bien!" << std::endl;
		person1.notify(yield);
		//
		person2.wait(yield);
		std::cout << "y yo ^^" << std::endl;
		//
		other.notify(yield);
	});
	// other
	sch.spawn([&](auto& yield) {
		//
		other.wait(yield);
		other.wait(yield);
		std::cout << "parar!!! tengo algo importante" << std::endl;
	});
	sch.run_until_complete();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2004-2015 Cray Inc.
 * Other additional copyright holders may be indicated within.
 *
 * The entirety of this work is licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ipeEvaluate.h"

void ipeEvaluate()
{

}
<commit_msg>Preliminary version of expression evaluation<commit_after>/*
 * Copyright 2004-2015 Cray Inc.
 * Other additional copyright holders may be indicated within.
 *
 * The entirety of this work is licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ipeEvaluate.h"

#include "AstDumpToNode.h"
#include "stmt.h"

#include <cstdio>
#include <cstdlib>

static int  rootEnvSize();
static void rootEnvInit(void* env);
static void rootEnvDescribe(void* env);

static int  sizeForType(Type* type);

void ipeEvaluate()
{
  int   rootSize = rootEnvSize();
  void* rootEnv  = malloc(rootSize);

  rootEnvInit(rootEnv);
  rootEnvDescribe(rootEnv);

  free(rootEnv);
}

static int rootEnvSize()
{
  int retval = 0;

  for_alist(rootStmt, rootModule->block->body)
  {
    if (DefExpr* rootDefExpr = toDefExpr(rootStmt))
    {
      if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))
      {
        if (module != rootModule)
        {
          for_alist(stmt, module->block->body)
          {
            if (DefExpr* defExpr = toDefExpr(stmt))
            {
              if (Type* type = defExpr->sym->type)
                retval = retval + sizeForType(type);

              else if (isFnSymbol(defExpr->sym) == true)
                retval = retval + 0;

              else
              {
                AstDumpToNode logger(stdout);

                printf("rootEnvSize\n");
                printf("Failed to determine size for\n");

                defExpr->accept(&logger);
                printf("\n\n\n");
              }
            }
          }
        }
      }
    }
  }

  return retval;
}

static void rootEnvInit(void* env)
{
  for_alist(rootStmt, rootModule->block->body)
  {
    if (DefExpr* rootDefExpr = toDefExpr(rootStmt))
    {
      if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))
      {
        if (module != rootModule)
        {
          for_alist(stmt, module->block->body)
          {
            if (DefExpr* defExpr = toDefExpr(stmt))
            {
              VarSymbol* varSym  = 0;

              if (defExpr->init == 0)
              {
                if (Type* type = defExpr->sym->type)
                  varSym = toVarSymbol(type->defaultValue);
              }

              else
              {
                if (SymExpr* symExpr = toSymExpr(defExpr->init))
                  varSym = toVarSymbol(symExpr->var);
              }

              if (varSym != 0)
              {
                bool handled = false;

                if (Immediate* imm = varSym->immediate)
                {
                  Type* type = varSym->type;
                  int   size = sizeForType(type);

                  if (strcmp(type->symbol->name, "bool") == 0)
                  {
                    *((long*) env)   = imm->v_bool;
                    handled          = true;
                  }

                  else if (strcmp(type->symbol->name, "int") == 0)
                  {
                    *((long*) env)   = imm->v_int64;
                    handled          = true;
                  }

                  else if (strcmp(type->symbol->name, "real") == 0)
                  {
                    *((double*) env) = imm->v_float64;
                    handled          = true;
                  }

                  env = ((char*) env) + size;
                }

                if (handled == false)
                  INT_ASSERT(false);
              }

              else if (isFnSymbol(defExpr->sym) == true)
              {

              }

              else
              {
                AstDumpToNode logger(stdout);

                printf("rootEnvInit\n\n");
                printf("Failed to handle\n");

                defExpr->accept(&logger);
                printf("\n\n\n");

                INT_ASSERT(false);
              }
            }
          }
        }
      }
    }
  }
}

static void rootEnvDescribe(void* env)
{
  printf("Final environment\n");

  for_alist(rootStmt, rootModule->block->body)
  {
    if (DefExpr* rootDefExpr = toDefExpr(rootStmt))
    {
      if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))
      {
        if (module != rootModule)
        {
          bool first = true;

          for_alist(stmt, module->block->body)
          {
            if (DefExpr* defExpr = toDefExpr(stmt))
            {
              if (Type* type = defExpr->sym->type)
              {
                int size = sizeForType(type);

                if (first == true)
                {
                  printf("   Module %s\n", module->name);
                  first = false;
                }

                printf("      %-20s ", defExpr->sym->name);

                if (strcmp(type->symbol->name, "bool") == 0)
                {
                  if (*((long*) env) == 0)
                    printf("       false\n");
                  else
                    printf("        true\n");
                }

                else if (strcmp(type->symbol->name, "int") == 0)
                {
                  printf("%12lu\n", *((long*) env));
                }

                else if (strcmp(type->symbol->name, "real") == 0)
                {
                  printf("     %12.4f\n", *((double*) env));
                }

                env = ((char*) env) + size;
              }
            }
          }
        }
      }
    }
  }
}

static int sizeForType(Type* type)
{
  int retval = 0;

  if (false)
    retval = 0;

  else if (strcmp(type->symbol->name, "bool") == 0)
    retval = 8;

  else if (strcmp(type->symbol->name, "int")  == 0)
    retval = 8;

  else if (strcmp(type->symbol->name, "real") == 0)
    retval = 8;

  else
  {
    AstDumpToNode logger(stdout);

    printf("sizeForType unhandled\n");
    type->accept(&logger);
    printf("\n\n\n\n\n");
    INT_ASSERT(false);
  }

  return retval;
}
<|endoftext|>


<commit_before>/*!   Copyright (c) 2010-2012 Delft University of Technology.
 *
 *    This software is protected by national and international copyright.
 *    Any unauthorized use, reproduction or modification is unlawful and
 *    will be prosecuted. Commercial and non-private application of the
 *    software in any form is strictly prohibited unless otherwise granted
 *    by the authors.
 *
 *    The code is provided without any warranty; without even the implied
 *    warranty of merchantibility or fitness for a particular purpose.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      110527    K. Kumar        First creation of the code.
 *
 *    References
 *
 */

// Temporary notes (move to class/function doxygen):
// Test runs code and verifies result against expected value.
// If the tested code is erroneous, the test function returns a boolean
// true; if the code is correct, the function returns a boolean false.
//

// Include statements.
#include <cmath>
#include <iostream>
#include <limits>
#include "Tudat/Astrodynamics/MissionSegments/deepSpaceManeuver.h"
#include "Tudat/Astrodynamics/States/cartesianElements.h"

//! Test deep space maneuver.
int main( )
{
    // Using declarations.
    using std::cerr;
    using std::endl;
    using namespace tudat;

    // Summary of tests.
    // Test 1: Test setTime( ) and getTime( ) functions.
    // Test 2: Test setState( ) and getState( ) functions with Cartesian elements state.

    // Test result initialised to false.
    bool isDeepSpaceManeuverErroneous_ = false;

    // Create DSM object.
    DeepSpaceManeuver deepSpaceManeuver_;

    // Test 1: Test setTime( ) and getTime( ) functions.
    // Declare and initialize time of DSM.
    double timeOfDeepSpaceManeuver_ = 123.3;

    // Set time of DSM.
    deepSpaceManeuver_.setTime( timeOfDeepSpaceManeuver_ );

    // Test if getTime( ) function results in set time for DSM.
    if ( std::fabs( timeOfDeepSpaceManeuver_ - deepSpaceManeuver_.getTime( ) )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setTime( )/getTime( ) functions do not work properly." << endl;

        isDeepSpaceManeuverErroneous_ = true;
    }

    // Test 2: Test setState( ) and getState( ) functions with Cartesian elements
    //         state.
    // Declare and initialize Cartesian elements state for DSM.
    CartesianElements deepSpaceManeuverState_;
    deepSpaceManeuverState_.setCartesianElementX( 1000.3 );
    deepSpaceManeuverState_.setCartesianElementY( 0.0 );
    deepSpaceManeuverState_.setCartesianElementZ( 613.41 );
    deepSpaceManeuverState_.setCartesianElementXDot( 2300.5 );
    deepSpaceManeuverState_.setCartesianElementYDot( 100.34 );
    deepSpaceManeuverState_.setCartesianElementZ( 0.0 );

    // Set DSM state.
    deepSpaceManeuver_.setState( &deepSpaceManeuverState_ );

    // Test if getState( ) function results in set state for DSM.
    if ( std::fabs( deepSpaceManeuverState_.state.norm( )
                    - deepSpaceManeuver_.getState( )->state.norm( ) )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setState( )/getState( ) functions do not work properly." << endl;
        isDeepSpaceManeuverErroneous_ = true;
    }

    // Test 1: Test setDeltaV( ) and getDeltaV( ) functions.
    // Declare and initialize deltaV for DSM.
    double deltaVOfDeepSpaceManeuver_ = 254.78;

    // Set deltaV of DSM.
    deepSpaceManeuver_.setDeltaV( deltaVOfDeepSpaceManeuver_ );

    // Test if getDeltaV( ) function results in set deltaV for DSM.
    if ( std::fabs( deltaVOfDeepSpaceManeuver_ - deepSpaceManeuver_.getDeltaV( ) )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setDeltaV( )/getDeltaV( ) functions do not work properly." << endl;
        isDeepSpaceManeuverErroneous_ = true;
    }

    // Return test result.
    // If test is successful return false; if test fails, return true.
    if ( isDeepSpaceManeuverErroneous_ )
    {
        cerr << "testDeepSpaceManeuver failed!" << endl;
    }

    return isDeepSpaceManeuverErroneous_;
}

// End of file.
<commit_msg>Precision fix in DSM unit test<commit_after>/*!   Copyright (c) 2010-2012 Delft University of Technology.
 *
 *    This software is protected by national and international copyright.
 *    Any unauthorized use, reproduction or modification is unlawful and
 *    will be prosecuted. Commercial and non-private application of the
 *    software in any form is strictly prohibited unless otherwise granted
 *    by the authors.
 *
 *    The code is provided without any warranty; without even the implied
 *    warranty of merchantibility or fitness for a particular purpose.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      110527    K. Kumar        First creation of the code.
 *
 *    References
 *
 */

// Temporary notes (move to class/function doxygen):
// Test runs code and verifies result against expected value.
// If the tested code is erroneous, the test function returns a boolean
// true; if the code is correct, the function returns a boolean false.
//

// Include statements.
#include <cmath>
#include <iostream>
#include <limits>
#include "Tudat/Astrodynamics/MissionSegments/deepSpaceManeuver.h"
#include "Tudat/Astrodynamics/States/cartesianElements.h"

//! Test deep space maneuver.
int main( )
{
    // Using declarations.
    using std::cerr;
    using std::endl;
    using namespace tudat;

    // Summary of tests.
    // Test 1: Test setTime( ) and getTime( ) functions.
    // Test 2: Test setState( ) and getState( ) functions with Cartesian elements state.

    // Test result initialised to false.
    bool isDeepSpaceManeuverErroneous_ = false;

    // Create DSM object.
    DeepSpaceManeuver deepSpaceManeuver_;

    // Test 1: Test setTime( ) and getTime( ) functions.
    // Declare and initialize time of DSM.
    double timeOfDeepSpaceManeuver_ = 123.3;

    // Set time of DSM.
    deepSpaceManeuver_.setTime( timeOfDeepSpaceManeuver_ );

    // Test if getTime( ) function results in set time for DSM.
    if ( std::fabs( timeOfDeepSpaceManeuver_ - deepSpaceManeuver_.getTime( ) )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setTime( )/getTime( ) functions do not work properly." << endl;

        isDeepSpaceManeuverErroneous_ = true;
    }

    // Test 2: Test setState( ) and getState( ) functions with Cartesian elements
    //         state.
    // Declare and initialize Cartesian elements state for DSM.
    CartesianElements deepSpaceManeuverState_;
    deepSpaceManeuverState_.setCartesianElementX( 1000.3 );
    deepSpaceManeuverState_.setCartesianElementY( 0.0 );
    deepSpaceManeuverState_.setCartesianElementZ( 613.41 );
    deepSpaceManeuverState_.setCartesianElementXDot( 2300.5 );
    deepSpaceManeuverState_.setCartesianElementYDot( 100.34 );
    deepSpaceManeuverState_.setCartesianElementZ( 0.0 );

    // Set DSM state.
    deepSpaceManeuver_.setState( &deepSpaceManeuverState_ );

    // Test if getState( ) function results in set state for DSM.
    if ( std::fabs( deepSpaceManeuverState_.state.norm( )
                    - deepSpaceManeuver_.getState( )->state.norm( ) )
         / deepSpaceManeuverState_.state.norm( )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setState( )/getState( ) functions do not work properly." << endl;
        isDeepSpaceManeuverErroneous_ = true;
    }

    // Test 1: Test setDeltaV( ) and getDeltaV( ) functions.
    // Declare and initialize deltaV for DSM.
    double deltaVOfDeepSpaceManeuver_ = 254.78;

    // Set deltaV of DSM.
    deepSpaceManeuver_.setDeltaV( deltaVOfDeepSpaceManeuver_ );

    // Test if getDeltaV( ) function results in set deltaV for DSM.
    if ( std::fabs( deltaVOfDeepSpaceManeuver_ - deepSpaceManeuver_.getDeltaV( ) )
         > std::numeric_limits< double >::epsilon( ) )
    {
        cerr << "The setDeltaV( )/getDeltaV( ) functions do not work properly." << endl;
        isDeepSpaceManeuverErroneous_ = true;
    }

    // Return test result.
    // If test is successful return false; if test fails, return true.
    if ( isDeepSpaceManeuverErroneous_ )
    {
        cerr << "testDeepSpaceManeuver failed!" << endl;
    }

    return isDeepSpaceManeuverErroneous_;
}

// End of file.
<|endoftext|>