text:
// Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <dp/DP.h>
#include <dp/Types.h>
#include <dp/Exception.h>
#include <dp/fx/mdl/inc/MDLTokenizer.h>
#include <dp/util/File.h>
#include <boost/algorithm/string.hpp>
#include <iostream>

namespace dp
{
  namespace fx
  {
    namespace mdl
    {
      static bool isHiddenMaterial( mi::base::Handle<mi::neuraylib::IAnnotation_block const> const& annotations );
      static std::string stripTrailingDigits( std::string const& name );
      static std::string typeName( mi::base::Handle<mi::neuraylib::IType const> const& type );

      static bool isHiddenMaterial( mi::base::Handle<mi::neuraylib::IAnnotation_block const> const& annotations )
      {
        if ( annotations )
        {
          for ( mi::Size i=0 ; i<annotations->get_size() ; i++ )
          {
            mi::base::Handle<mi::neuraylib::IAnnotation const> annotation = mi::base::make_handle(annotations->get_annotation(i));
            std::string annotationName = annotation->get_name();
            if ( annotationName == "::anno::hidden()" )
            {
              return( true );
            }
          }
        }
        return( false );
      }

      static std::string stripTrailingDigits( std::string const& name )
      {
        size_t pos = name.find_last_not_of( "0123456789" );
        if ( ( pos < name.length() - 1 ) && ( name[pos] == '_' ) )
        {
          return( name.substr( 0, pos ) );
        }
        return( name );
      }

      static std::string typeName( mi::base::Handle<mi::neuraylib::IType const> const& type )
      {
        mi::neuraylib::IType::Kind kind = type->get_kind();
        switch( kind )
        {
          case mi::neuraylib::IType::TK_ALIAS :
            return typeName(mi::base::make_handle(type.get_interface<mi::neuraylib::IType_alias const>()->get_aliased_type()));
          case mi::neuraylib::IType::TK_ARRAY:
            {
              mi::base::Handle<mi::neuraylib::IType_array const> array = type.get_interface<mi::neuraylib::IType_array const>();
              std::ostringstream oss;
              oss << typeName( mi::base::make_handle( array->get_element_type() ) );
              if ( array->is_immediate_sized() )
              {
                mi::Size size = array->get_size();
                oss << "[" << size << "]";
              }
              else
              {
                const char* deferredSize = array->get_deferred_size();
                DP_ASSERT(deferredSize != nullptr);
                // deferredSize can be an empty string. Normally it contains strings like "::df::L1559::N".
                // The actual size can be determined via the return type of the T[](...) function which constructs this array.
                oss << "[" << std::string( deferredSize ) << "]";
              }
              return( oss.str() );
            }
          case mi::neuraylib::IType::TK_BOOL :
            return( "Bool" );
          case mi::neuraylib::IType::TK_BSDF_MEASUREMENT :
            return( "BsdfMeasurement" );
          case mi::neuraylib::IType::TK_BSDF :
            return( "Bsdf" );
          case mi::neuraylib::IType::TK_EDF :
            return( "Edf" );
          case mi::neuraylib::IType::TK_ENUM :
            return type.get_interface<mi::neuraylib::IType_enum const>()->get_symbol();
          case mi::neuraylib::IType::TK_COLOR :
            return( "Color" );
          case mi::neuraylib::IType::TK_FLOAT :
            return( "Float" );
          case mi::neuraylib::IType::TK_INT :
            return( "Int" );
          case mi::neuraylib::IType::TK_LIGHT_PROFILE :
            return( "LightProfile" );
          case mi::neuraylib::IType::TK_MATRIX :
            {
              mi::base::Handle<mi::neuraylib::IType_matrix const> matrix = type.get_interface<mi::neuraylib::IType_matrix const>();
              DP_ASSERT(mi::base::make_handle(mi::base::make_handle(matrix->get_element_type())->get_element_type())->get_kind() == mi::neuraylib::IType::TK_FLOAT);
              std::ostringstream oss;
              oss << typeName(mi::base::make_handle(mi::base::make_handle(matrix->get_element_type())->get_element_type())) << "<" << matrix->get_size() << "," << matrix->get_size() << ">";
              return(oss.str());
            }
          case mi::neuraylib::IType::TK_STRING :
            return( "String" );
          case mi::neuraylib::IType::TK_STRUCT :
            return type.get_interface<mi::neuraylib::IType_struct const>()->get_symbol();
          case mi::neuraylib::IType::TK_TEXTURE :
            return( "Texture" );
          case mi::neuraylib::IType::TK_VDF :
            return( "Vdf" );
          case mi::neuraylib::IType::TK_VECTOR :
            {
              mi::base::Handle<mi::neuraylib::IType_vector const> vector = type.get_interface<mi::neuraylib::IType_vector const>();
              DP_ASSERT(mi::base::make_handle(vector->get_element_type())->get_kind() == mi::neuraylib::IType::TK_FLOAT);
              std::ostringstream oss;
              oss << typeName(mi::base::make_handle(vector->get_element_type())) << "<" << vector->get_size() << ">";
              return(oss.str());
            }
          default :
            DP_ASSERT( !"never passed this path!" );
            return( "" );
        }
      }

      class Logger : public mi::base::Interface_implement<mi::base::ILogger>
      {
        public:
          void message( mi::base::Message_severity level, const char* module_category, const char* message );
      };

      void Logger::message( mi::base::Message_severity level, const char* module_category, const char* message )
      {
        DP_ASSERT( strcmp( module_category, "MDL" ) == 0 );
        std::string m( message );

        std::string levelString;
        bool handled = false;
        switch ( level )
        {
          case mi::base::MESSAGE_SEVERITY_FATAL:
            levelString = "FATAL";
            break;
          case mi::base::MESSAGE_SEVERITY_ERROR:
            levelString = "ERROR";
            handled = boost::starts_with( m, "Could not locate default texture" )
                   || boost::starts_with( m, "No image plugin found to handle" );
            break;
          case mi::base::MESSAGE_SEVERITY_WARNING:
            levelString = "WARNING";
            handled = boost::contains( m, "extra parenthesis around function name" )
                   || boost::contains( m, "unused parameter" )
                   || boost::contains( m, "unused variable" )
                   || boost::ends_with( m, "material parameters of type 'bsdf' are forbidden" );
            break;
          case mi::base::MESSAGE_SEVERITY_INFO:
            levelString = "INFO";
            handled = boost::starts_with( m, "Found MDL module" )
                   || boost::starts_with( m, "Loading BSDF measurement" )
                   || boost::starts_with( m, "Loading lightprofile" );
            break;
          case mi::base::MESSAGE_SEVERITY_VERBOSE:
            levelString = "VERBOSE";
            break;
          case mi::base::MESSAGE_SEVERITY_DEBUG :
            levelString = "DEBUG";
            handled = boost::contains( m, "searching for" ) && boost::contains( m, "in path" ) && boost::contains( m, "not found" );
            break;
          default:
            levelString = "UNKNOWN";
            break;
        }
        if ( !handled )
        {
          std::cerr << "MDLTokenizer: " << levelString << ": " << message << std::endl;
          DP_ASSERT( !"MDLTokenizer Logger::message() unhandled!" );
        }
      }

      MDLTokenizer::MDLTokenizer()
        : m_filterDefaults( false )
      {
        m_mdlSDK = dp::util::DynamicLibrary::createFromFile( "libmdl_sdk.dll" );
        if ( !m_mdlSDK )
        {
          std::cerr << "MDL2XML: Can't load libmdl_sdk.dll" << std::endl;
          throw dp::FileNotFoundException( "libmdl_sdk.dll" );
        }

        typedef mi::neuraylib::INeuray* (INeuray_factory)( mi::neuraylib::IAllocator*, mi::Uint32 );
        INeuray_factory* factory = (INeuray_factory*)m_mdlSDK->getSymbol( "mi_neuray_factory" );
        DP_ASSERT( factory );

        m_neuray = factory( 0, MI_NEURAYLIB_API_VERSION );
        DP_ASSERT( m_neuray.is_valid_interface() );
        DP_VERIFY( m_neuray->start() == 0 );

        m_database = m_neuray->get_api_component<mi::neuraylib::IDatabase>();

        m_mdlCompiler = m_neuray->get_api_component<mi::neuraylib::IMdl_compiler>();
        m_mdlCompiler->set_logger( new Logger );

        mi::base::Handle<mi::neuraylib::IScope> scope(m_database->get_global_scope());
        m_transaction = mi::base::make_handle(scope->create_transaction());

        m_mdlFactory = m_neuray->get_api_component<mi::neuraylib::IMdl_factory>();
        m_mdlExpressionFactory = m_mdlFactory->create_expression_factory(m_transaction.get());
        m_mdlValueFactory = m_mdlFactory->create_value_factory(m_transaction.get());

        char * mdlSystemPath = getenv( "MDL_SYSTEM_PATH" );
        if ( mdlSystemPath )
        {
          DP_VERIFY( m_mdlCompiler->add_module_path( mdlSystemPath ) == 0 );
          DP_VERIFY(m_mdlCompiler->load_module(m_transaction.get(), "::nvidia::core_definitions") == 0);
          m_transaction->commit();
          m_transaction = mi::base::make_handle(scope->create_transaction());
        }
      }

      MDLTokenizer::~MDLTokenizer()
      {
        m_database.reset();
        m_mdlExpressionFactory.reset();
        m_mdlFactory.reset();
        m_mdlCompiler.reset();    // throw away before m_neuray is shut down
        m_neuray->shutdown();
      }

      bool MDLTokenizer::checkDefaultField(std::string const& fieldName, mi::base::Handle<mi::neuraylib::IExpression const> const& expression)
      {
        bool isDefault = (expression->get_kind() == mi::neuraylib::IExpression::EK_CONSTANT);
        if (isDefault)
        {
          if (fieldName == "ior")
          {
            isDefault = (m_mdlExpressionFactory->compare(expression.get(), m_mdlExpressionFactory->create_constant(m_mdlValueFactory->create_color(1.0f, 1.0f, 1.0f))) == 0);
          }
          else if (fieldName == "thin_walled")
          {
            isDefault = (m_mdlExpressionFactory->compare(expression.get(), m_mdlExpressionFactory->create_constant(m_mdlValueFactory->create_bool(false))) == 0);
          }
        }
        return(isDefault);
      }

      void MDLTokenizer::parseFile(std::string const& file, dp::util::FileFinder const& fileFinder)
      {
        DP_ASSERT( dp::util::fileExists( file ) );
        if (fileBegin(file))
        {
          std::vector<std::string> searchPaths = fileFinder.getSearchPaths();
          std::string packagePath = dp::util::getFilePath(file);
          if (!searchPaths.empty() && boost::starts_with(file, searchPaths.front()))
          {
            packagePath = searchPaths.front();
          }
          m_mdlCompiler->add_module_path(packagePath.c_str());

          for (auto const& s : searchPaths)
          {
            m_mdlCompiler->add_module_path(s.c_str()); // add_resource_path() is deprecated.
          }

          std::string moduleName = dp::util::getFilePath(file) + "\\" + dp::util::getFileStem(file);
          DP_ASSERT(boost::starts_with(moduleName, packagePath));
          boost::erase_first(moduleName, packagePath);
          boost::replace_all(moduleName, "\\", "::");
          boost::replace_all(moduleName, "/", "::");

          mi::Sint32 reason = m_mdlCompiler->load_module(m_transaction.get(), moduleName.c_str());
          if (reason < 0)
          {
            std::cout << "MDLTokenizer: failed to load module <" << file << ">" << std::endl;
            switch (reason)
            {
              // case 1: // Success (module exists already, loading from file was skipped).
              // case 0: // Success (module was actually loaded from file).
              case -1:
                std::cout << "The module name is invalid or a NULL pointer." << std::endl;
                break;
              case -2:
                std::cout << "Failed to find or to compile the module." << std::endl;
                break;
              case -3:
                std::cout << "The database name for an imported module is already in use but is not an MDL module," << std::endl;
                std::cout << "or the database name for a definition in this module is already in use." << std::endl;
                break;
              case -4:
                std::cout << "Initialization of an imported module failed." << std::endl;
                break;
              default:
                std::cout << "Unexpected return value " << reason << " from IMdl_compiler::load_module()." << std::endl;
                DP_ASSERT(!"Unexpected return value from IMdl_compiler::load_module()");
                break;
            }
          }
          else
          {
            moduleName = std::string("mdl") + moduleName;
            mi::base::Handle<const mi::neuraylib::IModule> module = mi::base::make_handle(m_transaction->access<mi::neuraylib::IModule>(moduleName.c_str()));
            DP_ASSERT(module.is_valid_interface());
            DP_ASSERT(module->get_filename());
            std::string fn = module->get_filename();

            mi::Size materialCount = module->get_material_count();
            DP_ASSERT(0 <= materialCount);
            for (mi::Size i = 0; i < materialCount; i++)
            {
              m_materialDefinition = mi::base::make_handle(m_transaction->access<mi::neuraylib::IMaterial_definition>(module->get_material(i)));
              DP_ASSERT(m_materialDefinition);

              if (!isHiddenMaterial(mi::base::make_handle(m_materialDefinition->get_annotations())))
              {
                mi::Sint32 result;
                mi::base::Handle<mi::neuraylib::IMaterial_instance> materialInstance = mi::base::make_handle(m_materialDefinition->create_material_instance(0, &result));
                if (result == 0)
                {
                  m_compiledMaterial = mi::base::make_handle(materialInstance->create_compiled_material(mi::neuraylib::IMaterial_instance::CLASS_COMPILATION, 1.0f, &result));
                  DP_ASSERT(result == 0);

                  tokenizeMaterial(module->get_material(i));
                  m_compiledMaterial.reset();
                }
                else
                {
                  std::cout << "failed to create a material instance for material <" << m_materialDefinition->get_mdl_name() << ">" << std::endl;
                  switch (result)
                  {
                    case -1:
                      std::cout << "An argument for a non-existing parameter was provided in arguments." << std::endl;
                      break;
                    case -2:
                      std::cout << "The type of an argument in arguments does not have the correct type, see get_parameter_types()." << std::endl;
                      break;
                    case -3:
                      std::cout << "A parameter that has no default was not provided with an argument value." << std::endl;
                      break;
                    case -4:
                      std::cout << "The definition can not be instantiated because it is not exported." << std::endl;
                      break;
                    case -5:
                      std::cout << "A parameter type is uniform, but the corresponding argument has a varying return type." << std::endl;
                      break;
                    case -6:
                      std::cout << "An argument expression is not a constant nor a call." << std::endl;
                      break;
                    default:
                      std::cout << "ERROR: Unexpected error result from create_material_instance()" << std::endl;
                      break;
                  }
                }
              }
              m_materialDefinition.reset();
            }
          }

          for (auto const& s : searchPaths)
          {
            m_mdlCompiler->remove_resource_path(s.c_str());
          }
          m_mdlCompiler->remove_module_path(packagePath.c_str());

          fileEnd();
        }
      }

      void MDLTokenizer::setFilterDefaults(bool filter)
      {
        m_filterDefaults = filter;
      }

      void MDLTokenizer::triggerTokenizeFunctionReturnType(std::string functionName)
      {
        if ( boost::starts_with( functionName, "mdl::base" ) )
        {
          mi::base::Handle<const mi::neuraylib::IModule> module = mi::base::make_handle(m_transaction->access<mi::neuraylib::IModule>("mdl::base"));
          mi::base::Handle<const mi::IArray> overloads = mi::base::make_handle(module->get_function_overloads(functionName.c_str()));
          DP_ASSERT(overloads->get_length() == 1);
          mi::base::Handle<const mi::IString> mdlFunctionName = mi::base::make_handle(overloads->get_element<mi::IString>(static_cast<mi::Uint32>(0)));
          mi::base::Handle<const mi::neuraylib::IFunction_definition> functionDefinition = mi::base::make_handle(m_transaction->access<mi::neuraylib::IFunction_definition>(mdlFunctionName->get_c_str()));
          tokenizeType(mi::base::make_handle(functionDefinition->get_return_type()));
        }
      }

      void MDLTokenizer::tokenizeArgument(mi::Size idx, std::string const& name, mi::base::Handle<mi::neuraylib::IExpression const> const& argumentExpression, mi::base::Handle<mi::neuraylib::IExpression const> const& defaultExpression)
      {
        if (!(m_filterDefaults && defaultExpression && (m_mdlExpressionFactory->compare(argumentExpression.get(), defaultExpression.get()) == 0)))
        {
          if (argumentBegin(dp::checked_cast<unsigned int>(idx), typeName(mi::base::make_handle(argumentExpression->get_type())), name))
          {
            tokenizeExpression(argumentExpression);
            argumentEnd();
          }
        }
      }

      void MDLTokenizer::tokenizeArray(mi::base::Handle<mi::neuraylib::IValue_array const> const& value)
      {
        mi::base::Handle<mi::neuraylib::IType const> type = mi::base::make_handle(value->get_type());
        tokenizeType(type);

        if (arrayBegin(typeName(type), value->get_size()))
        {
          for (mi::Size i = 0; i < value->get_size(); i++)
          {
            tokenizeValue(mi::base::make_handle(value->get_value(i)));
          }
          arrayEnd();
        }
      }

      void MDLTokenizer::tokenizeBSDFMeasurement(mi::base::Handle<mi::neuraylib::IValue_bsdf_measurement const> const& value)
      {
        if ( value )
        {
          DP_ASSERT( value->get_value() );
          std::string fileName = value->get_value();
          DP_ASSERT( boost::starts_with( fileName, "MI_default_bsdf_measurement_" ) );
          boost::erase_head( fileName, static_cast<int>( strlen( "MI_default_bsdf_measurement_" ) ) );
          valueBsdfMeasurement( fileName );
        }
        else
        {
          defaultRef( "BsdfMeasurement" );
        }
      }

      void MDLTokenizer::tokenizeColor(mi::base::Handle<mi::neuraylib::IValue_color const> const& value)
      {
        DP_ASSERT( value->get_size() == 3 );
        dp::math::Vec3f colorValue;
        for ( mi::Size i=0 ; i<3 ; i++ )
        {
          colorValue[i] = mi::base::make_handle(value->get_value(i))->get_value();
        }
        valueColor( colorValue );
      }

      void MDLTokenizer::tokenizeDirectCall(mi::base::Handle<mi::neuraylib::IExpression_direct_call const> const& call)
      {
        // special handling for functions containing the substring "_legacy" -> remove that part
        std::string callDefinition = call->get_definition();
        size_t pos = callDefinition.find("_legacy");
        if (pos != std::string::npos)
        {
          callDefinition.erase(pos, strlen("_legacy"));
        }

        mi::base::Handle<mi::neuraylib::IType const> type = mi::base::make_handle(call->get_type());
        tokenizeType(type);
        if (callBegin(typeName(type), callDefinition))
        {
          mi::base::Handle<mi::neuraylib::IFunction_definition const> functionDefinition = mi::base::make_handle(m_transaction->access<mi::neuraylib::IFunction_definition>(callDefinition.c_str()));
          mi::base::Handle<mi::neuraylib::IExpression_list const> defaults = mi::base::make_handle(functionDefinition->get_defaults());

          mi::base::Handle<mi::neuraylib::IExpression_list const> arguments = mi::base::make_handle(call->get_arguments());
          for (mi::Size i = 0; i<arguments->get_size(); i++)
          {
            tokenizeArgument(i, arguments->get_name(i), mi::base::make_handle(arguments->get_expression(i)), mi::base::make_handle(defaults->get_expression(i)));
          }
          callEnd();
        }
      }

      void MDLTokenizer::tokenizeEnum( mi::base::Handle<mi::neuraylib::IValue_enum const> const& value )
      {
        mi::base::Handle<mi::neuraylib::IType_enum const> type = mi::base::make_handle(value->get_type());
        tokenizeEnumType(type);
        valueEnum( type->get_symbol(), value->get_value(), type->get_value_name( value->get_index() ) );
      }

      void MDLTokenizer::tokenizeEnumType( mi::base::Handle<mi::neuraylib::IType_enum const> const& type )
      {
        if (enumTypeBegin(type->get_symbol(), type->get_size()))
        {
          for ( mi::Size i=0 ; i<type->get_size() ; i++ )
          {
            enumTypeValue( type->get_value_name( i ), type->get_value_code( i ) );
          }
          enumTypeEnd();
        }
      }

      void MDLTokenizer::tokenizeExpression( mi::base::Handle<mi::neuraylib::IExpression const> const& expression )
      {
        switch( expression->get_kind() )
        {
          case mi::neuraylib::IExpression::EK_CALL :
            DP_ASSERT( !"never passed this path!" );
            break;
          case mi::neuraylib::IExpression::EK_CONSTANT :
            tokenizeValue(mi::base::make_handle(expression.get_interface<mi::neuraylib::IExpression_constant const>()->get_value()));
            break;
          case mi::neuraylib::IExpression::EK_DIRECT_CALL :
            tokenizeDirectCall(expression.get_interface<mi::neuraylib::IExpression_direct_call const>());
            break;
          case mi::neuraylib::IExpression::EK_PARAMETER :
            tokenizeParameterExpression(expression.get_interface<mi::neuraylib::IExpression_parameter const>());
            break;
          case mi::neuraylib::IExpression::EK_TEMPORARY :
            referenceTemporary(dp::checked_cast<unsigned int>(expression.get_interface<mi::neuraylib::IExpression_temporary const>()->get_index()));
            break;
          default :
            DP_ASSERT( false );
            break;
        }
      }

      void MDLTokenizer::tokenizeField( std::string const& fieldName )
      {
        mi::base::Handle<mi::neuraylib::IExpression const> expression = mi::base::make_handle(m_compiledMaterial->get_field(fieldName.c_str()));
        if (!(m_filterDefaults && checkDefaultField(fieldName, expression)))
        {
          if ( fieldBegin( fieldName ) )
          {
            tokenizeExpression( expression );
            fieldEnd();
          }
        }
      }

      void MDLTokenizer::tokenizeLightProfile(mi::base::Handle<mi::neuraylib::IValue_light_profile const> const& value)
      {
        if ( value )
        {
          DP_ASSERT( value->get_value() );
          std::string fileName = value->get_value();
          DP_ASSERT( boost::starts_with( fileName, "MI_default_lightprofile_" ) );
          boost::erase_head( fileName, static_cast<int>( strlen( "MI_default_lightprofile_" ) ) );
          valueLightProfile( fileName );
        }
        else
        {
          defaultRef( "LightProfile" );
        }
      }

      void MDLTokenizer::tokenizeMaterial( std::string const& name )
      {
        mi::base::Uuid hash = m_compiledMaterial->get_hash();

        if (materialBegin(name, dp::math::Vec4ui(hash.m_id1, hash.m_id2, hash.m_id3, hash.m_id4)))
        {
          mi::Size parameterCount = m_compiledMaterial->get_parameter_count();
          for (mi::Size i = 0; i < parameterCount; i++)
          {
            tokenizeParameter(i);
          }

          mi::Size temporaryCount = m_compiledMaterial->get_temporary_count();
          for (mi::Uint32 ti = 0; ti < temporaryCount; ti++)
          {
            tokenizeTemporary(ti);
          }

          tokenizeField("thin_walled");
          tokenizeField("surface");
          tokenizeField("backface");
          tokenizeField("ior");
          tokenizeField("volume");
          tokenizeField("geometry");

          materialEnd();
        }
      }

      void MDLTokenizer::tokenizeMatrix( mi::base::Handle<mi::neuraylib::IValue_matrix const> const& value )
      {
        if (matrixBegin(typeName(mi::base::make_handle(value->get_type()))))
        {
          for (mi::Size i = 0; i < value->get_size(); i++)
          {
            tokenizeVector(mi::base::make_handle(value->get_value(i)));
          }
          matrixEnd();
        }
      }

      void MDLTokenizer::tokenizeParameter( mi::Size parameterIndex )
      {
        char const* parameterName = m_compiledMaterial->get_parameter_name( parameterIndex );
        if (parameterBegin(dp::checked_cast<unsigned int>(parameterIndex), parameterName ? parameterName : ""))
        {
          tokenizeValue(mi::base::make_handle(m_compiledMaterial->get_argument(parameterIndex)));

          // only named parameters need annotations!!
          if (parameterName)
          {
            mi::base::Handle<mi::neuraylib::IAnnotation_list const> annotations = mi::base::make_handle(m_materialDefinition->get_parameter_annotations());
            DP_ASSERT(annotations);

            mi::base::Handle<mi::neuraylib::IAnnotation_block const> parameterAnnotations = mi::base::make_handle(annotations->get_annotation_block(parameterName));
            if (parameterAnnotations)
            {
              for (mi::Size i = 0; i < parameterAnnotations->get_size(); i++)
              {
                mi::base::Handle<mi::neuraylib::IAnnotation const> annotation = mi::base::make_handle(parameterAnnotations->get_annotation(i));
                std::string annotationName = annotation->get_name();
                if (annotationBegin(annotationName))
                {
                  mi::base::Handle<mi::neuraylib::IExpression_list const> annotationArguments = mi::base::make_handle(annotation->get_arguments());
                  for (mi::Size j = 0; j < annotationArguments->get_size(); j++)
                  {
                    tokenizeExpression(mi::base::make_handle(annotationArguments->get_expression(j)));
                  }
                  annotationEnd();
                }
              }
            }
          }

          parameterEnd();
        }
      }

      void MDLTokenizer::tokenizeParameterExpression( mi::base::Handle<mi::neuraylib::IExpression_parameter const> const& expression )
      {
        tokenizeType(mi::base::make_handle(expression->get_type()));
        referenceParameter(dp::checked_cast<unsigned int>(expression->get_index()));
      }

      void MDLTokenizer::tokenizeStructure( mi::base::Handle<mi::neuraylib::IValue_struct const> const& structValue )
      {
        mi::base::Handle<mi::neuraylib::IType_struct const> type = mi::base::make_handle(structValue->get_type());
        tokenizeStructureType(type);

        if (structureBegin(type->get_symbol()))
        {
          for (mi::Size i = 0; i < structValue->get_size(); i++)
          {
            tokenizeValue(mi::base::make_handle(structValue->get_value(i)));
          }
          structureEnd();
        }
      }

      void MDLTokenizer::tokenizeStructureType( mi::base::Handle<mi::neuraylib::IType_struct const> const& type )
      {
        if (structureTypeBegin( type->get_symbol() ))
        {
          for ( mi::Size i=0 ; i<type->get_size() ; i++ )
          {
            mi::base::Handle<mi::neuraylib::IType const> componentType = mi::base::make_handle(type->get_component_type(i));
            tokenizeType(componentType);
            structureTypeElement( typeName( componentType ), type->get_field_name( i ) );
          }
          structureTypeEnd();
        }
      }

      void MDLTokenizer::tokenizeTemporary( mi::Size temporaryIndex )
      {
        if (temporaryBegin(dp::checked_cast<unsigned int>(temporaryIndex)))
        {
          tokenizeExpression(mi::base::make_handle(m_compiledMaterial->get_temporary(temporaryIndex)));
          temporaryEnd();
        }
      }

      void MDLTokenizer::tokenizeTexture( mi::base::Handle<mi::neuraylib::IValue_texture const> const& value )
      {
        if ( value )
        {
          DP_ASSERT( value->get_value() );
          mi::base::Handle<mi::neuraylib::ITexture const> texture = mi::base::make_handle(m_transaction->access<mi::neuraylib::ITexture>(value->get_value()));
          std::string fileName = texture->get_image();
          DP_ASSERT( boost::starts_with( fileName, "MI_default_image_" ) );
          boost::erase_head( fileName, static_cast<int>( strlen( "MI_default_image_" ) ) );
          mi::Float32 gamma = texture->get_effective_gamma();
          DP_ASSERT( ( gamma == 2.2f ) || ( gamma == 1.0f ) || ( gamma == 0.0f ) );   // I know, operator==() on floating points is unsafe! But here it works!
          GammaMode gammaMode = ( gamma == 2.2f ) ? GammaMode::SRGB : ( gamma == 1.0f ) ? GammaMode::LINEAR : GammaMode::DEFAULT;
          valueTexture( fileName, gammaMode );
        }
        else
        {
          defaultRef( "Texture" );
        }
      }

      void MDLTokenizer::tokenizeType( mi::base::Handle<mi::neuraylib::IType const> const& type )
      {
        mi::neuraylib::IType::Kind kind = type->get_kind();
        switch( kind )
        {
          case mi::neuraylib::IType::TK_ALIAS :
            tokenizeType(mi::base::make_handle(type.get_interface<mi::neuraylib::IType_alias const>()->get_aliased_type()));
            break;
          case mi::neuraylib::IType::TK_ARRAY :
            tokenizeType(mi::base::make_handle(type.get_interface<mi::neuraylib::IType_array const>()->get_element_type()));
            break;
          case mi::neuraylib::IType::TK_ENUM :
            tokenizeEnumType(type.get_interface<mi::neuraylib::IType_enum const>());
            break;
          case mi::neuraylib::IType::TK_MATRIX :
            tokenizeType(mi::base::make_handle(type.get_interface<mi::neuraylib::IType_matrix const>()->get_element_type()));
            break;
          case mi::neuraylib::IType::TK_STRUCT :
            tokenizeStructureType(type.get_interface<mi::neuraylib::IType_struct const>());
            break;
          case mi::neuraylib::IType::TK_VECTOR :
            tokenizeType(mi::base::make_handle(type.get_interface<mi::neuraylib::IType_vector const>()->get_element_type()));
            break;
          case mi::neuraylib::IType::TK_BOOL :   // those don't need explicit parsing!
          case mi::neuraylib::IType::TK_BSDF :
          case mi::neuraylib::IType::TK_BSDF_MEASUREMENT :
          case mi::neuraylib::IType::TK_COLOR :
          case mi::neuraylib::IType::TK_EDF :
          case mi::neuraylib::IType::TK_FLOAT :
          case mi::neuraylib::IType::TK_INT :
          case mi::neuraylib::IType::TK_LIGHT_PROFILE :
          case mi::neuraylib::IType::TK_TEXTURE :
          case mi::neuraylib::IType::TK_VDF :
            break;
          default :
            DP_ASSERT( !"never passed this path!" );
            break;
        }
      }

      void MDLTokenizer::tokenizeValue( mi::base::Handle<mi::neuraylib::IValue const> const& value )
      {
        mi::base::Handle<mi::neuraylib::IType const> type = mi::base::make_handle(value->get_type());

        mi::neuraylib::IValue::Kind kind = value->get_kind();
        switch( kind )
        {
          case mi::neuraylib::IValue::VK_ARRAY :
            tokenizeArray(value.get_interface<mi::neuraylib::IValue_array const>());
            break;
          case mi::neuraylib::IValue::VK_BOOL :
            valueBool(value.get_interface<mi::neuraylib::IValue_bool const>()->get_value());
            break;
          case mi::neuraylib::IValue::VK_BSDF_MEASUREMENT :
            tokenizeBSDFMeasurement(value.get_interface<mi::neuraylib::IValue_bsdf_measurement const>());
            break;
          case mi::neuraylib::IValue::VK_COLOR :
            tokenizeColor(value.get_interface<mi::neuraylib::IValue_color const>());
            break;
          case mi::neuraylib::IValue::VK_ENUM :
            tokenizeEnum(value.get_interface<mi::neuraylib::IValue_enum const>());
            break;
          case mi::neuraylib::IValue::VK_FLOAT :
            valueFloat(value.get_interface<mi::neuraylib::IValue_float const>()->get_value());
            break;
          case mi::neuraylib::IValue::VK_INT :
            valueInt(value.get_interface<mi::neuraylib::IValue_int const>()->get_value());
            break;
          case mi::neuraylib::IValue::VK_INVALID_REF :
            switch( type->get_kind() )
            {
              case mi::neuraylib::IType::TK_BSDF :
                defaultRef( "Bsdf" );
                break;
              case mi::neuraylib::IType::TK_EDF :
                defaultRef( "Edf" );
                break;
              case mi::neuraylib::IType::TK_LIGHT_PROFILE :
                defaultRef( "LightProfile" );
                break;
              case mi::neuraylib::IType::TK_TEXTURE :
                defaultRef( "Texture" );
                break;
              case mi::neuraylib::IType::TK_VDF :
                defaultRef( "Vdf" );
                break;
              default :
                DP_ASSERT( false );
                break;
            }
            break;
          case mi::neuraylib::IValue::VK_LIGHT_PROFILE :
            tokenizeLightProfile(value.get_interface<mi::neuraylib::IValue_light_profile const>());
            break;
          case mi::neuraylib::IValue::VK_MATRIX :
            tokenizeMatrix(value.get_interface<mi::neuraylib::IValue_matrix const>());
            break;
          case mi::neuraylib::IValue::VK_STRING :
            valueString(value.get_interface<mi::neuraylib::IValue_string const>()->get_value());
            break;
          case mi::neuraylib::IValue::VK_STRUCT :
            tokenizeStructure(value.get_interface<mi::neuraylib::IValue_struct const>());
            break;
          case mi::neuraylib::IValue::VK_TEXTURE :
            tokenizeTexture(value.get_interface<mi::neuraylib::IValue_texture const>());
            break;
          case mi::neuraylib::IValue::VK_VECTOR :
            tokenizeVector(value.get_interface<mi::neuraylib::IValue_vector const>());
            break;
          default :
            DP_ASSERT( !"never passed this path!" );
            break;
        }
      }

      void MDLTokenizer::tokenizeVector( mi::base::Handle<mi::neuraylib::IValue_vector const> const& value )
      {
        if (vectorBegin(typeName(mi::base::make_handle(value->get_type()))))
        {
          for (mi::Size i = 0; i < value->get_size(); i++)
          {
            tokenizeValue(mi::base::make_handle(value->get_value(i)));
          }
          vectorEnd();
        }
      }

    } // mdl
  } // fx
} // dp

max_stars_repo_name: siddharthuniv/nv-propipeline

max_issues_repo_name: siddharthuniv/nv-propipeline

max_forks_repo_name: siddharthuniv/nv-propipeline


text:
// Copyright (c) 2008 Michael B. Edwin Rickert
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt )
//
// $LastChangedBy$ - $LastChangedDate$

#ifndef IG_INDUSTRY_LANGUAGES_RUBY_DETAIL_BUILTINS
#define IG_INDUSTRY_LANGUAGES_RUBY_DETAIL_BUILTINS

#include <industry/languages/ruby/detail/wrap_retarded_ruby.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/range.hpp>
#include <map>
#include <string>
#include <cassert>

namespace industry { namespace languages { namespace ruby { namespace detail {
	template < typename T > struct class_registry;
	template < typename T > struct ruby_value;

/*-------------------------------------------------------------------------------------*/
#define BUILTIN( cpp_t, rubytypes, cpp2ruby, ruby2cpp )                                 \
template<> struct ruby_value<cpp_t> {                                                   \
	static VALUE to  ( cpp_t value ) { return cpp2ruby; }                               \
	static cpp_t from( VALUE value ) { return ruby2cpp; }                               \
	static bool is_a( VALUE value ) {                                                   \
		static const VALUE klasses[] = { BOOST_PP_SEQ_ENUM(rubytypes) };                \
		const VALUE klass = CLASS_OF(value);                                            \
		for ( const VALUE* i = boost::begin(klasses); i != boost::end(klasses); ++i ) { \
			if (klass == *i) return true;                                               \
		}                                                                               \
		return false;                                                                   \
	}                                                                                \
};                                                                                \
template<> struct ruby_value<cpp_t const&> : ruby_value<cpp_t> {                        \
	static VALUE to  ( cpp_t const& value ) { return cpp2ruby; }                        \
	static cpp_t from( VALUE        value ) { return ruby2cpp; }                        \
};                                                                                \
template<> struct ruby_value<cpp_t const>:ruby_value<cpp_t> {};                         \
template<> struct ruby_value<cpp_t&>:ruby_value<cpp_t const&>{};                        \
template<> struct class_registry<cpp_t> {                                               \
	static VALUE get() { assert(!"Should never happen!!!"); return Qnil; }              \
};                                                                                \
template<> struct class_registry<cpp_t const >:class_registry<cpp_t> {};                \
template<> struct class_registry<cpp_t const&>:class_registry<cpp_t> {};                \
template<> struct class_registry<cpp_t&      >:class_registry<cpp_t> {};                \
/*-------------------------------------------------------------------------------------*/

	//// OWNERSHIP:  Gives a copy to the other language ///////////////////////////////////////////////////////////
#define BOOLTYPES (rb_cTrueClass)(rb_cFalseClass)
#define INTTYPES  (rb_cFixnum)(rb_cBignum)
	BUILTIN( bool          , BOOLTYPES    , value?Qtrue:Qfalse  , RTEST(value)                                );
	BUILTIN( signed   char , INTTYPES     , CHR2FIX(value)      , NUM2CHR(value)                              );
	BUILTIN( signed   short, INTTYPES     , INT2NUM(value)      , static_cast<short>(NUM2INT(value))          );
	BUILTIN( signed   int  , INTTYPES     , INT2NUM(value)      , NUM2INT(value)                              );
	BUILTIN( signed   long , INTTYPES     , LONG2NUM(value)     , NUM2LONG(value)                             );
	BUILTIN( unsigned char , INTTYPES     , UINT2NUM(value)     , static_cast<unsigned char >(NUM2CHR(value)) );
	BUILTIN( unsigned short, INTTYPES     , UINT2NUM(value)     , static_cast<unsigned short>(NUM2INT(value)) );
	BUILTIN( unsigned int  , INTTYPES     , UINT2NUM(value)     , NUM2INT(value)                              );
	BUILTIN( unsigned long , INTTYPES     , ULONG2NUM(value)    , NUM2LONG(value)                             );
	BUILTIN( float         , (rb_cFloat)  , rb_float_new(value) , static_cast<float>(NUM2DBL(value))          );
	BUILTIN( double        , (rb_cFloat)  , rb_float_new(value) , NUM2DBL(value)                              );
	BUILTIN( char*         , (rb_cString) , rb_str_new2(value)  , STR2CSTR(value)                             );
	BUILTIN( const char*   , (rb_cString) , rb_str_new2(value)  , STR2CSTR(value)                             );
	BUILTIN( std::string   , (rb_cString) , rb_str_new(value.empty()?"":value.c_str(),value.size()), STR2CSTR(value) );
#undef INTTYPES
#undef BOOLTYPES
#undef BUILTIN

}}}}

#endif //ndef IG_INDUSTRY_LANGUAGES_RUBY_DETAIL_BUILTINS

ext: hpp

max_stars_repo_name: MaulingMonkey/libindustry

max_issues_repo_name: MaulingMonkey/libindustry

max_forks_repo_name: MaulingMonkey/libindustry


text:
// Copyright 2016 Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <gtest/gtest.h>
#include <boost/network/protocol/http/client/request.hpp>

using client_request = boost::network::http::client_request;

TEST(http_client_request, construct_from_uri) {
  ASSERT_NO_THROW(client_request("http://cpp-netlib.org/"));
}

TEST(http_client_request, DISABLED_construct_from_invalid_uri) {
  ASSERT_THROW(client_request("I am not a valid URI"), std::exception);
}

ext: cpp

max_stars_repo_name: yhager/cpp-netlib

max_issues_repo_name: yhager/cpp-netlib

max_forks_repo_name: yhager/cpp-netlib


text:
//==============================================================================
//          Copyright 2014    Jean-Thierry Lapreste
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SWAR_FUNCTIONS_CUMMAX_HPP_INCLUDED
#define BOOST_SIMD_SWAR_FUNCTIONS_CUMMAX_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
#include <boost/simd/operator/functions/plus.hpp>
#include <boost/simd/include/functions/scalar/max.hpp>
#include <boost/simd/constant/constants/minf.hpp>

namespace boost { namespace simd { namespace tag
  {
    /*!
      @brief cummax generic tag

      Represents the cummax function in generic contexts.

      @par Models:
      Hierarchy
    **/
    struct cummax_ : ext::cumulative_<cummax_, tag::max_, tag::Minf>
    {
      /// @brief Parent hierarchy
      typedef ext::cumulative_<cummax_, tag::max_, tag::Minf> parent;
      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_cummax_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };
  }
  namespace ext
  {
    template<class Site, class... Ts>
    BOOST_FORCEINLINE generic_dispatcher<tag::cummax_, Site> dispatching_cummax_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
    {
      return generic_dispatcher<tag::cummax_, Site>();
    }
    template<class... Args>
    struct impl_cummax_;
  }
  /*!
    @brief compute the cumulate maximum of the vector elements

    @par Semantic:

    For every parameter of type T0

    @code
    T0 r = cummax(a0);
    @endcode

    is similar to:

    @code
    T r =x;
    for(int i=0;i < T::static_size; ++i)
      r[i] += max(r[i-1], r[i]);
    @endcode

    @param a0

    @return a value of the same type as the second parameter
  **/
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cummax_, cummax, 1)
  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::cummax_, cummax, 2)
} }

#endif


text:
#include <boost/test/unit_test.hpp>

#include <xercesc/parsers/XercesDOMParser.hpp>

#include "xmlutils.hpp"

#include "lineside/xml/xercesguard.hpp"
#include "lineside/xml/utilities.hpp"

#include "lineside/xml/hardwaremanagerdatareader.hpp"

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

const std::string hardwaremanagerFragment = "hardwaremanager-fragment.xml";

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

BOOST_AUTO_TEST_SUITE( xml )

BOOST_AUTO_TEST_SUITE( HardwareManagerDataReader )

BOOST_AUTO_TEST_CASE( SmokeReader )
{
  Lineside::xml::XercesGuard xg;
  auto parser = GetParser();

  auto rootElement = GetRootElementOfFile(parser, hardwaremanagerFragment);
  BOOST_REQUIRE(rootElement);

  Lineside::xml::HardwareManagerDataReader reader;
  BOOST_REQUIRE( reader.HasHardwareManager(rootElement) );

  auto hardwaremanagerElement = reader.GetHardwareManagerElement(rootElement);

  auto result = reader.Read(hardwaremanagerElement);

  BOOST_REQUIRE_EQUAL( result.i2cDevices.size(), 1 );
  auto dev0 = result.i2cDevices.at(0);
  BOOST_CHECK_EQUAL( dev0.kind, "pca9685" );
  BOOST_CHECK_EQUAL( dev0.bus, 0 );
  BOOST_CHECK_EQUAL( dev0.address, 0xFF );
  BOOST_CHECK_EQUAL( dev0.name, "pwm0" );
  BOOST_REQUIRE_EQUAL( dev0.settings.size(), 1 );
  BOOST_CHECK_EQUAL( dev0.settings.at("key9685"), "val9685" );

  BOOST_REQUIRE_EQUAL( result.settings.size(), 1 );
  BOOST_CHECK_EQUAL( result.settings.at("some"), "thing" );
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: freesurfer-rge/linesidecabinet

max_issues_repo_name: freesurfer-rge/linesidecabinet

max_forks_repo_name: freesurfer-rge/linesidecabinet


text:
/*!
  @file
  @author Shin'ichiro Nakaoka
*/

#include "RobotAccessBar.h"
#include "RobotAccessItem.h"
#include <cnoid/RootItem>
#include <cnoid/ItemTreeView>
#include <cnoid/MessageView>
#include <boost/bind.hpp>
#include "gettext.h"

using namespace boost;
using namespace cnoid;

namespace cnoid {

class RobotAccessBarImpl
{
public:
    ToolButton* syncToggle;

    RobotAccessBarImpl(RobotAccessBar* self);
    void connectToRobots();
    void disconnectFromRobots();
    void turnOnServos();
    void turnOffServos();
    void onSendPoseButtonClicked();
    void onServoButtonToggled(bool on);
};
}

namespace {

void forEachCheckedRobotAccessItems
(boost::function<void(RobotAccessItem* item)> func, const char* noTargetMessage)
{
    ItemList<RobotAccessItem> items =
        ItemTreeView::instance()->checkedItems<RobotAccessItem>();
    if(items.empty()){
        MessageView::instance()->putln(noTargetMessage);
    } else {
        for(int i=0; i < items.size(); ++i){
            func(items[i].get());
        }
    }
}
}

RobotAccessBar::RobotAccessBar()
    : ToolBar(N_("RobotAccessBar"))
{
    impl = new RobotAccessBarImpl(this);
}

RobotAccessBar::~RobotAccessBar()
{

}

RobotAccessBarImpl::RobotAccessBarImpl(RobotAccessBar* self)
{
    self->addButton(_("C"), _("Connect to robots"))
        ->sigClicked().connect(boost::bind(&RobotAccessBarImpl::connectToRobots, this));

    self->addButton(_("D"), _("Disconnect from robots"))
        ->sigClicked().connect(boost::bind(&RobotAccessBarImpl::disconnectFromRobots, this));

    self->addButton(QIcon(":/RobotAccess/icons/servo-on.png"), _("Turn on servos"))
        ->sigClicked().connect(boost::bind(&RobotAccessBarImpl::turnOnServos, this));

    self->addButton(_("OFF"), _("Turn off servos"))
        ->sigClicked().connect(boost::bind(&RobotAccessBarImpl::turnOffServos, this));

    self->addButton(QIcon(":/RobotAccess/icons/sendpose.png"),
                    _("Send the current pose of virtual robots to actual robots"))
        ->sigClicked().connect(boost::bind(&RobotAccessBarImpl::onSendPoseButtonClicked, this));

    syncToggle = self->addToggleButton(QIcon(":/RobotAccess/icons/syncpose.png"),
                                       _("Synchronize the pose of actual robots pose with virtual robots"));
}

void RobotAccessBarImpl::connectToRobots()
{
    forEachCheckedRobotAccessItems(
        boost::bind(&RobotAccessItem::connectToRobot, _1),
        _("There are no checked items to connect to robots"));
}

void RobotAccessBarImpl::disconnectFromRobots()
{
    forEachCheckedRobotAccessItems(
        boost::bind(&RobotAccessItem::disconnectFromRobot, _1),
        _("There are no checked items to disconnect from robots"));
}

void RobotAccessBarImpl::turnOnServos()
{
    forEachCheckedRobotAccessItems(
        boost::bind(&RobotAccessItem::activateServos, _1, true),
        _("There are no checked items to activate servos"));
}

void RobotAccessBarImpl::turnOffServos()
{
    forEachCheckedRobotAccessItems(
        boost::bind(&RobotAccessItem::activateServos, _1, false),
        _("There are no checked items to deactivate servos"));
}

void RobotAccessBarImpl::onSendPoseButtonClicked()
{

}

void RobotAccessBarImpl::onServoButtonToggled(bool on)
{

}

max_stars_repo_name: snozawa/choreonoid

max_issues_repo_name: snozawa/choreonoid

max_forks_repo_name: snozawa/choreonoid


text:
/*
 * task_scheduler.cpp
 *
 *  Created on: Dec 30, 2015
 *      Author: Karol Dzitkowski
 */

#include "core/task/task_scheduler.hpp"
#include <boost/bind.hpp>

namespace ddj
{

TaskScheduler::TaskScheduler(int threadNumber)
	: _threadNumber(threadNumber)
{
	// Create synchronizer
	_synchronizer = boost::make_shared<TaskQueueSynchronizer>();

	// Start service
	_work = UniqueWorkPtr(new boost::asio::io_service::work(_ioService));

	// Create threads
	for(int i = 0; i < _threadNumber; i++)
		_threadPool.create_thread(
		    boost::bind(&boost::asio::io_service::run, &_ioService)
		);
}

TaskScheduler::~TaskScheduler()
{
	_ioService.stop();
	_threadPool.join_all();
}

int TaskScheduler::Schedule(SharedTaskPtr task)
{
	int nextId = _taskRegister.size();
	_synchronizer->AddTask(nextId);
	task->SetId(nextId);
	task->SetSynchronizer(_synchronizer);
	_taskRegister.push_back(task);
	_ioService.post(boost::bind(&Task::Execute, task));
	return nextId;
}

TaskStatus TaskScheduler::Wait(int id)
{
	return _taskRegister[id]->Wait();
}

std::vector<std::pair<int, TaskStatus>> TaskScheduler::WaitAll()
{
	std::vector<std::pair<int, TaskStatus>> result;
	for(auto& task : _taskRegister)
		result.push_back(std::make_pair(task->GetId(), task->Wait()));
	return result;
}

void TaskScheduler::Clear()
{
	_taskRegister.clear();
}

} /* namespace ddj */

max_stars_repo_licenses: MIT Unlicense

max_issues_repo_licenses: MIT Unlicense

max_forks_repo_licenses: MIT Unlicense


text:
//
// Created by Javier on 23/11/2016.
//

#include <boost/uuid/random_generator.hpp>
#include "BasketRepositoryMemory.h"

using namespace std;
using namespace ashop::infrastructure::impl::memory;

std::shared_ptr<ashop::infrastructure::BasketBase>
BasketRepositoryMemory::get_by_id(const boost::uuids::uuid &id) {

    if (id.is_nil()) {
        return nullptr;
    }

    auto result = this->baskets[id];

    if (nullptr == result) {
        result = make_shared<BasketBase>();
        this->persist_basket(id, result);
    }

    return result;
}

std::tuple<boost::uuids::uuid, std::shared_ptr<ashop::infrastructure::BasketBase>> BasketRepositoryMemory::save(
        std::shared_ptr<ashop::infrastructure::BasketBase> basket) {

    auto id = this->baskets_ids[basket];

    if (id.is_nil()) {
        id = boost::uuids::random_generator()();
        this->persist_basket(id, basket);
    }

    return {id, basket};
}

void BasketRepositoryMemory::persist_basket(const boost::uuids::uuid &id,
                                            const std::shared_ptr<ashop::infrastructure::BasketBase> &basket) {
    this->baskets[id]         = basket;
    this->baskets_ids[basket] = id;
}

max_stars_repo_name: javierjeronimo/ashop-cplusplus-crow

max_issues_repo_name: javierjeronimo/ashop-cplusplus-crow

max_forks_repo_name: javierjeronimo/ashop-cplusplus-crow


text:
/*
 * Copyright (c) 2011, Intel Corporation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <boost/format.hpp>
#include "fidIRQVec_r10b.h"
#include "globals.h"
#include "grpDefs.h"
#include "../Queues/acq.h"
#include "../Queues/asq.h"
#include "../Utils/kernelAPI.h"
#include "../Utils/irq.h"
#include "../Utils/io.h"
#include "../Cmds/baseFeatures.h"
#include "../Cmds/getFeatures.h"
#include "../Cmds/setFeatures.h"

namespace GrpAdminSetGetFeatCombo {

FIDIRQVec_r10b::FIDIRQVec_r10b(
    string grpName, string testName) :
    Test(grpName, testName, SPECREV_10b)
{
    // 63 chars allowed:     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    mTestDesc.SetCompliance("revision 1.0b, section 5");
    mTestDesc.SetShort(     "Verify changes are allowed on FID = IRQ vector");
    // No string size limit for the long description
    mTestDesc.SetLong(
        "Reset ctrlr to cause a clearing of DUT state. Issue GetFeatures, "
        "FID = 0x09. Programmatically and dynamically force new, legal values "
        "into all fields of CE.DW0 and assoc changes with SetFeatures. Redo "
        "GetFeatures to verify settings were accepted.");

}

FIDIRQVec_r10b::~FIDIRQVec_r10b()
{
    ///////////////////////////////////////////////////////////////////////////
    // Allocations taken from the heap and not under the control of the
    // RsrcMngr need to be freed/deleted here.
    ///////////////////////////////////////////////////////////////////////////
}

FIDIRQVec_r10b::
FIDIRQVec_r10b(const FIDIRQVec_r10b &other) : Test(other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
}

FIDIRQVec_r10b &
FIDIRQVec_r10b::operator=(const FIDIRQVec_r10b &other)
{
    ///////////////////////////////////////////////////////////////////////////
    // All pointers in this object must be NULL, never allow shallow or deep
    // copies, see Test::Clone() header comment.
    ///////////////////////////////////////////////////////////////////////////
    Test::operator=(other);
    return *this;
}

Test::RunType
FIDIRQVec_r10b::RunnableCoreTest(bool preserve)
{
    ///////////////////////////////////////////////////////////////////////////
    // All code contained herein must never permanently modify the state or
    // configuration of the DUT. Permanence is defined as state or configuration
    // changes that will not be restored after a cold hard reset.
    ///////////////////////////////////////////////////////////////////////////

    return ((preserve == true) ? RUN_FALSE : RUN_TRUE);   // Test is destructive
}

void
FIDIRQVec_r10b::RunCoreTest()
{
    /** \verbatim
     * Assumptions:
     * None.
     * \endverbatim
     */
    string work;
    union CE ce;
    struct nvme_gen_cq acqMetrics;

    if (gCtrlrConfig->SetState(ST_DISABLE_COMPLETELY) == false)
        throw FrmwkEx(HERE);

    LOG_NRM("Create admin queues ACQ and ASQ for test lifetime");
    SharedACQPtr acq = SharedACQPtr(new ACQ(gDutFd));
    acq->Init(5);

    SharedASQPtr asq = SharedASQPtr(new ASQ(gDutFd));
    asq->Init(5);

    // All queues will use identical IRQ vector
    IRQ::SetAnySchemeSpecifyNum(1);

    gCtrlrConfig->SetCSS(CtrlrConfig::CSS_NVM_CMDSET);
    if (gCtrlrConfig->SetState(ST_ENABLE) == false)
        throw FrmwkEx(HERE);

    LOG_NRM("Create Get features and set features cmds");
    SharedGetFeaturesPtr getFeaturesCmd =
        SharedGetFeaturesPtr(new GetFeatures());
    SharedSetFeaturesPtr setFeaturesCmd =
        SharedSetFeaturesPtr(new SetFeatures());

    LOG_NRM("Set and Get features for IRQ vec config (FID = 0x%x)",
        BaseFeatures::FID_IRQ_VEC_CONFIG);
    getFeaturesCmd->SetFID(BaseFeatures::FID_IRQ_VEC_CONFIG);
    setFeaturesCmd->SetFID(BaseFeatures::FID_IRQ_VEC_CONFIG);

    uint16_t max_ivec = IRQ::GetMaxIRQsSupportedAnyScheme();

    uint8_t ivecMismatch = 0;
    for (uint8_t cd = 0; cd < 2; cd++) {
         for (uint16_t ivec = 1; ivec < max_ivec; ivec++) {
            LOG_NRM("Set and Get features for IVECCONF # %d", ivec);

            LOG_NRM("Issue set features cmd with CD = %d", cd);
            LOG_NRM("Issue set features cmd with IVEC = %d", ivec);

            setFeaturesCmd->SetIntVecConfig(cd, ivec);
            work = str(boost::format("cdivec.%d") % ivec);
            IO::SendAndReapCmd(mGrpName, mTestName, CALC_TIMEOUT_ms(1),
                asq, acq, setFeaturesCmd, work, true);

            getFeaturesCmd->SetIntVecConfigIV(ivec);
            acqMetrics = acq->GetQMetrics();
            LOG_NRM("Issue get features & check (cd, ivec)=(%d, %d)", cd, ivec);
            IO::SendAndReapCmd(mGrpName, mTestName, CALC_TIMEOUT_ms(1),
                asq, acq, getFeaturesCmd, work, false);

            ce = acq->PeekCE(acqMetrics.head_ptr);
            LOG_NRM("IRQ Vector Conf using Get Features = %d", ce.t.dw0);
            if (ivec != (uint16_t)ce.t.dw0) {
                LOG_ERR("IRQ Vector Conf get feat does not match set feat"
                    "(expected, rcvd) = (%d, %d)", ivec, ce.t.dw0);
                ivecMismatch = 0xFF;
            }
            if (cd != ((ce.t.dw0 >> 16) & 0x1)) {
                LOG_ERR("Coalesing disable get feat does not match set feat"
                    "(expected, rcvd) = (%d, %d)", cd, (ce.t.dw0 >> 16) & 0x1);
                ivecMismatch = 0xFF;
            }
        }
    }

    if (ivecMismatch)
        throw FrmwkEx(HERE, "IRQ Vector Conf setting mismatched.");
}

}   // namespace

max_stars_repo_name: NirmalaArun/tnvme

max_issues_repo_name: NirmalaArun/tnvme

max_forks_repo_name: NirmalaArun/tnvme


text: #include <boost/spirit/home/support/attributes_fwd.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright Cromwell D. Enage 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef LIBS_PARAMETER_TEST_EVALUTE_CATEGORY_HPP
#define LIBS_PARAMETER_TEST_EVALUTE_CATEGORY_HPP

namespace test {

    enum invoked
    {
        passed_by_lvalue_reference_to_const
      , passed_by_lvalue_reference
      , passed_by_rvalue_reference_to_const
      , passed_by_rvalue_reference
    };

    float rvalue_float()
    {
        return 0.0f;
    }

    float const rvalue_const_float()
    {
        return 0.0f;
    }

    float& lvalue_float()
    {
        static float lfloat = 0.0f;
        return lfloat;
    }

    float const& lvalue_const_float()
    {
        static float const clfloat = 0.0f;
        return clfloat;
    }

    char const* rvalue_char_ptr()
    {
        return "foo";
    }

    char const* const rvalue_const_char_ptr()
    {
        return "foo";
    }

    char const*& lvalue_char_ptr()
    {
        static char const* larr = "foo";
        return larr;
    }

    char const* const& lvalue_const_char_ptr()
    {
        static char const* const clarr = "foo";
        return clarr;
    }
} // namespace test

#include <string>

namespace test {

    std::string rvalue_str()
    {
        return std::string("bar");
    }

    std::string const rvalue_const_str()
    {
        return std::string("bar");
    }

    std::string& lvalue_str()
    {
        static std::string lstr = std::string("bar");
        return lstr;
    }

    std::string const& lvalue_const_str()
    {
        static std::string const clstr = std::string("bar");
        return clstr;
    }
} // namespace test

#include <bitset>

namespace test {

    template <std::size_t N>
    std::bitset<N + 1> rvalue_bitset()
    {
        return std::bitset<N + 1>();
    }

    template <std::size_t N>
    std::bitset<N + 1> const rvalue_const_bitset()
    {
        return std::bitset<N + 1>();
    }

    template <std::size_t N>
    std::bitset<N + 1>& lvalue_bitset()
    {
        static std::bitset<N + 1> lset = std::bitset<N + 1>();
        return lset;
    }

    template <std::size_t N>
    std::bitset<N + 1> const& lvalue_const_bitset()
    {
        static std::bitset<N + 1> const clset = std::bitset<N + 1>();
        return clset;
    }

    template <std::size_t N>
    struct lvalue_bitset_function
    {
        typedef std::bitset<N + 1>& result_type;

        result_type operator()() const
        {
            return test::lvalue_bitset<N>();
        }
    };

    template <std::size_t N>
    struct lvalue_const_bitset_function
    {
        typedef std::bitset<N + 1> const& result_type;

        result_type operator()() const
        {
            return test::lvalue_const_bitset<N>();
        }
    };

    template <std::size_t N>
    struct rvalue_bitset_function
    {
        typedef std::bitset<N + 1> result_type;

        result_type operator()() const
        {
            return test::rvalue_bitset<N>();
        }
    };

    template <std::size_t N>
    struct rvalue_const_bitset_function
    {
        typedef std::bitset<N + 1> const result_type;

        result_type operator()() const
        {
            return test::rvalue_const_bitset<N>();
        }
    };
} // namespace test

#include <boost/parameter/config.hpp>

namespace test {

    template <typename T>
    struct A
    {
        static test::invoked evaluate_category(T const&)
        {
            return test::passed_by_lvalue_reference_to_const;
        }

        static test::invoked evaluate_category(T&)
        {
            return test::passed_by_lvalue_reference;
        }

#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
        static test::invoked evaluate_category(T const&&)
        {
            return test::passed_by_rvalue_reference_to_const;
        }

        static test::invoked evaluate_category(T&&)
        {
            return test::passed_by_rvalue_reference;
        }
#endif
    };

    struct U
    {
        template <std::size_t N>
        static test::invoked evaluate_category(std::bitset<N + 1> const&)
        {
            return test::passed_by_lvalue_reference_to_const;
        }

        template <std::size_t N>
        static test::invoked evaluate_category(std::bitset<N + 1>&)
        {
            return test::passed_by_lvalue_reference;
        }

#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
        template <std::size_t N>
        static test::invoked evaluate_category(std::bitset<N + 1> const&&)
        {
            return test::passed_by_rvalue_reference_to_const;
        }

        template <std::size_t N>
        static test::invoked evaluate_category(std::bitset<N + 1>&&)
        {
            return test::passed_by_rvalue_reference;
        }
#endif
    };
} // namespace test

#include <boost/parameter/value_type.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <type_traits>
#else
#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#endif

namespace test {

    template <typename CharConstPtrParamTag>
    struct string_predicate
    {
        template <typename Arg, typename Args>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
        using fn = std::is_convertible<
            Arg
          , std::basic_string<
                typename std::remove_const<
                    typename std::remove_pointer<
                        typename boost::parameter::value_type<
                            Args
                          , CharConstPtrParamTag
#if !defined(LIBS_PARAMETER_TEST_COMPILE_FAILURE)
                          , char const*
#endif
                        >::type
                    >::type
                >::type
            >
        >;
#else   // !defined(BOOST_PARAMETER_CAN_USE_MP11)
        struct apply
          : boost::mpl::if_<
                boost::is_convertible<
                    Arg
                  , std::basic_string<
                        typename boost::remove_const<
                            typename boost::remove_pointer<
                                typename boost::parameter::value_type<
                                    Args
                                  , CharConstPtrParamTag
#if !defined(LIBS_PARAMETER_TEST_COMPILE_FAILURE)
                                  , char const*
#endif
                                >::type
                            >::type
                        >::type
                    >
                >
              , boost::mpl::true_
              , boost::mpl::false_
            >
        {
        };
#endif  // BOOST_PARAMETER_CAN_USE_MP11
    };
} // namespace test

#endif  // include guard


text:
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <thread>
#include <vector>
using namespace std;

#include <leveldb/db.h>
#include <leveldb/write_batch.h>

#include <boost/format.hpp>

#include "ttsmaster.hpp"
#include "log.hpp"

TTSMaster::TTSMaster(const string &path) {
  master_db_path_phrase_ = path + "/phrase";
  master_db_path_hanzi_ = path + "/hanzi";
  master_db_path_phoneme_ = path + "/phoneme";
  openDB();
}

TTSMaster::~TTSMaster() {
  closeDB();
}

string TTSMaster::getPhoneme(const string &pinyin) const{
  string result;
  if (master_phoneme_) {
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true;
    leveldb::Slice key(pinyin);
    string valueStr;
    auto status = master_phoneme_->Get(readOptions, key, &valueStr);
    TRACE_VAR(status.ToString());
    if (status.ok() && valueStr.empty() == false) {
      TRACE_VAR(valueStr);
      return valueStr;
    }
  }
  return result;
}

string TTSMaster::getHanzi(const string &hanzi) const{
  string result;
  if (master_hanzi_) {
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true;
    leveldb::Slice key(hanzi);
    string valueStr;
    auto status = master_hanzi_->Get(readOptions, key, &valueStr);
    TRACE_VAR(status.ToString());
    if (status.ok() && valueStr.empty() == false) {
      TRACE_VAR(valueStr);
      return valueStr;
    }
  }
  return result;
}
string TTSMaster::getPhrase(const string &word) const{
  string result;
  if (master_phrase_) {
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true;
    leveldb::Slice key(word);
    string valueStr;
    auto status = master_phrase_->Get(readOptions, key, &valueStr);
    TRACE_VAR(status.ToString());
    if (status.ok() && valueStr.empty() == false) {
      TRACE_VAR(valueStr);
      return valueStr;
    }
  }
  return result;
}

#define OPEN_DB(x) { \
  if (master_##x##_ == nullptr) {\
    leveldb::Options options;\
    options.create_if_missing = true;\
    options.max_open_files = 512;\
    options.paranoid_checks = true;\
    options.compression = leveldb::kNoCompression;\
    auto status = leveldb::DB::Open(options, master_db_path_##x##_, & master_##x##_);\
    if (status.ok() == false) {\
      DUMP_VAR(status.ToString());\
      master_##x##_ = nullptr;\
    }\
  }\
}

#define CLOSE_DB(x) { \
  if (master_##x##_ != nullptr) {\
    delete master_##x##_;\
    master_##x##_ = nullptr;\
  }\
}

void TTSMaster::openDB() {
  OPEN_DB(phrase);
  OPEN_DB(hanzi);
  OPEN_DB(phoneme);
}

void TTSMaster::closeDB() {
  CLOSE_DB(phrase);
  CLOSE_DB(hanzi);
  CLOSE_DB(phoneme);
}


text:
#include "Inf.h"

#include "InfLexer.h"
#include "InfParser.h"
#include "InfParserBaseVisitor.h"

#include "AtxLexer.h"
#include "AtxParser.h"
#include "AtxParserBaseVisitor.h"

#include "zerrors.h"
#include "zlogging.h"
#include "file_utilities.h"

#include <antlr4-runtime.h>

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>
#include <array>
#include <cmath>
#include <cstdint>

#include <boost/lexical_cast.hpp>

namespace outlaws {

class ItemVisitor : public infgrammar::InfParserBaseVisitor {
public:

    virtual antlrcpp::Any visitInf_file(infgrammar::InfParser::Inf_fileContext *ctx) override {
        return visitChildren(ctx);
    }

    virtual antlrcpp::Any visitItem(infgrammar::InfParser::ItemContext *ctx) override {
        return visitChildren(ctx);
    }

    virtual antlrcpp::Any visitClass_(infgrammar::InfParser::Class_Context *ctx) override {
        return visitChildren(ctx);
    }

    virtual antlrcpp::Any visitClassElement(infgrammar::InfParser::ClassElementContext *ctx) override {
        return visitChildren(ctx);
    }

    virtual antlrcpp::Any visitFloat_(infgrammar::InfParser::Float_Context *ctx) override {
        return visitChildren(ctx);
    }
};

void loadInf(const std::string& filePath) {
    std::ifstream stream;
    stream.open(filePath);

    antlr4::ANTLRInputStream input(stream);
    infgrammar::InfLexer lexer(&input);
    antlr4::CommonTokenStream tokens(&lexer);
    infgrammar::InfParser parser(&tokens);

    infgrammar::InfParser::Inf_fileContext* tree = parser.inf_file();

    ItemVisitor itemVisitor;
    itemVisitor.visitInf_file(tree);
}

} // namespace outlaws

max_stars_repo_name: Zbyl/OutlawsX

max_issues_repo_name: Zbyl/OutlawsX

max_forks_repo_name: Zbyl/OutlawsX


text:
#pragma once

/**
   Dataflow analysis that computes the set of unjustified assumptions
   taken by Crab while proving the assertions.
 **/

#include <crab/common/types.hpp>
#include <crab/common/debug.hpp>
#include <crab/common/stats.hpp>
#include <crab/cfg/cfg.hpp>
#include <crab/analysis/dataflow/assertion_crawler.hpp>

#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/range/iterator_range.hpp>

#include <map>

namespace crab {

  namespace analyzer {

    using namespace crab::iterators;
    using namespace crab::domains;
    using namespace crab::cfg;

    // A class to represent an unjustified assumption
    template<class CFG>
    class assumption {

    public:

      typedef flat_killgen_domain<typename CFG::variable_t> var_dom_t;
      typedef typename CFG::basic_block_t::statement_t statement_t;

     protected:

      // unique id
      unsigned _id;
      // statement where the unsound assumption was assumed.
      const statement_t * _s;
      // a subset of s' variables on which the unsound assumption was assumed.
      var_dom_t _vars;

    public:

      assumption(unsigned id, const statement_t *s, var_dom_t vars)
	: _id(id), _s(s), _vars (vars) {}

      virtual ~assumption() {}

      var_dom_t get_vars () const { return _vars; }

      const statement_t* get_statement() const { return _s;}

      std::string get_id_str () const {
	std::string res("a");
	return res + std::to_string(_id);
      }

      virtual void write(crab::crab_os& o) = 0;
    };

    template<typename CFG>
    crab_os& operator<<(crab::crab_os&o, assumption<CFG> &a){
      a.write(o);
      return o;
    }

    // Subclass of assumption for arithmetic overflow
    template<class CFG>
    class overflow_assumption: public assumption<CFG> {

    public:

      typedef assumption<CFG> base_type;
      typedef overflow_assumption<CFG> this_type;

      typedef typename base_type::var_dom_t var_dom_t;
      typedef typename base_type::statement_t statement_t;

    private:

      var_dom_t _get_vars (const statement_t *s) const {
	var_dom_t vars;
	auto lvars = s->get_live ();
	for (auto v: boost::make_iterator_range(lvars.uses_begin(),
						lvars.uses_end())) {
	  vars += v;
	}
	return vars;
      }

    public:

      overflow_assumption (unsigned id, const statement_t *s)
	: base_type(id, s, _get_vars(s)) {}

      virtual void write (crab::crab_os& o) override {
	o << "assume NotOverflow(" << this->_vars << ")" << " as " << this->get_id_str();
      }
    };

    /** The analysis of unjustified assumptions.
     *
     * Compute for each assertion the set of unjustified assumptions,
     * that is, the unproved assumptions taken by the analyzer while
     * proving assertions.
     *
     * For now, we only take into consideration integer overflows.
     **/
    template<class CFG>
    class assumption_analysis {

    public:

      struct stats_t {
	unsigned num_assertions;
	unsigned max_assumptions_per_assertion;
	float avg_assumptions_per_assertion;

	stats_t(unsigned n1, unsigned n2, float n3):
	  num_assertions(n1),
	  max_assumptions_per_assertion(n2),
	  avg_assumptions_per_assertion(n3) {}

	void write(crab::crab_os&o) {
	  o << "BRUNCH_STAT Assertions " << num_assertions << "\n";
	  o << "BRUNCH_STAT Assumptions "
	    << avg_assumptions_per_assertion * num_assertions << "\n";
	  o << "BRUNCH_STAT MaxAssumptionsPerAssertion "
	    << max_assumptions_per_assertion << "\n";
	  o << "BRUNCH_STAT AvgAssumptionsPerAssertion "
	    << avg_assumptions_per_assertion << "\n";
	}

	friend crab_os& operator<<(crab::crab_os&o,
				   typename assumption_analysis<CFG>::stats_t &stats){
	  stats.write(o);
	  return o;
	}
      };

    public:

      typedef typename CFG::statement_t statement_t;
      typedef cfg::assert_stmt<typename CFG::number_t, typename CFG::varname_t> assert_t;
      typedef assumption<CFG> assumption_t;
      typedef boost::shared_ptr<assumption_t> assumption_ptr;
      typedef std::vector<assumption_ptr> vector_assumption_ptr;

    protected:

      // map an assert statement to its unjustified assumptions
      typedef boost::unordered_map<const assert_t*, vector_assumption_ptr> assumption_map_t;
      // map an arbitrary statement to the assumptions originated in that statement
      typedef boost::unordered_map<const statement_t*, vector_assumption_ptr> assumption_origin_map_t;

      /** the cfg **/
      CFG m_cfg;
      /** map each assertion to its unjustified assumptions **/
      assumption_map_t m_assumption_map;
      /** map a statement to the set of assumptions originated by that statement **/
      assumption_origin_map_t m_origin_map;
      /** generate id's for assumptions **/
      unsigned m_id;

      static bool can_overflow(statement_t &s) {
	// TODO: cover select/assume with conditions that can overflow

	if (s.is_int_cast()) {
	  auto cast_stmt = static_cast<const typename CFG::basic_block_t::int_cast_t*>(&s);
	  return (cast_stmt->op() == crab::CAST_TRUNC);
	} else if (s.is_bin_op ()) {
	  auto bin_op_s = static_cast<const typename CFG::basic_block_t::bin_op_t*>(&s);
	  return (bin_op_s->op () == crab::BINOP_ADD ||
		  bin_op_s->op () == crab::BINOP_SUB ||
		  bin_op_s->op () == crab::BINOP_MUL);
	} else {
	  return false;
	}
      }

    protected:

      void insert_assumption(const assert_t *a, assumption_ptr as) {
	auto it = m_assumption_map.find(a);
	if (it != m_assumption_map.end()) {
	  it->second.push_back(as);
	} else {
	  vector_assumption_ptr assumes = {as};
	  m_assumption_map.insert(std::make_pair(a, assumes));
	}
      }

      // create a new overflow assumption
      assumption_ptr new_assumption(const statement_t *s) {
	assumption_ptr assume = boost::make_shared<overflow_assumption<CFG> >(m_id++, s);
	auto it = m_origin_map.find(s);
	if (it != m_origin_map.end()) {
	  it->second.push_back(assume);
	} else {
	  vector_assumption_ptr assumes = {assume};
	  m_origin_map.insert(std::make_pair(s, assumes));
	}
	return assume;
      }

    public:

      assumption_analysis(CFG cfg): m_cfg(cfg), m_id(0) {}

      virtual ~assumption_analysis() {}

      virtual void exec() = 0;

      // return the assumptions originated in s
      void get_originated_assumptions(const statement_t *s, std::vector<assumption_ptr> &out)  {
	auto it = m_origin_map.find(s);
	if (it != m_origin_map.end()) {
	  std::copy(it->second.begin(), it->second.end(),std::back_inserter(out));
	}
      }

      // return the unjustified assumptions for assertion s
      void get_assumptions(const assert_t *s, std::vector<assumption_ptr> &out)  {
	auto it = m_assumption_map.find(s);
	if (it != m_assumption_map.end()) {
	  std::copy(it->second.begin(), it->second.end(),std::back_inserter(out));
	}
      }

      stats_t get_stats() const {
	unsigned num_assertions = 0;
	unsigned max_assumptions_per_assertion = 0;
	float avg_assumptions_per_assertion = 0.0;
	unsigned num_assumptions = 0;

	for (auto &kv: m_assumption_map) {
	  num_assertions++;
	  num_assumptions += kv.second.size();
	  if (kv.second.size() > max_assumptions_per_assertion)
	    max_assumptions_per_assertion = kv.second.size();
	}
	if (num_assertions > 0)
	  avg_assumptions_per_assertion = (float)num_assumptions / (float)num_assertions;

	return stats_t(num_assertions,
		       max_assumptions_per_assertion,
		       avg_assumptions_per_assertion);
      }

      void write (crab::crab_os &o)  {
	o << "******* UNJUSTIFIED ASSUMPTION ANALYSIS ********\n";
	for (auto &kv: m_assumption_map) {
	  o << *(kv.first) << " with unjustified assumptions:\n";
	  for (auto a: kv.second) {
	    o << "\t" << *a << " in " << *(a->get_statement()) << "\n";
	  }
	}
	o << "******************* STATS **********************\n";
	auto stats = get_stats();
	o << stats << "\n";
      }
    };

    template<typename CFG>
    crab_os& operator<<(crab::crab_os&o, assumption_analysis<CFG> &aa){
      aa.write(o);
      return o;
    }

    /**
        Based on "Guiding dynamic symbolic execution toward unverified program
	executions" by Christakis, Muller, and Wustholz (ICSE'16).

	For each assertion it considers all the assumptions
	backward-reachable in the CFG.
    **/
    template<class CFG>
    class assumption_naive_analysis: public assumption_analysis<CFG> {

      typedef assumption_analysis<CFG> assumption_analysis_t;
      using typename assumption_analysis_t::statement_t;
      using typename assumption_analysis_t::assert_t;
      using typename assumption_analysis_t::assumption_ptr;
      using typename assumption_analysis_t::vector_assumption_ptr;
      typedef typename CFG::basic_block_label_t bb_label_t;
      typedef boost::unordered_set<bb_label_t> label_set_t;
      typedef typename CFG::basic_block_t bb_t;

      void backward_reachable(bb_label_t r, const assert_t* a, label_set_t &visited){
	auto ret = visited.insert(r);
	if (!ret.second) return; // already in visited

	bb_t &bb = this->m_cfg.get_node(r);
	for (auto &s: boost::make_iterator_range(bb.begin(),bb.end())) {
	  if (static_cast<const assert_t*>(&s) == a) break;

	  if (assumption_analysis_t::can_overflow(s)) {
	    assumption_ptr assume = this->new_assumption(&s);
	    assumption_analysis_t::insert_assumption(a, assume);
	  }
	}

	for (auto child: this->m_cfg.prev_nodes(r)) {
	  backward_reachable(child, a, visited);
	}
      }

    public:

      assumption_naive_analysis(CFG cfg) : assumption_analysis_t(cfg) {}

      virtual ~assumption_naive_analysis() {}

      virtual void exec() {
	for (auto &bb: boost::make_iterator_range(this->m_cfg.begin(), this->m_cfg.end())) {
	  for (auto &s: boost::make_iterator_range(bb.begin(),bb.end())) {
	    if (s.is_assert()) {
	      auto a = static_cast<const assert_t*>(&s);
	      label_set_t visited;
	      backward_reachable(bb.label(), a, visited);
	    }
	  }
	}
      }
    };

    /** Uses the assertion crawler analysis to improve precision **/
    template<class CFG>
    class assumption_dataflow_analysis: public assumption_analysis<CFG> {

      typedef assumption_analysis<CFG> assumption_analysis_t;
      using typename assumption_analysis_t::statement_t;
      using typename assumption_analysis_t::assumption_ptr;
      typedef crab::analyzer::assertion_crawler<CFG> assertion_crawler_t;
      typedef typename assertion_crawler_t::separate_domain_t separate_domain_t;
      using typename assumption_analysis_t::vector_assumption_ptr;
      typedef std::map<statement_t*, separate_domain_t> pp_inv_map_t;

    public:

      assumption_dataflow_analysis(CFG cfg): assumption_analysis_t(cfg) {}

      virtual ~assumption_dataflow_analysis() {}

      virtual void exec() {
	assertion_crawler_t assert_crawler(this->m_cfg);
	assert_crawler.exec();

	for (auto &bb: boost::make_iterator_range(this->m_cfg.begin(),
						  this->m_cfg.end())) {

	  // find out if the block is of interest
	  bool op_can_overflow = false;
	  for (auto &s: bb) {
	    if (assumption_analysis_t::can_overflow(s)) {
	      op_can_overflow = true;
	      break;
	    }
	  }

	  if (!op_can_overflow) continue;

	  auto bb_out = assert_crawler.get_assertions(bb.label());

	  if (bb_out.is_bottom()) continue;

	  CRAB_LOG("aa",
		   crab::outs () << "Basic block    : "
		                 << cfg_impl::get_label_str(bb.label()) << "\n";
		   crab::outs () << "OUT invariants : "
		                 << bb_out << "\n";);

	  // get dataflow information at the pre-state at each program point
	  pp_inv_map_t pp_in_map;
	  assert_crawler.get_assertions(bb.label(), pp_in_map);

	  for (auto &s: boost::make_iterator_range(bb.begin(),bb.end())) {
	    if (!assumption_analysis_t::can_overflow(s)) continue;

	    auto in = pp_in_map[&s];
	    CRAB_LOG("aa",
		     crab::outs () << "Check s = " << s << "\n";
		     crab::outs () << "IN(s)   = " << in << "\n";);

	    // -- Traverse all pairs (i,V) where i is the id for the
	    //    assertion and V is the variables computed by the
	    //    dataflow analysis. If V intersect with the variables
	    //    on the rhs of the arithmetic operation then we
	    //    assume an assumption to the assertion.
	    assumption_ptr assume = this->new_assumption(&s);
	    for (auto kv: boost::make_iterator_range (in.begin(), in.end ())) {
	      auto vars = kv.second;
	      if (!(vars & assume->get_vars ()).is_bottom ())
		assumption_analysis_t::insert_assumption(kv.first.get(), assume);
	    }
	  }
	}
      }
    };

  } // end namespace
} // end namespace

max_stars_repo_name: aziem/crab

max_issues_repo_name: aziem/crab

max_forks_repo_name: aziem/crab


text:
#include <uhd/types/tune_request.hpp>
#include <uhd/utils/thread_priority.hpp>
#include <uhd/utils/safe_call.hpp>
#include <uhd/usrp/multi_usrp.hpp>

#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctime>

#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>

#include "guhd.h"
#include "buffer.h"

#define F_L1 (1575.42e6)
#define F_L2 (1227.60e6)
#define ANALOG_GAIN (50)
#define BW_L1 (2.0e6) // smallest BW supported by DBSRX2
#define BW_L2 (8.0e6)
#define SETUP_TIME (1.5)
#define NEW_FILE_CYCLE_MIN (10.0)

Guhd::Guhd(
    const boost::program_options::variables_map& vm,
/*        const std::vector<size_t>& ip,
        const std::vector<size_t>& ltwo,
        const std::string& clk,
        const std::string& sync,*/
        const bool& mimo
/*        const double& rate,
        const boost::filesystem::path& path*/):
	// Constructor initialize list to set up members which don't have default constructors
    _run(false),_overflow_message(true),
    _clock(vm["clk"] .as<std::string>()),
    _sync (vm["sync"].as<std::string>()), _mimo(mimo),
    _rate(vm["rate"] .as<double>()), _runN(0){

    const std::vector<size_t>& ip = vm["ip"].as< std::vector<size_t> >();

    _chan   .reserve(ip.size());
    _p_fbuff.reserve(ip.size());
    //_p_sock .reserve(ip.size());

    std::ostringstream oss;
    for(size_t i = 0 ; i < ip.size() ; i++){
        if (i) oss << ",";
        oss << "addr" << i << "=192.168.10." << ip[i];
        _chan.push_back(i);
    } std::clog << "[UHD] args = " << oss.str() << std::endl;
    std::clog << "[UHD] Setting usrp object & streamer" << std::endl;

    _usrp = uhd::usrp::multi_usrp::make(oss.str());
    UHD_ASSERT_THROW(_usrp->get_rx_num_channels() == _chan.size());

	// The params here define the sample sizes in data transfer and recording.
	//
	// CPU_FORMAT can be 8, 16, 24, or 32 bits and is meant to match
	// the data size used for baseband processing.
	// OTW_FORMAT can be 8 or 16 bits and is the size of the samples being sent
	// over-the-wire; 8 bits is faster, 16 bits is higher resolution.
	//
	// Both data types are complex.
	// Per guhd.h, this will be 16 bits for both, unless SC8 is defined.
	// Probably best to keep CPU_FORMAT matching OTW_FORMAT for processing speed...
	// not sure that CPU_FORMAT of 32 bits provides any increase in resolution.
	// MEM_TYPE takes care of this automatically the way that guhd.h is setup,
	// so don't change without good reason, and use MEM_TYPE in type definitions everywhere.
    uhd::stream_args_t stream_args(CPU_FORMAT,OTW_FORMAT);
    stream_args.channels = _chan;
    _rx_stream  = _usrp->get_rx_stream(stream_args);
    _spb        = _rx_stream->get_max_num_samps(); // This seems to be a fixed value based on USRP architecture
    // (treat this call like magic since there is no documentation how it decides what is the max size)

    // Setting up L2 channels
    _b_ltwo.insert(_b_ltwo.begin(),_chan.size(),false);
    for (auto const& c:vm["ltwo"].as< std::vector<size_t> >()){
        UHD_ASSERT_THROW(c < _chan.size());
        _b_ltwo[c] = true;
        //std::clog << "[UHD] Channel #" << c << " will operate at F_L2 = 1227.60 MHz" << std::endl;
    }

    for (auto const& c:_chan){
        _p_fbuff.push_back(new FileBuff(vm,c,_b_ltwo[c],&_run));
        //_p_sock.push_back (new SockBuff(1111 + i,&_run));
    }
}

Guhd::~Guhd(){
    Stop();
    for(auto const& ptr:_p_fbuff) delete ptr;
    //for(auto const& ptr:_p_sock) delete ptr;
}

int
Guhd::Start(){
    if (_run) return -1;
    _run = true;

    //allocate buffers to receive with samples (one buffer per channel)
    std::clog << "[UHD] Allocating buffers: "<< _spb <<" samples/buffer" <<std::endl;

	// Allocate buffers. This is a vector of type MEM_TYPE of the size of the
	// maximum possible number of samples per buffer (rx_streamer->get_max_num_samps)
	// (MEM_TYPE can be either 8 or 16 bits based on defines in guhd.h)
	//
	// This syntax is initializing the outer vector with as many elements as there are channels,
	// and each element being a vector of length samples-per-buffer
    _buffs = std::vector<std::vector<std::complex<MEM_TYPE> > > (
        _chan.size() , std::vector<std::complex<MEM_TYPE> >(_spb)
    );

    for(auto const& i:_chan){
        std::clog<<"\n[UHD] Configuring Channel #" << i << std::endl;
        _buff_ptrs.push_back(&_buffs[i].front());
        set_rf(i,_b_ltwo[i]);
    }

    // clock set
    set_clock();
    std::clog << "[UHD] " << "Using Device: " << _usrp->get_pp_string() << std::endl;

    uhd::stream_cmd_t stream_cmd( uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS);
    stream_cmd.num_samps = 0;
    stream_cmd.stream_now = false;
    stream_cmd.time_spec = uhd::time_spec_t(SETUP_TIME) + _usrp->get_time_now();
    _rx_stream->issue_stream_cmd(stream_cmd);

    auto t = std::time(nullptr);
    for (auto const &i:_chan){
        _p_fbuff[i]->/*init()->*/open(t);
        //_p_sock [i]->init()->open();
    }

    return 0;
}

int
Guhd::Update (){
    if (!_run) return -1;
    uhd::rx_metadata_t md;
    const size_t num_rx_samps = _rx_stream->recv(
        _buff_ptrs, _spb, md, 3.0 //timeout
    );

    //handle the error code
    if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
        std::cerr << "[UHD] " << boost::format("Timeout while streaming") << std::endl;
        return -1;
    }

    if (_overflow_message && md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW){
        _overflow_message = false;

        std::cerr << "[UHD] "
            << boost::format(
            "Got an overflow indication. Please consider the following:\n"
            "  Your write medium must sustain a rate of %fMB/s.\n"
            "  Dropped samples will not be written to the file.\n"
            "  This message will not appear again.\n"
        ) % (_usrp->get_rx_rate()*sizeof(std::complex<MEM_TYPE>) * _chan.size() /1e6);
    }

    if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
        auto t = std::time(nullptr);
        auto tm = *std::gmtime(&t);

        const std::string error = str(boost::format("[UHD] Receiver error: %s") % md.strerror());
        std::cerr
            << std::put_time(&tm, "%Y%m%d %H:%M:%S ")
            << error << std::endl;
    }

	// _runN is the number of samples recorded in the file so far
	// So, if this reaches the minute-limit for the file, make a new file and reset
    if ((_runN += num_rx_samps) > _rate * 60 * NEW_FILE_CYCLE_MIN){
        auto t = std::time(nullptr);
        // If sample number limit has been exceeded, call the FileBuff member function
        // that will create a new file and update the pointer attribute for it
        for (auto const& i:_chan)
            _p_fbuff[i]->open(t);
        _runN = 0;
    }

	// No catastropic errors have occurred yet, so log the samples we do have
    for(auto const& i:_chan){
		// Call the FileBuff member function that will write this data to the current log file
        _p_fbuff[i]->append(_buffs[i],num_rx_samps);
    }

    return 0;
}

int
Guhd::Stop(){
    if (!_run) return -1;
    _run = false;
    for (auto const& i:_chan){
        _p_fbuff[i]/*->terminate()*/->close();
        //_p_sock[i] ->terminate()->close();
    }

    uhd::stream_cmd_t stream_cmd( uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS);
    _rx_stream->issue_stream_cmd(stream_cmd);
    std::clog << "[UHD] Stopping...";
    //for(auto& os : _ofs) os.close();
    //_ofs.clear();
    _buff_ptrs.clear();
    _buffs.clear();
    std::clog << " Stopped"<<std::endl;
    return 0;
}

void
Guhd::set_clock (){
    if (_mimo) {
        UHD_ASSERT_THROW(_usrp->get_num_mboards() == 2);
        std::clog << "[UHD] MIMO enabled: channel #1 set as slave." << std::endl;
        //make mboard 1 a slave over the MIMO Cable
        _usrp->set_clock_source("mimo", 1);
        _usrp->set_time_source ("mimo", 1);
    }

    size_t board_set = _mimo? 0 : uhd::usrp::multi_usrp::ALL_CHANS;
    _usrp->set_clock_source(_clock, board_set);

    if (_sync == "pps"){
        _usrp->set_time_source("external" , board_set );
        _usrp->set_time_unknown_pps(uhd::time_spec_t(0.0));
        boost::this_thread::sleep(boost::posix_time::seconds(1)); //wait for pps sync pulse
    } else //if (_sync == "internal"){
    //    _usrp->set_time_source_out(true,board_set);
        _usrp->set_time_now(uhd::time_spec_t(0.0));
    //} else UHD_ASSERT_THROW(false);

    // LO Lock Detect
    for (auto const& i:_chan){
        std::clog << "[UHD] Detecting clock lock: channel #" << i <<std::endl;
        check_locked_sensor(_usrp->get_rx_sensor_names(i), "lo_locked", boost::bind(&uhd::usrp::multi_usrp::get_rx_sensor, _usrp, _1, i));
        if (_mimo)
            check_locked_sensor(_usrp->get_mboard_sensor_names(i), "mimo_locked", boost::bind(&uhd::usrp::multi_usrp::get_mboard_sensor, _usrp, _1, i));
        if (_clock == "external")
            check_locked_sensor(_usrp->get_mboard_sensor_names(i), "ref_locked", boost::bind(&uhd::usrp::multi_usrp::get_mboard_sensor, _usrp, _1, i));
    }
}

void
Guhd::set_rf(const size_t& ch,const bool is_L2){
    uhd::tune_request_t tune_request(is_L2?F_L2:F_L1);
    _usrp->set_rx_freq(tune_request,ch);
    std::clog << "[UHD] " << boost::format("Actual RX Freq: %f MHz...") % (_usrp->get_rx_freq(ch)/1e6) << std::endl << std::endl;

    // SETTING RATE
    std::clog << "[UHD] " << boost::format("Setting RX Rate: %f Msps...") % (_rate/1e6) << std::endl;
    _usrp->set_rx_rate(_rate,ch);
    std::clog << "[UHD] " << boost::format("Actual RX Rate: %f Msps...") % (_usrp->get_rx_rate(ch)/1e6) << std::endl << std::endl;

    //set the rf gain
    std::clog << "[UHD] " << boost::format("Setting RX Gain: %f dB...") % ANALOG_GAIN << std::endl;
    _usrp->set_rx_gain(ANALOG_GAIN,ch);
    std::clog << "[UHD] " << boost::format("Actual RX Gain: %f dB...") % _usrp->get_rx_gain(ch) << std::endl << std::endl;

    //set the IF filter bandwidth
    const double bw = is_L2?BW_L2:BW_L1;
    std::clog << "[UHD] " << boost::format("Setting RX Bandwidth: %f MHz...") % (bw/1e6) << std::endl;
    _usrp->set_rx_bandwidth(bw,ch);
    std::clog << "[UHD] " << boost::format("Actual RX Bandwidth: %f MHz...") % (_usrp->get_rx_bandwidth(ch)/1e6) << std::endl << std::endl;

    // system setup.
    boost::this_thread::sleep(boost::posix_time::seconds(SETUP_TIME)); //allow for some setup time
}

bool
Guhd::check_locked_sensor(std::vector<std::string> sensor_names, const char* sensor_name, get_sensor_fn_t get_sensor_fn){
    if (std::find(sensor_names.begin(), sensor_names.end(), sensor_name) == sensor_names.end())
        return false;

    boost::system_time start = boost::get_system_time();
    boost::system_time first_lock_time;

    std::clog << boost::format("Waiting for \"%s\": ") % sensor_name;
    std::clog.flush();

    while (true) {
        if ((not first_lock_time.is_not_a_date_time()) and
                (boost::get_system_time() > (first_lock_time + boost::posix_time::seconds(SETUP_TIME)))) {
            std::clog << " locked." << std::endl;
            break;
        }
        if (get_sensor_fn(sensor_name).to_bool()){
            if (first_lock_time.is_not_a_date_time())
                first_lock_time = boost::get_system_time();
            std::clog << "+";
            std::clog.flush();
        } else {
            first_lock_time = boost::system_time();	//reset to 'not a date time'

            if (boost::get_system_time() > (start + boost::posix_time::seconds(SETUP_TIME))){
                std::clog << std::endl;
                throw std::runtime_error(str(boost::format("timed out waiting for consecutive locks on sensor \"%s\"") % sensor_name));
            } (std::clog << "_").flush();
        }
        boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    }
    //std::clog << std::endl;
    return true;
}

max_stars_repo_name: Stanford-NavLab/NAVLab-DPE-SDR

max_issues_repo_name: Stanford-NavLab/NAVLab-DPE-SDR

max_forks_repo_name: Stanford-NavLab/NAVLab-DPE-SDR