<commit_before>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_PRINT_RULES_TRAITS_HPP
#define TAO_PEGTL_CONTRIB_PRINT_RULES_TRAITS_HPP

#include "../config.hpp"
#include "../rules.hpp"

#include "../internal/peek_char.hpp"
#incldue "../internal/peek_utf8.hpp"

#include "forward.hpp"

#include "internal/print_utility.hpp"

namespace TAO_PEGTL_NAMESPACE
{
   template<>
   struct print_rules_traits< internal::ranges< internal::peek_char, 'a', 'z', 'A', 'Z', '0', '9' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "alnum";
      }
   };

   template<>
   struct print_rules_traits< internal::ranges< internal::peek_char, 'a', 'z', 'A', 'Z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "alpha";
      }
   };

   template<>
   struct print_rules_traits< internal::any< internal::peek_char > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "any";
      }
   };

   template<>
   struct print_rules_traits< internal::any< internal::peek_utf8 > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "utf8";
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::at< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "at" );
      }
   };

   template<>
   struct print_rules_traits< internal::bof >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bof";
      }
   };

   template<>
   struct print_rules_traits< internal::bol >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bol";
      }
   };

   template< unsigned Num >
   struct print_rules_traits< internal::bytes< Num > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bytes( " << Num << " )";
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, '0', '9' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "digit";
      }
   };

   template<>
   struct print_rules_traits< internal::eof >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eof";
      }
   };

   template<>
   struct print_rules_traits< internal::eol >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eol";
      }
   };

   template<>
   struct print_rules_traits< internal::eolf >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eolf";
      }
   };

   template<>
   struct print_rules_traits< internal::failure >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "failure";
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::if_must< false, Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "if_must" );
      }
   };

   template< typename Cond, typename Then, typename Else >
   struct print_rules_traits< internal::if_then_else< Cond, Then, Else > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Then, Else >( os, prefix, "if_then_else" );
      }
   };

   template< typename Cond, typename Then, typename Else >
   struct print_rules_traits< internal::if_then_else< Cond, internal::must< Then >, internal::must< Else > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Then, Else >( os, prefix, "if_must_else" );
      }
   };

   template< char... Cs >
   struct print_rules_traits< internal::istring< Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "istring( \"";
         ( internal::print_escape( os, Cs ), ... );
         os << "\" )";
      }
   };

   template< typename Rule, typename Sep >
   struct print_rules_traits< internal::seq< Rule, internal::star< Sep, Rule > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rule, Sep >( os, prefix, "list" );
      }
   };

   template< typename Rule, typename Sep >
   struct print_rules_traits< internal::seq< Rule, internal::star< Sep, internal::must< Rule > > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rule, Sep >( os, prefix, "list_must" );
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, 'a', 'z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "lower";
      }
   };

   template< typename Head, typename Rule >
   struct print_rules_traits< internal::rematch< Head, internal::not_at< Rule, internal::eof > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Head, Rule >( os, prefix, "minus" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::must< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[38;5;202mmust\033[m" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::not_at< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "not_at" );
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::one< internal::result_on_found::failure, Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "not_one( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi >
   struct print_rules_traits< internal::range< internal::result_on_found::failure, Peek, Lo, Hi > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "not_range( ";
         internal::print_escape1( os, Lo );
         os << ", ";
         internal::print_escape1( os, Hi );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::one< internal::result_on_found::success, Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "one( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::opt< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "opt" );
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::if_must< true, Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "opt_must" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::plus< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "plus" );
      }
   };

   template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi >
   struct print_rules_traits< internal::range< internal::result_on_found::success, Peek, Lo, Hi > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "range( ";
         internal::print_escape1( os, Lo );
         os << ", ";
         internal::print_escape1( os, Hi );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::ranges< Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "ranges( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename Head, typename... Rules >
   struct print_rules_traits< internal::rematch< Head, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Head, Rules... >( os, prefix, "rematch" );
      }
   };

   template< unsigned Cnt, typename... Rules >
   struct print_rules_traits< internal::rep< Cnt, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         os << "rep( " << Cnt;
         internal::print_rules_rules< Rules... >( os, prefix, "", ", " );
      }
   };

   template< typename Rule >
   struct print_rules_traits< internal::seq< Rule > >
      : print_rules_traits< typename Rule::rule_t >
   {};

   template< typename... Rules >
   struct print_rules_traits< internal::seq< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[1;38;5;64mseq\033[m" );
      }
   };

   template< typename Rule >
   struct print_rules_traits< internal::sor< Rule > >
      : print_rules_traits< typename Rule::rule_t >
   {};

   template< typename... Rules >
   struct print_rules_traits< internal::sor< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[1;38;5;27msor\033[m" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::star< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "star" );
      }
   };

   template< char... Cs >
   struct print_rules_traits< internal::string< Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "string( \"";
         ( internal::print_escape( os, Cs ), ... );
         os << "\" )";
      }
   };

   template<>
   struct print_rules_traits< internal::success >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "success";
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::until< Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "until" );
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, 'A', 'Z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "upper";
      }
   };

}  // namespace TAO_PEGTL_NAMESPACE

#endif
<commit_msg>Fix typo.<commit_after>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_CONTRIB_PRINT_RULES_TRAITS_HPP
#define TAO_PEGTL_CONTRIB_PRINT_RULES_TRAITS_HPP

#include "../config.hpp"
#include "../rules.hpp"

#include "../internal/peek_char.hpp"
#include "../internal/peek_utf8.hpp"

#include "forward.hpp"

#include "internal/print_utility.hpp"

namespace TAO_PEGTL_NAMESPACE
{
   template<>
   struct print_rules_traits< internal::ranges< internal::peek_char, 'a', 'z', 'A', 'Z', '0', '9' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "alnum";
      }
   };

   template<>
   struct print_rules_traits< internal::ranges< internal::peek_char, 'a', 'z', 'A', 'Z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "alpha";
      }
   };

   template<>
   struct print_rules_traits< internal::any< internal::peek_char > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "any";
      }
   };

   template<>
   struct print_rules_traits< internal::any< internal::peek_utf8 > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "utf8";
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::at< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "at" );
      }
   };

   template<>
   struct print_rules_traits< internal::bof >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bof";
      }
   };

   template<>
   struct print_rules_traits< internal::bol >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bol";
      }
   };

   template< unsigned Num >
   struct print_rules_traits< internal::bytes< Num > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "bytes( " << Num << " )";
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, '0', '9' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "digit";
      }
   };

   template<>
   struct print_rules_traits< internal::eof >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eof";
      }
   };

   template<>
   struct print_rules_traits< internal::eol >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eol";
      }
   };

   template<>
   struct print_rules_traits< internal::eolf >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "eolf";
      }
   };

   template<>
   struct print_rules_traits< internal::failure >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "failure";
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::if_must< false, Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "if_must" );
      }
   };

   template< typename Cond, typename Then, typename Else >
   struct print_rules_traits< internal::if_then_else< Cond, Then, Else > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Then, Else >( os, prefix, "if_then_else" );
      }
   };

   template< typename Cond, typename Then, typename Else >
   struct print_rules_traits< internal::if_then_else< Cond, internal::must< Then >, internal::must< Else > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Then, Else >( os, prefix, "if_must_else" );
      }
   };

   template< char... Cs >
   struct print_rules_traits< internal::istring< Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "istring( \"";
         ( internal::print_escape( os, Cs ), ... );
         os << "\" )";
      }
   };

   template< typename Rule, typename Sep >
   struct print_rules_traits< internal::seq< Rule, internal::star< Sep, Rule > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rule, Sep >( os, prefix, "list" );
      }
   };

   template< typename Rule, typename Sep >
   struct print_rules_traits< internal::seq< Rule, internal::star< Sep, internal::must< Rule > > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rule, Sep >( os, prefix, "list_must" );
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, 'a', 'z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "lower";
      }
   };

   template< typename Head, typename Rule >
   struct print_rules_traits< internal::rematch< Head, internal::not_at< Rule, internal::eof > > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Head, Rule >( os, prefix, "minus" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::must< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[38;5;202mmust\033[m" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::not_at< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "not_at" );
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::one< internal::result_on_found::failure, Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "not_one( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi >
   struct print_rules_traits< internal::range< internal::result_on_found::failure, Peek, Lo, Hi > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "not_range( ";
         internal::print_escape1( os, Lo );
         os << ", ";
         internal::print_escape1( os, Hi );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::one< internal::result_on_found::success, Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "one( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::opt< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "opt" );
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::if_must< true, Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "opt_must" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::plus< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "plus" );
      }
   };

   template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi >
   struct print_rules_traits< internal::range< internal::result_on_found::success, Peek, Lo, Hi > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "range( ";
         internal::print_escape1( os, Lo );
         os << ", ";
         internal::print_escape1( os, Hi );
         os << " )";
      }
   };

   template< typename Peek, typename Peek::data_t C, typename Peek::data_t... Cs >
   struct print_rules_traits< internal::ranges< Peek, C, Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "ranges( ";
         ( internal::print_escape1( os, C ), ..., ( os << ", ", internal::print_escape1( os, Cs ) ) );
         os << " )";
      }
   };

   template< typename Head, typename... Rules >
   struct print_rules_traits< internal::rematch< Head, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Head, Rules... >( os, prefix, "rematch" );
      }
   };

   template< unsigned Cnt, typename... Rules >
   struct print_rules_traits< internal::rep< Cnt, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         os << "rep( " << Cnt;
         internal::print_rules_rules< Rules... >( os, prefix, "", ", " );
      }
   };

   template< typename Rule >
   struct print_rules_traits< internal::seq< Rule > >
      : print_rules_traits< typename Rule::rule_t >
   {};

   template< typename... Rules >
   struct print_rules_traits< internal::seq< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[1;38;5;64mseq\033[m" );
      }
   };

   template< typename Rule >
   struct print_rules_traits< internal::sor< Rule > >
      : print_rules_traits< typename Rule::rule_t >
   {};

   template< typename... Rules >
   struct print_rules_traits< internal::sor< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "\033[1;38;5;27msor\033[m" );
      }
   };

   template< typename... Rules >
   struct print_rules_traits< internal::star< Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Rules... >( os, prefix, "star" );
      }
   };

   template< char... Cs >
   struct print_rules_traits< internal::string< Cs... > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "string( \"";
         ( internal::print_escape( os, Cs ), ... );
         os << "\" )";
      }
   };

   template<>
   struct print_rules_traits< internal::success >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "success";
      }
   };

   template< typename Cond, typename... Rules >
   struct print_rules_traits< internal::until< Cond, Rules... > >
   {
      static void print( std::ostream& os, const std::string_view prefix )
      {
         internal::print_rules_rules< Cond, Rules... >( os, prefix, "until" );
      }
   };

   template<>
   struct print_rules_traits< internal::range< internal::result_on_found::success, internal::peek_char, 'A', 'Z' > >
   {
      static void print( std::ostream& os, const std::string_view /*unused*/ )
      {
         os << "upper";
      }
   };

}  // namespace TAO_PEGTL_NAMESPACE

#endif
<|endoftext|>


<commit_before><commit_msg>fix/add_custom_icons (#2167)<commit_after><|endoftext|>


<commit_before><commit_msg>Set correct grid color.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabvwshh.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 15:18:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

// INCLUDE ---------------------------------------------------------------

#include <svx/svdmark.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/request.hxx>
#include <basic/sbxcore.hxx>
#include <svtools/whiter.hxx>

#include "tabvwsh.hxx"
#include "client.hxx"
#include "document.hxx"
#include "docsh.hxx"
#include "sc.hrc"
#include "drwlayer.hxx"     // GetVisibleName

using namespace com::sun::star;

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

void ScTabViewShell::ExecuteSbx( SfxRequest& rReq )
{
    //  SID_RANGE_OFFSET (Offset),
    //  SID_PIVOT_CREATE (DataPilotCreate) - removed (old Basic)
}

void ScTabViewShell::GetSbxState( SfxItemSet& rSet )
{
    //  SID_RANGE_REGION (CurrentRegion) - removed (old Basic)
}

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

void ScTabViewShell::ExecuteObject( SfxRequest& rReq )
{
    USHORT nSlotId = rReq.GetSlot();
    const SfxItemSet* pReqArgs = rReq.GetArgs();

        //  Objekte aktivieren/deaktivieren immer auf der sichtbaren View

    ScTabViewShell* pVisibleSh = this;
    if ( nSlotId == SID_OLE_SELECT || nSlotId == SID_OLE_ACTIVATE || nSlotId == SID_OLE_DEACTIVATE )
    {
        DBG_ERROR("old slot SID_OLE...");
    }

    switch (nSlotId)
    {
        case SID_OLE_SELECT:
        case SID_OLE_ACTIVATE:
            {
                //  in beiden Faellen erstmal auf der sichtbaren View selektieren

                String aName;
                SdrView* pDrView = GetSdrView();
                if (pDrView)
                {
                    const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                    if (rMarkList.GetMarkCount() == 1)
                        aName = ScDrawLayer::GetVisibleName( rMarkList.GetMark(0)->GetObj() );
                }
                pVisibleSh->SelectObject( aName );

                //  aktivieren

                if ( nSlotId == SID_OLE_ACTIVATE )
                    pVisibleSh->DoVerb( 0 );
            }
            break;
        case SID_OLE_DEACTIVATE:
            pVisibleSh->DeactivateOle();
            break;

        case SID_OBJECT_LEFT:
        case SID_OBJECT_TOP:
        case SID_OBJECT_WIDTH:
        case SID_OBJECT_HEIGHT:
            {
                BOOL bDone = FALSE;
                const SfxPoolItem* pItem;
                if ( pReqArgs && pReqArgs->GetItemState( nSlotId, TRUE, &pItem ) == SFX_ITEM_SET )
                {
                    long nNewVal = ((const SfxInt32Item*)pItem)->GetValue();
                    if ( nNewVal < 0 )
                        nNewVal = 0;

                    //! von irgendwas in 1/100mm umrechnen ??????

                    SdrView* pDrView = GetSdrView();
                    if ( pDrView )
                    {
                        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                        if (rMarkList.GetMarkCount() == 1)
                        {
                            SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
                            Rectangle aRect = pObj->GetLogicRect();

                            if ( nSlotId == SID_OBJECT_LEFT )
                                pDrView->MoveMarkedObj( Size( nNewVal - aRect.Left(), 0 ) );
                            else if ( nSlotId == SID_OBJECT_TOP )
                                pDrView->MoveMarkedObj( Size( 0, nNewVal - aRect.Top() ) );
                            else if ( nSlotId == SID_OBJECT_WIDTH )
                                pDrView->ResizeMarkedObj( aRect.TopLeft(),
                                                Fraction( nNewVal, aRect.GetWidth() ),
                                                Fraction( 1, 1 ) );
                            else // if ( nSlotId == SID_OBJECT_HEIGHT )
                                pDrView->ResizeMarkedObj( aRect.TopLeft(),
                                                Fraction( 1, 1 ),
                                                Fraction( nNewVal, aRect.GetHeight() ) );
                            bDone = TRUE;
                        }
                    }
                }
                if (!bDone)
                    SbxBase::SetError( SbxERR_BAD_PARAMETER );  // Basic-Fehler
            }
            break;

    }
}

uno::Reference < embed::XEmbeddedObject > lcl_GetSelectedObj( SdrView* pDrView )       //! Member von ScDrawView?
{
    uno::Reference < embed::XEmbeddedObject > xRet;
    if (pDrView)
    {
        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
        if (rMarkList.GetMarkCount() == 1)
        {
            SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
            if (pObj->GetObjIdentifier() == OBJ_OLE2)
            {
                SdrOle2Obj* pOle2Obj = (SdrOle2Obj*) pObj;
                xRet = pOle2Obj->GetObjRef();
            }
        }
    }

    return xRet;
}

void ScTabViewShell::GetObjectState( SfxItemSet& rSet )
{
    //  SID_OLE_OBJECT - removed (old Basic)

    SfxWhichIter aIter(rSet);
    USHORT nWhich = aIter.FirstWhich();
    while ( nWhich )
    {
        switch (nWhich)
        {
            case SID_ACTIVE_OBJ_NAME:
                {
                    String aName;
                    uno::Reference < embed::XEmbeddedObject > xOLE = lcl_GetSelectedObj( GetSdrView() );
                    if (xOLE.is())
                    {
                        aName = GetViewData()->GetSfxDocShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xOLE );
                    }
                    rSet.Put( SfxStringItem( nWhich, aName ) );
                }
                break;
            case SID_OBJECT_LEFT:
            case SID_OBJECT_TOP:
            case SID_OBJECT_WIDTH:
            case SID_OBJECT_HEIGHT:
                {
                    SdrView* pDrView = GetSdrView();
                    if ( pDrView )
                    {
                        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                        if (rMarkList.GetMarkCount() == 1)
                        {
                            SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
                            Rectangle aRect = pObj->GetLogicRect();

                            long nVal;
                            if ( nWhich == SID_OBJECT_LEFT )
                                nVal = aRect.Left();
                            else if ( nWhich == SID_OBJECT_TOP )
                                nVal = aRect.Top();
                            else if ( nWhich == SID_OBJECT_WIDTH )
                                nVal = aRect.GetWidth();
                            else // if ( nWhich == SID_OBJECT_HEIGHT )
                                nVal = aRect.GetHeight();

                            //! von 1/100mm in irgendwas umrechnen ??????

                            rSet.Put( SfxInt32Item( nWhich, nVal ) );
                        }
                    }
                }
                break;
        }
        nWhich = aIter.NextWhich();
    }
}

void ScTabViewShell::AddAccessibilityObject( SfxListener& rObject )
{
    if (!pAccessibilityBroadcaster)
        pAccessibilityBroadcaster = new SfxBroadcaster;

    rObject.StartListening( *pAccessibilityBroadcaster );
    ScDocument* pDoc = GetViewData()->GetDocument();
    if (pDoc)
        pDoc->AddUnoObject(rObject);
}

void ScTabViewShell::RemoveAccessibilityObject( SfxListener& rObject )
{
    if (pAccessibilityBroadcaster)
    {
        rObject.EndListening( *pAccessibilityBroadcaster );
        ScDocument* pDoc = GetViewData()->GetDocument();
        if (pDoc)
            pDoc->RemoveUnoObject(rObject);
    }
    else
        DBG_ERROR("kein Accessibility-Broadcaster??!?");
}

void ScTabViewShell::BroadcastAccessibility( const SfxHint &rHint )
{
    if (pAccessibilityBroadcaster)
        pAccessibilityBroadcaster->Broadcast( rHint );
}

BOOL ScTabViewShell::HasAccessibilityObjects()
{
    return pAccessibilityBroadcaster != NULL;
}

<commit_msg>INTEGRATION: CWS aw035 (1.11.218); FILE MERGED 2006/07/13 15:04:14 aw 1.11.218.1: #126320# SdrMark::GetObj() -> SdrMark::GetMarkedSdrObj() for isolating selection handling<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabvwshh.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-25 12:27:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

// INCLUDE ---------------------------------------------------------------

#include <svx/svdmark.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/request.hxx>
#include <basic/sbxcore.hxx>
#include <svtools/whiter.hxx>

#include "tabvwsh.hxx"
#include "client.hxx"
#include "document.hxx"
#include "docsh.hxx"
#include "sc.hrc"
#include "drwlayer.hxx"     // GetVisibleName

using namespace com::sun::star;

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

void ScTabViewShell::ExecuteSbx( SfxRequest& rReq )
{
    //  SID_RANGE_OFFSET (Offset),
    //  SID_PIVOT_CREATE (DataPilotCreate) - removed (old Basic)
}

void ScTabViewShell::GetSbxState( SfxItemSet& rSet )
{
    //  SID_RANGE_REGION (CurrentRegion) - removed (old Basic)
}

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

void ScTabViewShell::ExecuteObject( SfxRequest& rReq )
{
    USHORT nSlotId = rReq.GetSlot();
    const SfxItemSet* pReqArgs = rReq.GetArgs();

        //  Objekte aktivieren/deaktivieren immer auf der sichtbaren View

    ScTabViewShell* pVisibleSh = this;
    if ( nSlotId == SID_OLE_SELECT || nSlotId == SID_OLE_ACTIVATE || nSlotId == SID_OLE_DEACTIVATE )
    {
        DBG_ERROR("old slot SID_OLE...");
    }

    switch (nSlotId)
    {
        case SID_OLE_SELECT:
        case SID_OLE_ACTIVATE:
            {
                //  in beiden Faellen erstmal auf der sichtbaren View selektieren

                String aName;
                SdrView* pDrView = GetSdrView();
                if (pDrView)
                {
                    const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                    if (rMarkList.GetMarkCount() == 1)
                        aName = ScDrawLayer::GetVisibleName( rMarkList.GetMark(0)->GetMarkedSdrObj() );
                }
                pVisibleSh->SelectObject( aName );

                //  aktivieren

                if ( nSlotId == SID_OLE_ACTIVATE )
                    pVisibleSh->DoVerb( 0 );
            }
            break;
        case SID_OLE_DEACTIVATE:
            pVisibleSh->DeactivateOle();
            break;

        case SID_OBJECT_LEFT:
        case SID_OBJECT_TOP:
        case SID_OBJECT_WIDTH:
        case SID_OBJECT_HEIGHT:
            {
                BOOL bDone = FALSE;
                const SfxPoolItem* pItem;
                if ( pReqArgs && pReqArgs->GetItemState( nSlotId, TRUE, &pItem ) == SFX_ITEM_SET )
                {
                    long nNewVal = ((const SfxInt32Item*)pItem)->GetValue();
                    if ( nNewVal < 0 )
                        nNewVal = 0;

                    //! von irgendwas in 1/100mm umrechnen ??????

                    SdrView* pDrView = GetSdrView();
                    if ( pDrView )
                    {
                        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                        if (rMarkList.GetMarkCount() == 1)
                        {
                            SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
                            Rectangle aRect = pObj->GetLogicRect();

                            if ( nSlotId == SID_OBJECT_LEFT )
                                pDrView->MoveMarkedObj( Size( nNewVal - aRect.Left(), 0 ) );
                            else if ( nSlotId == SID_OBJECT_TOP )
                                pDrView->MoveMarkedObj( Size( 0, nNewVal - aRect.Top() ) );
                            else if ( nSlotId == SID_OBJECT_WIDTH )
                                pDrView->ResizeMarkedObj( aRect.TopLeft(),
                                                Fraction( nNewVal, aRect.GetWidth() ),
                                                Fraction( 1, 1 ) );
                            else // if ( nSlotId == SID_OBJECT_HEIGHT )
                                pDrView->ResizeMarkedObj( aRect.TopLeft(),
                                                Fraction( 1, 1 ),
                                                Fraction( nNewVal, aRect.GetHeight() ) );
                            bDone = TRUE;
                        }
                    }
                }
                if (!bDone)
                    SbxBase::SetError( SbxERR_BAD_PARAMETER );  // Basic-Fehler
            }
            break;

    }
}

uno::Reference < embed::XEmbeddedObject > lcl_GetSelectedObj( SdrView* pDrView )       //! Member von ScDrawView?
{
    uno::Reference < embed::XEmbeddedObject > xRet;
    if (pDrView)
    {
        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
        if (rMarkList.GetMarkCount() == 1)
        {
            SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
            if (pObj->GetObjIdentifier() == OBJ_OLE2)
            {
                SdrOle2Obj* pOle2Obj = (SdrOle2Obj*) pObj;
                xRet = pOle2Obj->GetObjRef();
            }
        }
    }

    return xRet;
}

void ScTabViewShell::GetObjectState( SfxItemSet& rSet )
{
    //  SID_OLE_OBJECT - removed (old Basic)

    SfxWhichIter aIter(rSet);
    USHORT nWhich = aIter.FirstWhich();
    while ( nWhich )
    {
        switch (nWhich)
        {
            case SID_ACTIVE_OBJ_NAME:
                {
                    String aName;
                    uno::Reference < embed::XEmbeddedObject > xOLE = lcl_GetSelectedObj( GetSdrView() );
                    if (xOLE.is())
                    {
                        aName = GetViewData()->GetSfxDocShell()->GetEmbeddedObjectContainer().GetEmbeddedObjectName( xOLE );
                    }
                    rSet.Put( SfxStringItem( nWhich, aName ) );
                }
                break;
            case SID_OBJECT_LEFT:
            case SID_OBJECT_TOP:
            case SID_OBJECT_WIDTH:
            case SID_OBJECT_HEIGHT:
                {
                    SdrView* pDrView = GetSdrView();
                    if ( pDrView )
                    {
                        const SdrMarkList& rMarkList = pDrView->GetMarkedObjectList();
                        if (rMarkList.GetMarkCount() == 1)
                        {
                            SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
                            Rectangle aRect = pObj->GetLogicRect();

                            long nVal;
                            if ( nWhich == SID_OBJECT_LEFT )
                                nVal = aRect.Left();
                            else if ( nWhich == SID_OBJECT_TOP )
                                nVal = aRect.Top();
                            else if ( nWhich == SID_OBJECT_WIDTH )
                                nVal = aRect.GetWidth();
                            else // if ( nWhich == SID_OBJECT_HEIGHT )
                                nVal = aRect.GetHeight();

                            //! von 1/100mm in irgendwas umrechnen ??????

                            rSet.Put( SfxInt32Item( nWhich, nVal ) );
                        }
                    }
                }
                break;
        }
        nWhich = aIter.NextWhich();
    }
}

void ScTabViewShell::AddAccessibilityObject( SfxListener& rObject )
{
    if (!pAccessibilityBroadcaster)
        pAccessibilityBroadcaster = new SfxBroadcaster;

    rObject.StartListening( *pAccessibilityBroadcaster );
    ScDocument* pDoc = GetViewData()->GetDocument();
    if (pDoc)
        pDoc->AddUnoObject(rObject);
}

void ScTabViewShell::RemoveAccessibilityObject( SfxListener& rObject )
{
    if (pAccessibilityBroadcaster)
    {
        rObject.EndListening( *pAccessibilityBroadcaster );
        ScDocument* pDoc = GetViewData()->GetDocument();
        if (pDoc)
            pDoc->RemoveUnoObject(rObject);
    }
    else
        DBG_ERROR("kein Accessibility-Broadcaster??!?");
}

void ScTabViewShell::BroadcastAccessibility( const SfxHint &rHint )
{
    if (pAccessibilityBroadcaster)
        pAccessibilityBroadcaster->Broadcast( rHint );
}

BOOL ScTabViewShell::HasAccessibilityObjects()
{
    return pAccessibilityBroadcaster != NULL;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

#include <ode/odeconfig.h>
#include <ode/misc.h>
#include <ode/matrix.h>
#include "config.h"

//****************************************************************************
// random numbers

static unsigned long seed = 0;

unsigned long dRand()
{
  seed = (1664525UL*seed + 1013904223UL) & 0xffffffff;
  return seed;
}

unsigned long  dRandGetSeed()
{
  return seed;
}

void dRandSetSeed (unsigned long s)
{
  seed = s;
}

int dTestRand()
{
  unsigned long oldseed = seed;
  int ret = 1;
  seed = 0;
  if (dRand() != 0x3c6ef35f || dRand() != 0x47502932 ||
      dRand() != 0xd1ccf6e9 || dRand() != 0xaaf95334 ||
      dRand() != 0x6252e503) ret = 0;
  seed = oldseed;
  return ret;
}

// adam's all-int straightforward(?) dRandInt (0..n-1)
int dRandInt (int n)
{
  // seems good; xor-fold and modulus
  const unsigned long un = n;
  // Since there is no memory barrier macro in ODE assign via volatile variable
  // to prevent compiler reusing seed as value of `r'
  volatile unsigned long raw_r = dRand();
  unsigned long r = raw_r;

  // note: probably more aggressive than it needs to be -- might be
  //       able to get away without one or two of the innermost branches.
  // if (un <= 0x00010000UL) {
  //   r ^= (r >> 16);
  //   if (un <= 0x00000100UL) {
  //     r ^= (r >> 8);
  //     if (un <= 0x00000010UL) {
  //       r ^= (r >> 4);
  //       if (un <= 0x00000004UL) {
  //         r ^= (r >> 2);
  //         if (un <= 0x00000002UL) {
  //           r ^= (r >> 1);
  //         }
  //       }
  //     }
  //   }
  // }
  // Optimized version of above
  if (un <= 0x00000010UL) {
    if (un <= 0x00000002UL) {
      r ^= (r >> 16);
      r ^= (r >> 8);
      r ^= (r >> 4);
      r ^= (r >> 2);
      r ^= (r >> 1);
    } else {
      if (un <= 0x00000004UL) {
        r ^= (r >> 16);
        r ^= (r >> 8);
        r ^= (r >> 4);
        r ^= (r >> 2);
      } else {
        r ^= (r >> 16);
        r ^= (r >> 8);
        r ^= (r >> 4);
      }
    }
  } else {
    if (un <= 0x00000100UL) {
      r ^= (r >> 16);
      r ^= (r >> 8);
    } else {
      if (un <= 0x00010000UL) {
        r ^= (r >> 16);
      }
    }
  }

  return (int) (r % un);
}

dReal dRandReal()
{
  return ((dReal) dRand()) / ((dReal) 0xffffffff);
}

//****************************************************************************
// matrix utility stuff

void dPrintMatrix (const dReal *A, int n, int m, char *fmt, FILE *f)
{
  int skip = dPAD(m);
  const dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=0; j<m; ++j) fprintf (f,fmt,Arow[j]);
    fprintf (f,"\n");
  }
}

void dMakeRandomVector (dReal *A, int n, dReal range)
{
  int i;
  for (i=0; i<n; i++) A[i] = (dRandReal()*REAL(2.0)-REAL(1.0))*range;
}

void dMakeRandomMatrix (dReal *A, int n, int m, dReal range)
{
  int skip = dPAD(m);
//  dSetZero (A,n*skip);
  dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=0; j<m; ++j) Arow[j] = (dRandReal()*REAL(2.0)-REAL(1.0))*range;
  }
}

void dClearUpperTriangle (dReal *A, int n)
{
  int skip = dPAD(n);
  dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=i+1; j<n; ++j) Arow[j] = 0;
  }
}

dReal dMaxDifference (const dReal *A, const dReal *B, int n, int m)
{
  int skip = dPAD(m);
  dReal max = REAL(0.0);
  const dReal *Arow = A, *Brow = B;
  for (int i=0; i<n; Arow+=skip, Brow +=skip, ++i) {
    for (int j=0; j<m; ++j) {
      dReal diff = dFabs(Arow[j] - Brow[j]);
      if (diff > max) max = diff;
    }
  }
  return max;
}

dReal dMaxDifferenceLowerTriangle (const dReal *A, const dReal *B, int n)
{
  int skip = dPAD(n);
  dReal max = REAL(0.0);
  const dReal *Arow = A, *Brow = B;
  for (int i=0; i<n; Arow+=skip, Brow+=skip, ++i) {
    for (int j=0; j<=i; ++j) {
      dReal diff = dFabs(Arow[j] - Brow[j]);
      if (diff > max) max = diff;
    }
  }
  return max;
}

<commit_msg>Cosmetic: Some common code moved out of branches<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * This library is distributed in the hope that it will be useful,       *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

#include <ode/odeconfig.h>
#include <ode/misc.h>
#include <ode/matrix.h>
#include "config.h"

//****************************************************************************
// random numbers

static unsigned long seed = 0;

unsigned long dRand()
{
  seed = (1664525UL*seed + 1013904223UL) & 0xffffffff;
  return seed;
}

unsigned long  dRandGetSeed()
{
  return seed;
}

void dRandSetSeed (unsigned long s)
{
  seed = s;
}

int dTestRand()
{
  unsigned long oldseed = seed;
  int ret = 1;
  seed = 0;
  if (dRand() != 0x3c6ef35f || dRand() != 0x47502932 ||
      dRand() != 0xd1ccf6e9 || dRand() != 0xaaf95334 ||
      dRand() != 0x6252e503) ret = 0;
  seed = oldseed;
  return ret;
}

// adam's all-int straightforward(?) dRandInt (0..n-1)
int dRandInt (int n)
{
  // seems good; xor-fold and modulus
  const unsigned long un = n;
  // Since there is no memory barrier macro in ODE assign via volatile variable
  // to prevent compiler reusing seed as value of `r'
  volatile unsigned long raw_r = dRand();
  unsigned long r = raw_r;

  // note: probably more aggressive than it needs to be -- might be
  //       able to get away without one or two of the innermost branches.
  // if (un <= 0x00010000UL) {
  //   r ^= (r >> 16);
  //   if (un <= 0x00000100UL) {
  //     r ^= (r >> 8);
  //     if (un <= 0x00000010UL) {
  //       r ^= (r >> 4);
  //       if (un <= 0x00000004UL) {
  //         r ^= (r >> 2);
  //         if (un <= 0x00000002UL) {
  //           r ^= (r >> 1);
  //         }
  //       }
  //     }
  //   }
  // }
  // Optimized version of above
  if (un <= 0x00000010UL) {
    r ^= (r >> 16);
    r ^= (r >> 8);
    r ^= (r >> 4);
    if (un <= 0x00000002UL) {
      r ^= (r >> 2);
      r ^= (r >> 1);
    } else {
      if (un <= 0x00000004UL) {
        r ^= (r >> 2);
      }
    }
  } else {
    if (un <= 0x00000100UL) {
      r ^= (r >> 16);
      r ^= (r >> 8);
    } else {
      if (un <= 0x00010000UL) {
        r ^= (r >> 16);
      }
    }
  }

  return (int) (r % un);
}

dReal dRandReal()
{
  return ((dReal) dRand()) / ((dReal) 0xffffffff);
}

//****************************************************************************
// matrix utility stuff

void dPrintMatrix (const dReal *A, int n, int m, char *fmt, FILE *f)
{
  int skip = dPAD(m);
  const dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=0; j<m; ++j) fprintf (f,fmt,Arow[j]);
    fprintf (f,"\n");
  }
}

void dMakeRandomVector (dReal *A, int n, dReal range)
{
  int i;
  for (i=0; i<n; i++) A[i] = (dRandReal()*REAL(2.0)-REAL(1.0))*range;
}

void dMakeRandomMatrix (dReal *A, int n, int m, dReal range)
{
  int skip = dPAD(m);
//  dSetZero (A,n*skip);
  dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=0; j<m; ++j) Arow[j] = (dRandReal()*REAL(2.0)-REAL(1.0))*range;
  }
}

void dClearUpperTriangle (dReal *A, int n)
{
  int skip = dPAD(n);
  dReal *Arow = A;
  for (int i=0; i<n; Arow+=skip, ++i) {
    for (int j=i+1; j<n; ++j) Arow[j] = 0;
  }
}

dReal dMaxDifference (const dReal *A, const dReal *B, int n, int m)
{
  int skip = dPAD(m);
  dReal max = REAL(0.0);
  const dReal *Arow = A, *Brow = B;
  for (int i=0; i<n; Arow+=skip, Brow +=skip, ++i) {
    for (int j=0; j<m; ++j) {
      dReal diff = dFabs(Arow[j] - Brow[j]);
      if (diff > max) max = diff;
    }
  }
  return max;
}

dReal dMaxDifferenceLowerTriangle (const dReal *A, const dReal *B, int n)
{
  int skip = dPAD(n);
  dReal max = REAL(0.0);
  const dReal *Arow = A, *Brow = B;
  for (int i=0; i<n; Arow+=skip, Brow+=skip, ++i) {
    for (int j=0; j<=i; ++j) {
      dReal diff = dFabs(Arow[j] - Brow[j]);
      if (diff > max) max = diff;
    }
  }
  return max;
}

<|endoftext|>


<commit_before>#include <iostream>;

int main(){
    std::cout << "Hello World!";
}<commit_msg>Delete test1.cpp<commit_after><|endoftext|>


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

/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

#include "meta_service.h"
#include "server_state.h"
#include "load_balancer.h"
#include "meta_server_failure_detector.h"
#include <sys/stat.h>

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "meta.service"

meta_service::meta_service()
    : serverlet("meta_service"), _failure_detector(nullptr), _balancer(nullptr), _started(false)
{
    _opts.initialize();
    // create in constructor because it may be used in checker before started
    _state = new server_state();
}

meta_service::~meta_service()
{
}

error_code meta_service::start()
{
    dassert(!_started, "meta service is already started");

    // init server state
    error_code err = _state->initialize();
    if (err != ERR_OK)
    {
        derror("init server_state failed, err = %s", err.to_string());
        return err;
    }
    ddebug("init server state succeed");

    // should register rpc handlers before acquiring leader lock, so that this meta service
    // can tell others who is the current leader
    register_rpc_handlers();

    _failure_detector = new meta_server_failure_detector(_state, this);
    // become leader
    _failure_detector->acquire_leader_lock();
    dassert(_failure_detector->is_primary(), "must be primary at this point");
    ddebug("hahaha, I got the primary lock! now start to recover server state");

    // recover server state
    while ((err = _state->on_become_leader()) != ERR_OK)
    {
        derror("recover server state failed, err = %s, retry ...");
    }
    ddebug("recover server state succeed");

    err = _failure_detector->start(
        _opts.fd_check_interval_seconds,
        _opts.fd_beacon_interval_seconds,
        _opts.fd_lease_seconds,
        _opts.fd_grace_seconds,
        false
        );
    if (err != ERR_OK)
    {
        derror("start failure_detector failed, err = %s", err.to_string());
        return err;
    }

    _balancer = new load_balancer(_state);
    // make sure the delay is larger than fd.grace to ensure
    // all machines are in the correct state (assuming connected initially)
    tasking::enqueue(LPC_LBM_START, this, &meta_service::on_load_balance_start, 0,
        _opts.fd_grace_seconds * 1000);

    ddebug("start meta_service succeed");
    return ERR_OK;
}

void meta_service::register_rpc_handlers()
{
    register_rpc_handler(
        RPC_CM_QUERY_NODE_PARTITIONS,
        "RPC_CM_QUERY_NODE_PARTITIONS",
        &meta_service::on_query_configuration_by_node
        );

    register_rpc_handler(
        RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX,
        "RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX",
        &meta_service::on_query_configuration_by_index
        );

    register_rpc_handler(
        RPC_CM_UPDATE_PARTITION_CONFIGURATION,
        "RPC_CM_UPDATE_PARTITION_CONFIGURATION",
        &meta_service::on_update_configuration
        );

    register_rpc_handler(
        RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND,
        "RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND",
        &meta_service::on_modify_replica_config_explictly
        );
}

void meta_service::stop()
{
    _started = false;

    unregister_rpc_handler(RPC_CM_QUERY_NODE_PARTITIONS);
    unregister_rpc_handler(RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX);
    unregister_rpc_handler(RPC_CM_UPDATE_PARTITION_CONFIGURATION);
    unregister_rpc_handler(RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND);

    if (_balancer_timer != nullptr)
    {
        _balancer_timer->cancel(true);
    }

    if (_balancer != nullptr)
    {
        delete _balancer;
        _balancer = nullptr;
    }

    if (_failure_detector != nullptr)
    {
        _failure_detector->stop();
        delete _failure_detector;
        _failure_detector = nullptr;
    }

    if (_state != nullptr)
    {
        delete _state;
        _state = nullptr;
    }
}

void meta_service::on_load_balance_start()
{
    dassert(_balancer_timer == nullptr, "");

    _state->unfree_if_possible_on_start();
    _balancer_timer = tasking::enqueue(LPC_LBM_RUN, this, &meta_service::on_load_balance_timer,
        0,
        1,
        10000
        );

    _started = true;
}

bool meta_service::check_primary(dsn_message_t req)
{
    if (!_failure_detector->is_primary())
    {
        auto primary = _failure_detector->get_primary();
        if (!primary.is_invalid())
        {
            dsn_rpc_forward(req, _failure_detector->get_primary().c_addr());
            return false;
        }
    }

    return true;
}

// partition server & client => meta server
void meta_service::on_query_configuration_by_node(dsn_message_t msg)
{
    if (!check_primary(msg))
        return;

    if (!_started)
    {
        configuration_query_by_node_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(msg, response);
        return;
    }

    configuration_query_by_node_response response;
    configuration_query_by_node_request request;
    ::unmarshall(msg, request);
    _state->query_configuration_by_node(request, response);
    reply(msg, response);
}

void meta_service::on_query_configuration_by_index(dsn_message_t msg)
{
    if (_failure_detector == nullptr || !check_primary(msg))
        return;

    if (!_started)
    {
        configuration_query_by_index_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(msg, response);
        return;
    }

    configuration_query_by_index_response response;
    configuration_query_by_index_request request;
    ::unmarshall(msg, request);
    _state->query_configuration_by_index(request, response);
    reply(msg, response);
}

void meta_service::on_modify_replica_config_explictly(dsn_message_t req)
{
    if (!check_primary(req))
        return;

    // TODO: implement modify config with reply
    if (!_started)
    {
        configuration_query_by_index_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(req, response);
        return;
    }

    global_partition_id gpid;
    rpc_address receiver;
    config_type type;
    rpc_address node;

    ::unmarshall(req, gpid);
    ::unmarshall(req, receiver);
    ::unmarshall(req, type);
    ::unmarshall(req, node);

    _balancer->explictly_send_proposal(gpid, receiver, type, node);
}

void meta_service::on_update_configuration(dsn_message_t req)
{
    if (!check_primary(req))
        return;

    if (!_started)
    {
        configuration_update_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(req, response);
        return;
    }

    std::shared_ptr<configuration_update_request> request(new configuration_update_request);
    ::unmarshall(req, *request);

    if (_state->freezed())
    {
        configuration_update_response response;

        response.err = ERR_STATE_FREEZED;
        _state->query_configuration_by_gpid(request->config.gpid, response.config);

        reply(req, response);
        return;
    }

    global_partition_id gpid = request->config.gpid;
    _state->update_configuration(request, req, [this, gpid](){
        if (_started)
        {
            tasking::enqueue(LPC_LBM_RUN, this, std::bind(&meta_service::on_config_changed, this, gpid));
        }
    });
}

void meta_service::update_configuration_on_machine_failure(std::shared_ptr<configuration_update_request>& update)
{
    global_partition_id gpid = update->config.gpid;
    _state->update_configuration(update, nullptr, [this, gpid](){
        if (_started)
        {
            tasking::enqueue(LPC_LBM_RUN, this, std::bind(&meta_service::on_config_changed, this, gpid));
        }
    });
}

// local timers
void meta_service::on_load_balance_timer()
{
    if (!_started)
        return;

    if (_state->freezed())
        return;

    if (_failure_detector->is_primary())
    {
        _balancer->run();
    }
}

void meta_service::on_config_changed(global_partition_id gpid)
{
    if (_failure_detector->is_primary())
    {
        _balancer->run(gpid);
    }
}
<commit_msg>minor change to meta_service initialization<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

#include "meta_service.h"
#include "server_state.h"
#include "load_balancer.h"
#include "meta_server_failure_detector.h"
#include <sys/stat.h>

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "meta.service"

meta_service::meta_service()
    : serverlet("meta_service"), _failure_detector(nullptr), _balancer(nullptr), _started(false)
{
    _opts.initialize();
    // create in constructor because it may be used in checker before started
    _state = new server_state();
}

meta_service::~meta_service()
{
}

error_code meta_service::start()
{
    dassert(!_started, "meta service is already started");

    // init server state
    error_code err = _state->initialize();
    if (err != ERR_OK)
    {
        derror("init server_state failed, err = %s", err.to_string());
        return err;
    }
    ddebug("init server state succeed");

    _failure_detector = new meta_server_failure_detector(_state, this);
    // should register rpc handlers before acquiring leader lock, so that this meta service
    // can tell others who is the current leader
    register_rpc_handlers();

    // become leader
    _failure_detector->acquire_leader_lock();
    dassert(_failure_detector->is_primary(), "must be primary at this point");
    ddebug("hahaha, I got the primary lock! now start to recover server state");

    // recover server state
    while ((err = _state->on_become_leader()) != ERR_OK)
    {
        derror("recover server state failed, err = %s, retry ...");
    }
    ddebug("recover server state succeed");

    err = _failure_detector->start(
        _opts.fd_check_interval_seconds,
        _opts.fd_beacon_interval_seconds,
        _opts.fd_lease_seconds,
        _opts.fd_grace_seconds,
        false
        );
    if (err != ERR_OK)
    {
        derror("start failure_detector failed, err = %s", err.to_string());
        return err;
    }

    _balancer = new load_balancer(_state);
    // make sure the delay is larger than fd.grace to ensure
    // all machines are in the correct state (assuming connected initially)
    tasking::enqueue(LPC_LBM_START, this, &meta_service::on_load_balance_start, 0,
        _opts.fd_grace_seconds * 1000);

    ddebug("start meta_service succeed");
    return ERR_OK;
}

void meta_service::register_rpc_handlers()
{
    register_rpc_handler(
        RPC_CM_QUERY_NODE_PARTITIONS,
        "RPC_CM_QUERY_NODE_PARTITIONS",
        &meta_service::on_query_configuration_by_node
        );

    register_rpc_handler(
        RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX,
        "RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX",
        &meta_service::on_query_configuration_by_index
        );

    register_rpc_handler(
        RPC_CM_UPDATE_PARTITION_CONFIGURATION,
        "RPC_CM_UPDATE_PARTITION_CONFIGURATION",
        &meta_service::on_update_configuration
        );

    register_rpc_handler(
        RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND,
        "RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND",
        &meta_service::on_modify_replica_config_explictly
        );
}

void meta_service::stop()
{
    _started = false;

    unregister_rpc_handler(RPC_CM_QUERY_NODE_PARTITIONS);
    unregister_rpc_handler(RPC_CM_QUERY_PARTITION_CONFIG_BY_INDEX);
    unregister_rpc_handler(RPC_CM_UPDATE_PARTITION_CONFIGURATION);
    unregister_rpc_handler(RPC_CM_MODIFY_REPLICA_CONFIG_COMMAND);

    if (_balancer_timer != nullptr)
    {
        _balancer_timer->cancel(true);
    }

    if (_balancer != nullptr)
    {
        delete _balancer;
        _balancer = nullptr;
    }

    if (_failure_detector != nullptr)
    {
        _failure_detector->stop();
        delete _failure_detector;
        _failure_detector = nullptr;
    }

    if (_state != nullptr)
    {
        delete _state;
        _state = nullptr;
    }
}

void meta_service::on_load_balance_start()
{
    dassert(_balancer_timer == nullptr, "");

    _state->unfree_if_possible_on_start();
    _balancer_timer = tasking::enqueue(LPC_LBM_RUN, this, &meta_service::on_load_balance_timer,
        0,
        1,
        10000
        );

    _started = true;
}

bool meta_service::check_primary(dsn_message_t req)
{
    if (!_failure_detector->is_primary())
    {
        auto primary = _failure_detector->get_primary();
        if (!primary.is_invalid())
        {
            dsn_rpc_forward(req, _failure_detector->get_primary().c_addr());
            return false;
        }
    }

    return true;
}

// partition server & client => meta server
void meta_service::on_query_configuration_by_node(dsn_message_t msg)
{
    if (!check_primary(msg))
        return;

    if (!_started)
    {
        configuration_query_by_node_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(msg, response);
        return;
    }

    configuration_query_by_node_response response;
    configuration_query_by_node_request request;
    ::unmarshall(msg, request);
    _state->query_configuration_by_node(request, response);
    reply(msg, response);
}

void meta_service::on_query_configuration_by_index(dsn_message_t msg)
{
    if (!check_primary(msg))
        return;

    if (!_started)
    {
        configuration_query_by_index_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(msg, response);
        return;
    }

    configuration_query_by_index_response response;
    configuration_query_by_index_request request;
    ::unmarshall(msg, request);
    _state->query_configuration_by_index(request, response);
    reply(msg, response);
}

void meta_service::on_modify_replica_config_explictly(dsn_message_t req)
{
    if (!check_primary(req))
        return;

    // TODO: implement modify config with reply
    if (!_started)
    {
        configuration_query_by_index_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(req, response);
        return;
    }

    global_partition_id gpid;
    rpc_address receiver;
    config_type type;
    rpc_address node;

    ::unmarshall(req, gpid);
    ::unmarshall(req, receiver);
    ::unmarshall(req, type);
    ::unmarshall(req, node);

    _balancer->explictly_send_proposal(gpid, receiver, type, node);
}

void meta_service::on_update_configuration(dsn_message_t req)
{
    if (!check_primary(req))
        return;

    if (!_started)
    {
        configuration_update_response response;
        response.err = ERR_SERVICE_NOT_ACTIVE;
        reply(req, response);
        return;
    }

    std::shared_ptr<configuration_update_request> request(new configuration_update_request);
    ::unmarshall(req, *request);

    if (_state->freezed())
    {
        configuration_update_response response;

        response.err = ERR_STATE_FREEZED;
        _state->query_configuration_by_gpid(request->config.gpid, response.config);

        reply(req, response);
        return;
    }

    global_partition_id gpid = request->config.gpid;
    _state->update_configuration(request, req, [this, gpid](){
        if (_started)
        {
            tasking::enqueue(LPC_LBM_RUN, this, std::bind(&meta_service::on_config_changed, this, gpid));
        }
    });
}

void meta_service::update_configuration_on_machine_failure(std::shared_ptr<configuration_update_request>& update)
{
    global_partition_id gpid = update->config.gpid;
    _state->update_configuration(update, nullptr, [this, gpid](){
        if (_started)
        {
            tasking::enqueue(LPC_LBM_RUN, this, std::bind(&meta_service::on_config_changed, this, gpid));
        }
    });
}

// local timers
void meta_service::on_load_balance_timer()
{
    if (!_started)
        return;

    if (_state->freezed())
        return;

    if (_failure_detector->is_primary())
    {
        _balancer->run();
    }
}

void meta_service::on_config_changed(global_partition_id gpid)
{
    if (_failure_detector->is_primary())
    {
        _balancer->run(gpid);
    }
}
<|endoftext|>


<commit_before>#pragma once
#ifndef BENCHMARK_HPP_778YQPEJ
#define BENCHMARK_HPP_778YQPEJ

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/current_function.hpp>
#include <vector>
#include <string>
#define BENCHMARK(list,exp) \
    { \
        benchmark::timer t(&list,#exp,__FILE__,__LINE__,BOOST_CURRENT_FUNCTION); \
        _Pragma("pomp inst begin(#exp,__LINE__)") \
        (exp); \
        _Pragma("pomp inst end(#exp,__LINE__)") \
    }

namespace benchmark
{
    struct event {
        const bool operator<(const event &other) const;
        friend std::ostream& operator<<(std::ostream &out, event &ev);

        std::string exp, file, function;
        boost::posix_time::time_duration time;
        unsigned int line, count;
    };

    class event_list
    {
    public:
        friend std::ostream& operator<<(std::ostream &out, event_list &el);
        event& max();
        boost::posix_time::time_duration average_time();
        void push_back(const event &ev);
        size_t size() const;
        const event front() const;

    private:
        typedef std::vector<event> actual_list_type;
        actual_list_type actual_list;
    };

    class timer
    {
    public:
        timer(event_list *list, const std::string exp, const std::string file, const unsigned int line, const std::string function);
        virtual ~timer();

    private:
        event_list *_list;
        const std::string _exp, _file;
        const unsigned int _line;
        const std::string _function;
        boost::posix_time::ptime *start, *end;
        std::ostringstream oss;
    };
}

#endif /* end of include guard: BENCHMARK_HPP_778YQPEJ */
<commit_msg>Concatenate exp and line<commit_after>#pragma once
#ifndef BENCHMARK_HPP_778YQPEJ
#define BENCHMARK_HPP_778YQPEJ

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/current_function.hpp>
#include <vector>
#include <string>
#define BENCHMARK(list,exp) \
    { \
        benchmark::timer t(&list,#exp,__FILE__,__LINE__,BOOST_CURRENT_FUNCTION); \
        _Pragma("pomp inst begin(#exp##_##__LINE__)") \
        (exp); \
        _Pragma("pomp inst end(#exp##_##__LINE__)") \
    }

namespace benchmark
{
    struct event {
        const bool operator<(const event &other) const;
        friend std::ostream& operator<<(std::ostream &out, event &ev);

        std::string exp, file, function;
        boost::posix_time::time_duration time;
        unsigned int line, count;
    };

    class event_list
    {
    public:
        friend std::ostream& operator<<(std::ostream &out, event_list &el);
        event& max();
        boost::posix_time::time_duration average_time();
        void push_back(const event &ev);
        size_t size() const;
        const event front() const;

    private:
        typedef std::vector<event> actual_list_type;
        actual_list_type actual_list;
    };

    class timer
    {
    public:
        timer(event_list *list, const std::string exp, const std::string file, const unsigned int line, const std::string function);
        virtual ~timer();

    private:
        event_list *_list;
        const std::string _exp, _file;
        const unsigned int _line;
        const std::string _function;
        boost::posix_time::ptime *start, *end;
        std::ostringstream oss;
    };
}

#endif /* end of include guard: BENCHMARK_HPP_778YQPEJ */
<|endoftext|>


<commit_before>#include "utils.hpp"
#include "graph_loaders.hpp"
#include <boost/graph/distributed/page_rank.hpp>
#include <boost/graph/small_world_generator.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/random/linear_congruential.hpp>

#ifndef __ALGORITHM_NAME__
#define __ALGORITHM_NAME__ "PageRank"
#endif

namespace Csv
{
    struct Node {
        Node() {}
        Node(const std::string& name) : name(name) {}
        std::string name;
        float pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & name & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef typename property_map<Graph, float Node::*>::type VertexFloatMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexFloatMap prm;

    public:
        Fixture(const char* graphfile) {
            g = new Graph();

            if (is_root()) {
                assert(filesystem::exists(graphfile));
                ifstream in(graphfile);
                sigsna::load_graph_from_csv(in, graph());
            }

            prm = get(&Node::pagerank, graph());
            synchronize(process_group(graph()));
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexFloatMap& pagerank_map() {
            return prm;
        }
    };
}

namespace SmallWorld
{
    struct Node {
        float pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef small_world_iterator<minstd_rand, Graph> SWGen;
        typedef typename property_map<Graph, float Node::*>::type VertexFloatMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexFloatMap prm;

    public:
        Fixture(const unsigned int nodes, const unsigned int nearest, const float prob) {
            boost::minstd_rand gen(1); // Generate the same graph
            g = new Graph(SWGen(gen, nodes, nearest, prob), SWGen(), nodes);
            prm = get(&Node::pagerank, graph());
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexFloatMap& pagerank_map() {
            return prm;
        }
    };

};

namespace ErdosRenyi
{
    struct Node {
        float pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef erdos_renyi_iterator<minstd_rand, Graph> ERGen;
        typedef typename property_map<Graph, float Node::*>::type VertexFloatMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexFloatMap prm;

    public:
        Fixture(const unsigned int nodes, const double prob) {
            boost::minstd_rand gen(1); // Generate the same graph
            g = new Graph(ERGen(gen, nodes, prob), ERGen(), nodes);
            prm = get(&Node::pagerank, graph());
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexFloatMap& pagerank_map() {
            return prm;
        }
    };

};

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, SmallWorld::Node> SmallWorldDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, SmallWorld::Node> SmallWorldBigraph;
DECLARE_TYPE_NAME(SmallWorldDigraph);
DECLARE_TYPE_NAME(SmallWorldBigraph);

typedef mpl::list<SmallWorldDigraph, SmallWorldBigraph> SmallWorldGraphTypes; // PageRank doesn't work with CSR graphs

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTest, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(28250, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTestMed, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(282500, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTestBig, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(653646, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, ErdosRenyi::Node> ErdosRenyiDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, ErdosRenyi::Node> ErdosRenyiBigraph;
DECLARE_TYPE_NAME(ErdosRenyiDigraph);
DECLARE_TYPE_NAME(ErdosRenyiBigraph);

typedef mpl::list<ErdosRenyiDigraph, ErdosRenyiBigraph> ErdosRenyiGraphTypes;

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTest, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(28250, 0.0005);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTestMed, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(282500, 0.00001);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTestBig, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(653646, 0.000001);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

// Enable named vertex support
namespace boost
{
    namespace graph
    {
        template<>
        struct internal_vertex_name<Csv::Node> {
            typedef multi_index::member<Csv::Node, std::string, &Csv::Node::name> type;
        };

        template<>
        struct internal_vertex_constructor<Csv::Node> {
            typedef vertex_from_name<Csv::Node> type;
        };
    }
}

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, Csv::Node> CsvDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, Csv::Node> CsvBigraph;
DECLARE_TYPE_NAME(CsvDigraph);
DECLARE_TYPE_NAME(CsvBigraph);

typedef mpl::list<CsvDigraph, CsvBigraph> CsvGraphTypes;

BOOST_AUTO_TEST_CASE_TEMPLATE(CsvScalabilityTest, G, CsvGraphTypes)
{
    benchmark::event_list events;
    Csv::Fixture<G> f("graph.csv");
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(CsvScalabilityTestBig, G, CsvGraphTypes)
{
    benchmark::event_list events;
    Csv::Fixture<G> f("subscriptions.csv");
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

int BOOST_TEST_CALL_DECL main(int argc, char *argv[])
{
#pragma pomp inst init
    mpi::environment env(argc, argv);
    return ::boost::unit_test::unit_test_main(&init_unit_test, argc, argv);
}
<commit_msg>Use doubles instead of floats for storing pagerank values<commit_after>#include "utils.hpp"
#include "graph_loaders.hpp"
#include <boost/graph/distributed/page_rank.hpp>
#include <boost/graph/small_world_generator.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/random/linear_congruential.hpp>

#ifndef __ALGORITHM_NAME__
#define __ALGORITHM_NAME__ "PageRank"
#endif

namespace Csv
{
    struct Node {
        Node() {}
        Node(const std::string& name) : name(name) {}
        std::string name;
        double pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & name & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef typename property_map<Graph, double Node::*>::type VertexDoubleMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexDoubleMap prm;

    public:
        Fixture(const char* graphfile) {
            g = new Graph();

            if (is_root()) {
                assert(filesystem::exists(graphfile));
                ifstream in(graphfile);
                sigsna::load_graph_from_csv(in, graph());
            }

            prm = get(&Node::pagerank, graph());
            synchronize(process_group(graph()));
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexDoubleMap& pagerank_map() {
            return prm;
        }
    };
}

namespace SmallWorld
{
    struct Node {
        double pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef small_world_iterator<minstd_rand, Graph> SWGen;
        typedef typename property_map<Graph, double Node::*>::type VertexDoubleMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexDoubleMap prm;

    public:
        Fixture(const unsigned int nodes, const unsigned int nearest, const float prob) {
            boost::minstd_rand gen(1); // Generate the same graph
            g = new Graph(SWGen(gen, nodes, nearest, prob), SWGen(), nodes);
            prm = get(&Node::pagerank, graph());
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexDoubleMap& pagerank_map() {
            return prm;
        }
    };

};

namespace ErdosRenyi
{
    struct Node {
        double pagerank;
        template<typename Archiver>
        void serialize(Archiver &ar, const unsigned int) {
            ar & pagerank;
        }
    };

    template <typename Graph>
    class Fixture
    {
        typedef erdos_renyi_iterator<minstd_rand, Graph> ERGen;
        typedef typename property_map<Graph, double Node::*>::type VertexDoubleMap;
        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;

        Graph *g;
        VertexDoubleMap prm;

    public:
        Fixture(const unsigned int nodes, const double prob) {
            boost::minstd_rand gen(1); // Generate the same graph
            g = new Graph(ERGen(gen, nodes, prob), ERGen(), nodes);
            prm = get(&Node::pagerank, graph());
        }

        virtual ~Fixture() {
            delete g;
        }

        bool is_root() {
            return (process_id(process_group(graph())) == 0);
        }

        Graph& graph() {
            return *g;
        }

        VertexDoubleMap& pagerank_map() {
            return prm;
        }
    };

};

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, SmallWorld::Node> SmallWorldDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, SmallWorld::Node> SmallWorldBigraph;
DECLARE_TYPE_NAME(SmallWorldDigraph);
DECLARE_TYPE_NAME(SmallWorldBigraph);

typedef mpl::list<SmallWorldDigraph, SmallWorldBigraph> SmallWorldGraphTypes; // PageRank doesn't work with CSR graphs

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTest, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(28250, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTestMed, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(282500, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(SmallWorldScalabilityTestBig, G, SmallWorldGraphTypes)
{
    benchmark::event_list events;
    SmallWorld::Fixture<G> f(653646, 10, 0.05);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, ErdosRenyi::Node> ErdosRenyiDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, ErdosRenyi::Node> ErdosRenyiBigraph;
DECLARE_TYPE_NAME(ErdosRenyiDigraph);
DECLARE_TYPE_NAME(ErdosRenyiBigraph);

typedef mpl::list<ErdosRenyiDigraph, ErdosRenyiBigraph> ErdosRenyiGraphTypes;

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTest, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(28250, 0.0005);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTestMed, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(282500, 0.00001);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(ErdosRenyiScalabilityTestBig, G, ErdosRenyiGraphTypes)
{
    benchmark::event_list events;
    ErdosRenyi::Fixture<G> f(653646, 0.000001);
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

// Enable named vertex support
namespace boost
{
    namespace graph
    {
        template<>
        struct internal_vertex_name<Csv::Node> {
            typedef multi_index::member<Csv::Node, std::string, &Csv::Node::name> type;
        };

        template<>
        struct internal_vertex_constructor<Csv::Node> {
            typedef vertex_from_name<Csv::Node> type;
        };
    }
}

typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, directedS, Csv::Node> CsvDigraph;
typedef adjacency_list <vecS, distributedS<mpi_process_group, vecS>, bidirectionalS, Csv::Node> CsvBigraph;
DECLARE_TYPE_NAME(CsvDigraph);
DECLARE_TYPE_NAME(CsvBigraph);

typedef mpl::list<CsvDigraph, CsvBigraph> CsvGraphTypes;

BOOST_AUTO_TEST_CASE_TEMPLATE(CsvScalabilityTest, G, CsvGraphTypes)
{
    benchmark::event_list events;
    Csv::Fixture<G> f("graph.csv");
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

BOOST_AUTO_TEST_CASE_TEMPLATE(CsvScalabilityTestBig, G, CsvGraphTypes)
{
    benchmark::event_list events;
    Csv::Fixture<G> f("subscriptions.csv");
    BENCHMARK(events, page_rank(f.graph(), f.pagerank_map()));
    write_average_log(__ALGORITHM_NAME__, GET_TYPE_NAME(f.graph()), total_vertices(f.graph()), total_edges(f.graph()), events, f.is_root());
}

int BOOST_TEST_CALL_DECL main(int argc, char *argv[])
{
#pragma pomp inst init
    mpi::environment env(argc, argv);
    return ::boost::unit_test::unit_test_main(&init_unit_test, argc, argv);
}
<|endoftext|>