<commit_before>#pragma once

#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/webassembly/wavm.hpp>
#include <eosio/chain/webassembly/wabt.hpp>
#include <eosio/chain/webassembly/eos-vm.hpp>
#include <eosio/chain/webassembly/runtime_interface.hpp>
#include <eosio/chain/wasm_eosio_injection.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/exceptions.hpp>
#include <fc/scoped_exit.hpp>

#include "IR/Module.h"
#include "Runtime/Intrinsics.h"
#include "Platform/Platform.h"
#include "WAST/WAST.h"

#include "IR/Validate.h"

#include <eosio/vm/allocator.hpp>

using namespace fc;
using namespace eosio::chain::webassembly;
using namespace eosio::vm;
using namespace IR;
using namespace Runtime;

using boost::multi_index_container;

namespace eosio { namespace chain {

   struct wasm_interface_impl {
      struct wasm_cache_entry {
         digest_type                                          code_hash;
         uint32_t                                             first_block_num_used;
         uint32_t                                             last_block_num_used;
         std::unique_ptr<wasm_instantiated_module_interface>  module;
         uint8_t                                              vm_type = 0;
         uint8_t                                              vm_version = 0;
      };
      struct by_hash;
      struct by_first_block_num;
      struct by_last_block_num;

      wasm_interface_impl(wasm_interface::vm_type vm, const chainbase::database& d) : db(d) {
         if(vm == wasm_interface::vm_type::wavm)
            runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>();
         else if(vm == wasm_interface::vm_type::wabt)
            runtime_interface = std::make_unique<webassembly::wabt_runtime::wabt_runtime>();
         else if(vm == wasm_interface::vm_type::eos_vm)
            runtime_interface = std::make_unique<webassembly::eos_vm_runtime::eos_vm_runtime>();
         else
            EOS_THROW(wasm_exception, "wasm_interface_impl fall through");
      }

      ~wasm_interface_impl() {
         if(is_shutting_down)
            for(wasm_cache_index::iterator it = wasm_instantiation_cache.begin(); it != wasm_instantiation_cache.end(); ++it)
               wasm_instantiation_cache.modify(it, [](wasm_cache_entry& e) {
                  e.module.release();
               });
      }

      static wasm_allocator* get_wasm_allocator() {
         static wasm_allocator walloc;
         return &walloc;
      }

      std::vector<uint8_t> parse_initial_memory(const Module& module) {
         std::vector<uint8_t> mem_image;

         for(const DataSegment& data_segment : module.dataSegments) {
            EOS_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const, wasm_exception, "");
            EOS_ASSERT(module.memories.defs.size(), wasm_exception, "");
            const U32 base_offset = data_segment.baseOffset.i32;
            const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2);
            if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size)
               FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range");
            if(base_offset + data_segment.data.size() > mem_image.size())
               mem_image.resize(base_offset + data_segment.data.size(), 0x00);
            memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size());
         }

         return mem_image;
      }

      void code_block_num_last_used(const digest_type& code_hash, const uint8_t& vm_type, const uint8_t& vm_version, const uint32_t& block_num) {
         wasm_cache_index::iterator it = wasm_instantiation_cache.find(boost::make_tuple(code_hash, vm_type, vm_version));
         if(it != wasm_instantiation_cache.end())
            wasm_instantiation_cache.modify(it, [block_num](wasm_cache_entry& e) {
               e.last_block_num_used = block_num;
            });
      }

      void current_lib(uint32_t lib) {
         //anything last used before or on the LIB can be evicted
         wasm_instantiation_cache.get<by_last_block_num>().erase(wasm_instantiation_cache.get<by_last_block_num>().begin(), wasm_instantiation_cache.get<by_last_block_num>().upper_bound(lib));
      }

      const std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module( const digest_type& code_hash, const uint8_t& vm_type,
                                                                                const uint8_t& vm_version, transaction_context& trx_context, bool inject )
      {
         wasm_cache_index::iterator it = wasm_instantiation_cache.find(
                                             boost::make_tuple(code_hash, vm_type, vm_version) );
         const code_object* codeobject = nullptr;
         if(it == wasm_instantiation_cache.end()) {
            codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));

            it = wasm_instantiation_cache.emplace( wasm_interface_impl::wasm_cache_entry{
                                                      .code_hash = code_hash,
                                                      .first_block_num_used = codeobject->first_block_used,
                                                      .last_block_num_used = UINT32_MAX,
                                                      .module = nullptr,
                                                      .vm_type = vm_type,
                                                      .vm_version = vm_version
                                                   } ).first;
         }

         if(!it->module) {
            if(!codeobject)
               codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));

            auto timer_pause = fc::make_scoped_exit([&](){
               trx_context.resume_billing_timer();
            });
            trx_context.pause_billing_timer();
            IR::Module module;
	    std::vector<U8> bytes = {(const U8*)codeobject->code.data(), (const U8*)codeobject->code.data() + codeobject->code.size()};
            try {
               Serialization::MemoryInputStream stream((const U8*)bytes.data(), bytes.size());
               WASM::serialize(stream, module);
               module.userSections.clear();
            } catch(const Serialization::FatalSerializationException& e) {
               EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
            } catch(const IR::ValidationException& e) {
               EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
            }
            if(inject) {
               wasm_injections::wasm_binary_injection injector(module);
               injector.inject();

               try {
                  Serialization::ArrayOutputStream outstream;
                  WASM::serialize(outstream, module);
                  bytes = outstream.getBytes();
               } catch(const Serialization::FatalSerializationException& e) {
                  EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
               } catch(const IR::ValidationException& e) {
                  EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
               }
	    }

            wasm_instantiation_cache.modify(it, [&](auto& c) {
               c.module = runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module));
            });
         }
         return it->module;
      }

      bool is_shutting_down = false;
      std::unique_ptr<wasm_runtime_interface> runtime_interface;
      wasm_interface::vm_type runtime;

      typedef boost::multi_index_container<
         wasm_cache_entry,
         indexed_by<
            ordered_unique<tag<by_hash>,
               composite_key< wasm_cache_entry,
                  member<wasm_cache_entry, digest_type, &wasm_cache_entry::code_hash>,
                  member<wasm_cache_entry, uint8_t,     &wasm_cache_entry::vm_type>,
                  member<wasm_cache_entry, uint8_t,     &wasm_cache_entry::vm_version>
               >
            >,
            ordered_non_unique<tag<by_first_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::first_block_num_used>>,
            ordered_non_unique<tag<by_last_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::last_block_num_used>>
         >
      > wasm_cache_index;
      wasm_cache_index wasm_instantiation_cache;

      const chainbase::database& db;
   };

#define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
   _REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)         \
   _REGISTER_WABT_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)         \
   _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)

#define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG )

#define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) )

#define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) )

#define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\
   static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature");

#define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\
   static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature");

#define _UNWRAP_SEQ(...) __VA_ARGS__

#define _EXPAND_ARGS(CLS, MOD, INFO)\
   ( CLS, MOD, _UNWRAP_SEQ INFO )

#define _REGISTER_INTRINSIC(R, CLS, INFO)\
   BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY())

#define REGISTER_INTRINSICS(CLS, MEMBERS)\
   BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))

#define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\
   BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY())

#define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\
   BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))

} } // eosio::chain
<commit_msg>just totally disable injection for now<commit_after>#pragma once

#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/webassembly/wavm.hpp>
#include <eosio/chain/webassembly/wabt.hpp>
#include <eosio/chain/webassembly/eos-vm.hpp>
#include <eosio/chain/webassembly/runtime_interface.hpp>
#include <eosio/chain/wasm_eosio_injection.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/exceptions.hpp>
#include <fc/scoped_exit.hpp>

#include "IR/Module.h"
#include "Runtime/Intrinsics.h"
#include "Platform/Platform.h"
#include "WAST/WAST.h"

#include "IR/Validate.h"

#include <eosio/vm/allocator.hpp>

using namespace fc;
using namespace eosio::chain::webassembly;
using namespace eosio::vm;
using namespace IR;
using namespace Runtime;

using boost::multi_index_container;

namespace eosio { namespace chain {

   struct wasm_interface_impl {
      struct wasm_cache_entry {
         digest_type                                          code_hash;
         uint32_t                                             first_block_num_used;
         uint32_t                                             last_block_num_used;
         std::unique_ptr<wasm_instantiated_module_interface>  module;
         uint8_t                                              vm_type = 0;
         uint8_t                                              vm_version = 0;
      };
      struct by_hash;
      struct by_first_block_num;
      struct by_last_block_num;

      wasm_interface_impl(wasm_interface::vm_type vm, const chainbase::database& d) : db(d) {
         if(vm == wasm_interface::vm_type::wavm)
            runtime_interface = std::make_unique<webassembly::wavm::wavm_runtime>();
         else if(vm == wasm_interface::vm_type::wabt)
            runtime_interface = std::make_unique<webassembly::wabt_runtime::wabt_runtime>();
         else if(vm == wasm_interface::vm_type::eos_vm)
            runtime_interface = std::make_unique<webassembly::eos_vm_runtime::eos_vm_runtime>();
         else
            EOS_THROW(wasm_exception, "wasm_interface_impl fall through");
      }

      ~wasm_interface_impl() {
         if(is_shutting_down)
            for(wasm_cache_index::iterator it = wasm_instantiation_cache.begin(); it != wasm_instantiation_cache.end(); ++it)
               wasm_instantiation_cache.modify(it, [](wasm_cache_entry& e) {
                  e.module.release();
               });
      }

      static wasm_allocator* get_wasm_allocator() {
         static wasm_allocator walloc;
         return &walloc;
      }

      std::vector<uint8_t> parse_initial_memory(const Module& module) {
         std::vector<uint8_t> mem_image;

         for(const DataSegment& data_segment : module.dataSegments) {
            EOS_ASSERT(data_segment.baseOffset.type == InitializerExpression::Type::i32_const, wasm_exception, "");
            EOS_ASSERT(module.memories.defs.size(), wasm_exception, "");
            const U32 base_offset = data_segment.baseOffset.i32;
            const Uptr memory_size = (module.memories.defs[0].type.size.min << IR::numBytesPerPageLog2);
            if(base_offset >= memory_size || base_offset + data_segment.data.size() > memory_size)
               FC_THROW_EXCEPTION(wasm_execution_error, "WASM data segment outside of valid memory range");
            if(base_offset + data_segment.data.size() > mem_image.size())
               mem_image.resize(base_offset + data_segment.data.size(), 0x00);
            memcpy(mem_image.data() + base_offset, data_segment.data.data(), data_segment.data.size());
         }

         return mem_image;
      }

      void code_block_num_last_used(const digest_type& code_hash, const uint8_t& vm_type, const uint8_t& vm_version, const uint32_t& block_num) {
         wasm_cache_index::iterator it = wasm_instantiation_cache.find(boost::make_tuple(code_hash, vm_type, vm_version));
         if(it != wasm_instantiation_cache.end())
            wasm_instantiation_cache.modify(it, [block_num](wasm_cache_entry& e) {
               e.last_block_num_used = block_num;
            });
      }

      void current_lib(uint32_t lib) {
         //anything last used before or on the LIB can be evicted
         wasm_instantiation_cache.get<by_last_block_num>().erase(wasm_instantiation_cache.get<by_last_block_num>().begin(), wasm_instantiation_cache.get<by_last_block_num>().upper_bound(lib));
      }

      const std::unique_ptr<wasm_instantiated_module_interface>& get_instantiated_module( const digest_type& code_hash, const uint8_t& vm_type,
                                                                                const uint8_t& vm_version, transaction_context& trx_context, bool inject )
      {
         wasm_cache_index::iterator it = wasm_instantiation_cache.find(
                                             boost::make_tuple(code_hash, vm_type, vm_version) );
         const code_object* codeobject = nullptr;
         if(it == wasm_instantiation_cache.end()) {
            codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));

            it = wasm_instantiation_cache.emplace( wasm_interface_impl::wasm_cache_entry{
                                                      .code_hash = code_hash,
                                                      .first_block_num_used = codeobject->first_block_used,
                                                      .last_block_num_used = UINT32_MAX,
                                                      .module = nullptr,
                                                      .vm_type = vm_type,
                                                      .vm_version = vm_version
                                                   } ).first;
         }

         if(!it->module) {
            if(!codeobject)
               codeobject = &db.get<code_object,by_code_hash>(boost::make_tuple(code_hash, vm_type, vm_version));

            auto timer_pause = fc::make_scoped_exit([&](){
               trx_context.resume_billing_timer();
            });
            trx_context.pause_billing_timer();
            IR::Module module;
	    std::vector<U8> bytes = {(const U8*)codeobject->code.data(), (const U8*)codeobject->code.data() + codeobject->code.size()};
            try {
               Serialization::MemoryInputStream stream((const U8*)bytes.data(), bytes.size());
               WASM::serialize(stream, module);
               module.userSections.clear();
            } catch(const Serialization::FatalSerializationException& e) {
               EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
            } catch(const IR::ValidationException& e) {
               EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
            }
            if(false && inject) {
               wasm_injections::wasm_binary_injection injector(module);
               injector.inject();
               std::cout << "INJECTING!!!!!!!!!!!!\n";
               try {
                  Serialization::ArrayOutputStream outstream;
                  WASM::serialize(outstream, module);
                  bytes = outstream.getBytes();
               } catch(const Serialization::FatalSerializationException& e) {
                  EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
               } catch(const IR::ValidationException& e) {
                  EOS_ASSERT(false, wasm_serialization_error, e.message.c_str());
               }
	    }

            wasm_instantiation_cache.modify(it, [&](auto& c) {
               c.module = runtime_interface->instantiate_module((const char*)bytes.data(), bytes.size(), parse_initial_memory(module));
            });
         }
         return it->module;
      }

      bool is_shutting_down = false;
      std::unique_ptr<wasm_runtime_interface> runtime_interface;
      wasm_interface::vm_type runtime;

      typedef boost::multi_index_container<
         wasm_cache_entry,
         indexed_by<
            ordered_unique<tag<by_hash>,
               composite_key< wasm_cache_entry,
                  member<wasm_cache_entry, digest_type, &wasm_cache_entry::code_hash>,
                  member<wasm_cache_entry, uint8_t,     &wasm_cache_entry::vm_type>,
                  member<wasm_cache_entry, uint8_t,     &wasm_cache_entry::vm_version>
               >
            >,
            ordered_non_unique<tag<by_first_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::first_block_num_used>>,
            ordered_non_unique<tag<by_last_block_num>, member<wasm_cache_entry, uint32_t, &wasm_cache_entry::last_block_num_used>>
         >
      > wasm_cache_index;
      wasm_cache_index wasm_instantiation_cache;

      const chainbase::database& db;
   };

#define _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
   _REGISTER_WAVM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)         \
   _REGISTER_WABT_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)         \
   _REGISTER_EOS_VM_INTRINSIC(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)

#define _REGISTER_INTRINSIC4(CLS, MOD, METHOD, WASM_SIG, NAME, SIG)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, SIG )

#define _REGISTER_INTRINSIC3(CLS, MOD, METHOD, WASM_SIG, NAME)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, NAME, decltype(&CLS::METHOD) )

#define _REGISTER_INTRINSIC2(CLS, MOD, METHOD, WASM_SIG)\
   _REGISTER_INTRINSIC_EXPLICIT(CLS, MOD, METHOD, WASM_SIG, BOOST_PP_STRINGIZE(METHOD), decltype(&CLS::METHOD) )

#define _REGISTER_INTRINSIC1(CLS, MOD, METHOD)\
   static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":" BOOST_PP_STRINGIZE(METHOD) " without a signature");

#define _REGISTER_INTRINSIC0(CLS, MOD, METHOD)\
   static_assert(false, "Cannot register " BOOST_PP_STRINGIZE(CLS) ":<unknown> without a method name and signature");

#define _UNWRAP_SEQ(...) __VA_ARGS__

#define _EXPAND_ARGS(CLS, MOD, INFO)\
   ( CLS, MOD, _UNWRAP_SEQ INFO )

#define _REGISTER_INTRINSIC(R, CLS, INFO)\
   BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, "env", INFO), BOOST_PP_EMPTY())

#define REGISTER_INTRINSICS(CLS, MEMBERS)\
   BOOST_PP_SEQ_FOR_EACH(_REGISTER_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))

#define _REGISTER_INJECTED_INTRINSIC(R, CLS, INFO)\
   BOOST_PP_CAT(BOOST_PP_OVERLOAD(_REGISTER_INTRINSIC, _UNWRAP_SEQ INFO) _EXPAND_ARGS(CLS, EOSIO_INJECTED_MODULE_NAME, INFO), BOOST_PP_EMPTY())

#define REGISTER_INJECTED_INTRINSICS(CLS, MEMBERS)\
   BOOST_PP_SEQ_FOR_EACH(_REGISTER_INJECTED_INTRINSIC, CLS, _WRAPPED_SEQ(MEMBERS))

} } // eosio::chain
<|endoftext|>


<commit_before>#include "bittorrent/ui/platforms/IOS.h"

#if BT_IOS

#import <UIKit/UIAlertView.h>
#import <UIKit/UIApplication.h>

@interface AlertViewHelper : NSObject<UIAlertViewDelegate>
    typedef void(^CompletionHandler)(NSInteger buttonIndex);
    @property (strong,nonatomic) CompletionHandler completionHandler;

    + (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler;
@end

@implementation AlertViewHelper
    + (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler {
        __block AlertViewHelper* delegate = [AlertViewHelper new];
        alertView.delegate = delegate;
        delegate.completionHandler = ^(NSInteger buttonIndex) {
            handler(buttonIndex);
            alertView.delegate = nil;
            delegate = nil;
        };
        [alertView show];
    }

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        self.completionHandler(buttonIndex);
    }
@end

namespace bittorrent {
namespace ui {
namespace platforms {

bool IOS::canOpenURL(const char* url) const {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}

bool IOS::openURL(const char* url) {
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}

void IOS::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) {
    UIAlertView* alert = [UIAlertView new];
    alert.title = [NSString stringWithUTF8String:title];
    alert.message = [NSString stringWithUTF8String:message];
    for (auto& button : buttons) {
        [alert addButtonWithTitle:[NSString stringWithUTF8String:button.c_str()]];
    }
    [AlertViewHelper showAlertView:alert withCompletionHandler:^(NSInteger buttonIndex) {
        action(buttonIndex);
    }];
}

}}}

#endif
<commit_msg>suppress warning<commit_after>#include "bittorrent/ui/platforms/IOS.h"

#if BT_IOS

#import <UIKit/UIAlertView.h>
#import <UIKit/UIApplication.h>

@interface AlertViewHelper : NSObject<UIAlertViewDelegate>
    typedef void(^CompletionHandler)(NSInteger buttonIndex);
    @property (strong,nonatomic) CompletionHandler completionHandler;

    + (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler;
@end

@implementation AlertViewHelper
    + (void)showAlertView:(UIAlertView*)alertView withCompletionHandler:(CompletionHandler)handler {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-retain-cycles"
        __block AlertViewHelper* delegate = [AlertViewHelper new];
        alertView.delegate = delegate;
        delegate.completionHandler = ^(NSInteger buttonIndex) {
            handler(buttonIndex);
            alertView.delegate = nil;
            delegate = nil;
        };
        [alertView show];
        #pragma clang diagnostic pop
    }

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        self.completionHandler(buttonIndex);
    }
@end

namespace bittorrent {
namespace ui {
namespace platforms {

bool IOS::canOpenURL(const char* url) const {
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}

bool IOS::openURL(const char* url) {
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String:url]]];
}

void IOS::openDialog(Window* window, const char* title, const char* message, const std::vector<std::string>& buttons, std::function<void(int)> action) {
    UIAlertView* alert = [UIAlertView new];
    alert.title = [NSString stringWithUTF8String:title];
    alert.message = [NSString stringWithUTF8String:message];
    for (auto& button : buttons) {
        [alert addButtonWithTitle:[NSString stringWithUTF8String:button.c_str()]];
    }
    [AlertViewHelper showAlertView:alert withCompletionHandler:^(NSInteger buttonIndex) {
        action(buttonIndex);
    }];
}

}}}

#endif
<|endoftext|>


<commit_before>
/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Windows4Root.h"
#include "TWin32SplashThread.h"

TWin32SplashThread *gSplash = 0;

extern void CreateSplash(DWORD time, BOOL extended);
extern void DestroySplashScreen();

//______________________________________________________________________________
static DWORD WINAPI HandleSplashThread(LPVOID extended)
{
   // thread for handling Splash Screen

   CreateSplash(4, (Bool_t)extended);
   ::ExitThread(0);
   if (gSplash) delete gSplash;
   gSplash = 0;
   return 0;
}

//______________________________________________________________________________
TWin32SplashThread::TWin32SplashThread(Bool_t extended)
{
   // ctor.
   fHandle = 0;
   DWORD splashId = 0;
   fHandle = ::CreateThread( NULL, 0,&HandleSplashThread, (LPVOID)extended, 0, &splashId );
   gSplash = this;
}

//______________________________________________________________________________
TWin32SplashThread::~TWin32SplashThread()
{
   // dtor

   DestroySplashScreen();
   TerminateThread(fHandle, 0);
   if (fHandle) ::CloseHandle(fHandle);
   fHandle = 0;
}

<commit_msg>From Axel: in C++ "return" is better than ExitThread. Says MS. And who are we to doubt that!<commit_after>
/*************************************************************************
 * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Windows4Root.h"
#include "TWin32SplashThread.h"

TWin32SplashThread *gSplash = 0;

extern void CreateSplash(DWORD time, BOOL extended);
extern void DestroySplashScreen();

//______________________________________________________________________________
static DWORD WINAPI HandleSplashThread(LPVOID extended)
{
   // thread for handling Splash Screen

   CreateSplash(4, (Bool_t)extended);
   if (gSplash) delete gSplash;
   gSplash = 0;
   return 0;
}

//______________________________________________________________________________
TWin32SplashThread::TWin32SplashThread(Bool_t extended)
{
   // ctor.
   fHandle = 0;
   DWORD splashId = 0;
   fHandle = ::CreateThread( NULL, 0,&HandleSplashThread, (LPVOID)extended, 0, &splashId );
   gSplash = this;
}

//______________________________________________________________________________
TWin32SplashThread::~TWin32SplashThread()
{
   // dtor

   DestroySplashScreen();
   TerminateThread(fHandle, 0);
   if (fHandle) ::CloseHandle(fHandle);
   fHandle = 0;
}

<|endoftext|>


<commit_before>#include "Card.h"
#include "Deck.h"

int main() {

	// Instantiate deck of cards

	Deck *d = new Deck();

	// Pick a card from the deck
	string noCards;

	// 1 or 2 character number
	const regex reg("\\d{1,2}");

	while (true) {

		cout << "How many cards (1-52): " << flush;

		getline(cin, noCards);

		// Validate user input
		const bool result = regex_match(noCards, reg);

		if (result)
		{
			int iNoCards = atoi(noCards.c_str());
			for (unsigned int i = 0; i < iNoCards; ++i) {
				d->pickCard();
			}
		}
		else
		{
			cout << "Number 1-25 please" << endl;
		}

		cin.clear();

		if (noCards == "0") { break; }

	}

	//cin.get();

	delete d;

	return 0;
}<commit_msg>Improved support for user input<commit_after>#include "Card.h"
#include "Deck.h"

bool validEntry(string *nC, unsigned int *iC){

	// 1 or 2 character number regex pattern
	const regex reg("\\d{1,2}");

	// Validate user input
	bool valid = regex_match(*nC, reg);

	const string s = *nC;
	*iC = atoi(s.c_str());

	if (*iC > 52) { valid = false; }

	return valid;
}

int main() {

	// Instantiate deck of cards

	Deck *d = new Deck();

	// Pick a card from the deck
	string noCards;
	string *nC = &noCards;

	// integer for valid result
	unsigned int iNoCards;
	unsigned int *iN = &iNoCards;

	while (true) {

		d->getDeck();

		cout << "How many cards (1-52): " << flush;

		getline(cin, *nC);

		if (validEntry(nC, iN))
		{
			for (unsigned int i = 0; i < *iN; ++i) {
				d->pickCard();
			}
		}
		else
		{
			cout << "Number 1-25 please" << endl;
		}

		cin.clear();

		if (noCards == "0") { break; }

	}

	delete d;

	return 0;
}<|endoftext|>


<commit_before>/// \file ROOT/RHistBufferedFill.h
/// \ingroup Hist ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_RHistBufferedFill
#define ROOT7_RHistBufferedFill

#include "ROOT/RSpan.hxx"

namespace ROOT {
namespace Experimental {

namespace Internal {
template <class DERIVED, class HIST, int SIZE>
class RHistBufferedFillBase {
public:
   using CoordArray_t = typename HIST::CoordArray_t;
   using Weight_t = typename HIST::Weight_t;

private:
   size_t fCursor = 0;
   std::array<CoordArray_t, SIZE> fXBuf;
   std::array<Weight_t, SIZE> fWBuf;

public:
   RHistBufferedFillBase() {}
   ~RHistBufferedFillBase() { toDerived().Flush(); }

   DERIVED &toDerived() { return *static_cast<DERIVED *>(this); }
   const DERIVED &toDerived() const { return *static_cast<const DERIVED *>(this); }

   std::span<const CoordArray_t> GetCoords() const
   {
      return std::span<const CoordArray_t>(fXBuf.begin(), fXBuf.begin() + fCursor);
   }
   std::span<const Weight_t> GetWeights() const
   {
      return std::span<const Weight_t>(fWBuf.begin(), fWBuf.begin() + fCursor);
   }

   void Fill(const CoordArray_t &x, Weight_t weight = 1.)
   {
      fXBuf[fCursor] = x;
      fWBuf[fCursor++] = weight;
      if (fCursor == SIZE) {
         Flush();
      }
   }

   void Flush() {
      toDerived().FlushImpl();
      fCursor = 0;
   }
};

} // namespace Internal

/** \class RHistBufferedFill
 Buffers calls to Fill().

 Once the buffer is full, on destruction of when calling Flush(), it sends the
 buffers off as an ideally vectorizable FillN() operation. It also serves as a
 multi-threaded way of filling the same histogram, reducing the locking
 frequency.

 The HIST template can be either a RHist instance, a RHistImpl instance, or
 a RHistLockedFill instance.
 **/

template <class HIST, int SIZE = 1024>
class RHistBufferedFill: public Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE> {
public:
   using Hist_t = HIST;
   using CoordArray_t = typename HIST::CoordArray_t;
   using Weight_t = typename HIST::Weight_t;

private:
   HIST &fHist;
   size_t fCursor = 0;
   std::array<CoordArray_t, SIZE> fXBuf;
   std::array<Weight_t, SIZE> fWBuf;

   friend class Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE>;
   void FlushImpl() { fHist.FillN(this->GetCoords(), this->GetWeights()); }

public:
   RHistBufferedFill(Hist_t &hist): fHist{hist} {}

   void FillN(const std::span<const CoordArray_t> xN, const std::span<const Weight_t> weightN)
   {
      fHist.FillN(xN, weightN);
   }

   void FillN(const std::span<const CoordArray_t> xN) { fHist.FillN(xN); }

   HIST &GetHist()
   {
      this->Flush(); // synchronize!
      return fHist;
   }
   operator HIST &() { return GetHist(); }

   static constexpr int GetNDim() { return HIST::GetNDim(); }
};
} // namespace Experimental
} // namespace ROOT

#endif
<commit_msg>Do not duplicate RHistBufferedFillBase data members in RHistBufferedFill<commit_after>/// \file ROOT/RHistBufferedFill.h
/// \ingroup Hist ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-07-03
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT7_RHistBufferedFill
#define ROOT7_RHistBufferedFill

#include "ROOT/RSpan.hxx"

namespace ROOT {
namespace Experimental {

namespace Internal {
template <class DERIVED, class HIST, int SIZE>
class RHistBufferedFillBase {
public:
   using CoordArray_t = typename HIST::CoordArray_t;
   using Weight_t = typename HIST::Weight_t;

private:
   size_t fCursor = 0;
   std::array<CoordArray_t, SIZE> fXBuf;
   std::array<Weight_t, SIZE> fWBuf;

public:
   RHistBufferedFillBase() {}
   ~RHistBufferedFillBase() { toDerived().Flush(); }

   DERIVED &toDerived() { return *static_cast<DERIVED *>(this); }
   const DERIVED &toDerived() const { return *static_cast<const DERIVED *>(this); }

   std::span<const CoordArray_t> GetCoords() const
   {
      return std::span<const CoordArray_t>(fXBuf.begin(), fXBuf.begin() + fCursor);
   }
   std::span<const Weight_t> GetWeights() const
   {
      return std::span<const Weight_t>(fWBuf.begin(), fWBuf.begin() + fCursor);
   }

   void Fill(const CoordArray_t &x, Weight_t weight = 1.)
   {
      fXBuf[fCursor] = x;
      fWBuf[fCursor++] = weight;
      if (fCursor == SIZE) {
         Flush();
      }
   }

   void Flush() {
      toDerived().FlushImpl();
      fCursor = 0;
   }
};

} // namespace Internal

/** \class RHistBufferedFill
 Buffers calls to Fill().

 Once the buffer is full, on destruction of when calling Flush(), it sends the
 buffers off as an ideally vectorizable FillN() operation. It also serves as a
 multi-threaded way of filling the same histogram, reducing the locking
 frequency.

 The HIST template can be either a RHist instance, a RHistImpl instance, or
 a RHistLockedFill instance.
 **/

template <class HIST, int SIZE = 1024>
class RHistBufferedFill: public Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE> {
public:
   using Hist_t = HIST;
   using CoordArray_t = typename HIST::CoordArray_t;
   using Weight_t = typename HIST::Weight_t;

private:
   HIST &fHist;

   friend class Internal::RHistBufferedFillBase<RHistBufferedFill<HIST, SIZE>, HIST, SIZE>;
   void FlushImpl() { fHist.FillN(this->GetCoords(), this->GetWeights()); }

public:
   RHistBufferedFill(Hist_t &hist): fHist{hist} {}

   void FillN(const std::span<const CoordArray_t> xN, const std::span<const Weight_t> weightN)
   {
      fHist.FillN(xN, weightN);
   }

   void FillN(const std::span<const CoordArray_t> xN) { fHist.FillN(xN); }

   HIST &GetHist()
   {
      this->Flush(); // synchronize!
      return fHist;
   }
   operator HIST &() { return GetHist(); }

   static constexpr int GetNDim() { return HIST::GetNDim(); }
};
} // namespace Experimental
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>#include <SofaTest/Python_test.h>
#include <sofa/helper/system/FileSystem.h>

namespace sofa {

static bool ends_with(const std::string& suffix, const std::string& full){
    const std::size_t lf = full.length();
    const std::size_t ls = suffix.length();

    if(lf < ls) return false;

    return (0 == full.compare(lf - ls, ls, suffix));
}

static bool starts_with(const std::string& prefix, const std::string& full){
    const std::size_t lf = full.length();
    const std::size_t lp = prefix.length();

    if(lf < lp) return false;

    return (0 == full.compare(0, lp, prefix));
}

static bool is_scene_file(const std::string& filename) {
    return starts_with("scene_", filename) && ends_with(".py", filename);
}

static bool is_test_file(const std::string& filename) {
    return starts_with("test_", filename) && ends_with(".py", filename);
}

// these are sofa scenes
static struct Tests : public Python_test_list
{
    Tests()
    {
        static const std::string scenePath = std::string(COMPLIANT_TEST_PYTHON_DIR);

        std::vector<std::string> files;
        helper::system::FileSystem::listDirectory(scenePath, files);

        for(const std::string& file : files) {
            if(is_scene_file(file) ) {
                addTest(file, scenePath);
            }
        }

    }
} tests;

// run test list
INSTANTIATE_TEST_CASE_P(Batch,
                        Python_scene_test,
                        ::testing::ValuesIn(tests.list));

TEST_P(Python_scene_test, sofa_python_scene_tests)
{
    run(GetParam());
}

////////////////////////

// these are just python files loaded in the sofa python environment (paths...)
static struct Tests2 : public Python_test_list
{
    Tests2()
    {
        static const std::string testPath = std::string(COMPLIANT_TEST_PYTHON_DIR);

        std::vector<std::string> files;
        helper::system::FileSystem::listDirectory(testPath, files);

        for(const std::string& file : files) {
            if(is_test_file(file) ) {
                addTest(file, testPath);
            }
        }

    }
} tests2;

// run test list
INSTANTIATE_TEST_CASE_P(Batch,
                        Python_test,
                        ::testing::ValuesIn(tests2.list));

TEST_P(Python_test, sofa_python_tests)
{
    run(GetParam());
}

} // namespace sofa
<commit_msg>[Compliant] use SofaTest test list from dir<commit_after>#include <SofaTest/Python_test.h>
#include <sofa/helper/system/FileSystem.h>

namespace sofa {

// these are sofa scenes
static struct Tests : public Python_test_list {
    Tests() {
        addTestDir(COMPLIANT_TEST_PYTHON_DIR, "scene_");

    }
} tests;

// run test list
INSTANTIATE_TEST_CASE_P(Batch,
                        Python_scene_test,
                        ::testing::ValuesIn(tests.list));

TEST_P(Python_scene_test, sofa_python_scene_tests)
{
    run(GetParam());
}

////////////////////////

// these are just python files loaded in the sofa python environment (paths...)
static struct Tests2 : public Python_test_list {
    Tests2() {
        addTestDir(COMPLIANT_TEST_PYTHON_DIR, "test_");
    }
} tests2;

// run test list
INSTANTIATE_TEST_CASE_P(Batch,
                        Python_test,
                        ::testing::ValuesIn(tests2.list));

TEST_P(Python_test, sofa_python_tests)
{
    run(GetParam());
}

} // namespace sofa
<|endoftext|>


<commit_before>#ifndef VFRENDERING_ISOSURFACE_RENDERER_H
#define VFRENDERING_ISOSURFACE_RENDERER_H

#include <functional>

#include <VFRendering/RendererBase.hxx>

namespace VFRendering {
class IsosurfaceRenderer : public RendererBase {
public:
    enum Option {
        ISOVALUE = 700,
        VALUEFUNCTION
    };

    IsosurfaceRenderer(const View& view);
    virtual ~IsosurfaceRenderer();
    virtual void update(bool keep_geometry) override;
    virtual void draw(float aspect_ratio) const override;
    virtual void optionsHaveChanged(const std::vector<int>& changed_options) override;

private:
    void updateShaderProgram();
    void updateIsosurfaceIndices();

    unsigned int m_program = 0;
    unsigned int m_vao = 0;
    unsigned int m_ibo = 0;
    unsigned int m_position_vbo = 0;
    unsigned int m_direction_vbo = 0;
    unsigned int m_num_indices = 0;
};
}

template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::ISOVALUE> {
    double default_value = 0;
};

template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::VALUEFUNCTION> {
    std::function<float(const glm::vec3&, const glm::vec3&)> default_value = [] (const glm::vec3& position, const glm::vec3& direction) {
        (void)direction;
        return position.x+position.y;
    };
};

#endif
<commit_msg>Set default value function back to direction.z<commit_after>#ifndef VFRENDERING_ISOSURFACE_RENDERER_H
#define VFRENDERING_ISOSURFACE_RENDERER_H

#include <functional>

#include <VFRendering/RendererBase.hxx>

namespace VFRendering {
class IsosurfaceRenderer : public RendererBase {
public:
    enum Option {
        ISOVALUE = 700,
        VALUEFUNCTION
    };

    IsosurfaceRenderer(const View& view);
    virtual ~IsosurfaceRenderer();
    virtual void update(bool keep_geometry) override;
    virtual void draw(float aspect_ratio) const override;
    virtual void optionsHaveChanged(const std::vector<int>& changed_options) override;

private:
    void updateShaderProgram();
    void updateIsosurfaceIndices();

    unsigned int m_program = 0;
    unsigned int m_vao = 0;
    unsigned int m_ibo = 0;
    unsigned int m_position_vbo = 0;
    unsigned int m_direction_vbo = 0;
    unsigned int m_num_indices = 0;
};
}

template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::ISOVALUE> {
    double default_value = 0;
};

template<>
struct VFRendering::Option<VFRendering::IsosurfaceRenderer::Option::VALUEFUNCTION> {
    std::function<float(const glm::vec3&, const glm::vec3&)> default_value = [] (const glm::vec3& position, const glm::vec3& direction) {
        (void)position;
        return direction.z;
    };
};

#endif
<|endoftext|>


<commit_before>#ifndef CLOTHO_ITERATOR_HELPER_HPP_
#define CLOTHO_ITERATOR_HELPER_HPP_

#include "clotho/utility/element_iterator.hpp"

namespace clotho {
namespace utility {

template < class Container >
struct iterator_helper {
    typedef clotho::utility::element_iterator< Container > type;

    static type make_first( Container & con ) {
        return type( con );
    }

    static type make_second( Container & con ) {
        return type( con );
    }
};

template < class Element >
struct iterator_helper< std::pair< Element, Element > > {
    typedef element_iterator< std::pair< Element, Element > > type;

    static type    make_first( std::pair< Element, Element > & ind ) {
        return element_iterator< Element >( ind, pair_iterator_state::FIRST);
    }

    static type    make_last( std::pair< Element, Element > & ind ) {
        return element_iterator< Element >( ind );
    }
};

#include <memory>

template < class Element >
struct iterator_helper< std::shared_ptr< Element > > {
    typedef typename iterator_helper< Element >::type type;

    static type make_first( std::shared_ptr< Element > s ) {
        return iterator_helper< Element >::make_first( *s );
    }

    static type make_last( std::shared_ptr< Element > s ) {
        return iterator_helper< Element >::make_last( *s );
    }
};

}   // namespace utility {
}   // namespace clotho {

#endif  // CLOTHO_ITERATOR_HELPER_HPP_
<commit_msg>slight changes to helpers<commit_after>#ifndef CLOTHO_ITERATOR_HELPER_HPP_
#define CLOTHO_ITERATOR_HELPER_HPP_

#include "clotho/utility/element_iterator.hpp"

namespace clotho {
namespace utility {

template < class Container >
struct iterator_helper {
    typedef clotho::utility::element_iterator< Container > type;

    static type make_first( Container & con ) {
        return type( con );
    }

    static type make_last( Container & con ) {
        return type( con );
    }
};

template < class Element >
struct iterator_helper< std::pair< Element, Element > > {
    typedef clotho::utility::element_iterator< std::pair< Element, Element > > type;

    static type    make_first( std::pair< Element, Element > & ind ) {
        return type( ind, pair_iterator_state::FIRST);
    }

    static type    make_last( std::pair< Element, Element > & ind ) {
        return type( ind );
    }
};

template < class Element >
struct iterator_helper< std::shared_ptr< Element > > :
    public iterator_helper< Element >
{
    typedef iterator_helper< Element > base_type;
    typedef typename base_type::type type;

    static type make_first( std::shared_ptr< Element > s ) {
        return base_type::make_first( *s );
    }

    static type make_last( std::shared_ptr< Element > s ) {
        return base_type::make_last( *s );
    }
};

}   // namespace utility {
}   // namespace clotho {

#endif  // CLOTHO_ITERATOR_HELPER_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GLOBAL_CONFIG_PARSER_HPP
#define RJ_GLOBAL_CONFIG_PARSER_HPP

#include <string>
#include <utility>
#include <vector>

namespace rj
{
	using config_entry = std::pair<std::string, std::string>;
	using config_entry_vec = std::vector<config_entry>;

	class config_parser
	{
		const std::vector<std::string>& m_content;
		config_entry_vec m_entrys;

	public:
		config_parser(const std::vector<std::string>& content) :
			m_content{content}
		{this->parse();}

		auto get_entrys() const noexcept
		-> const decltype(m_entrys)&
		{return m_entrys;}

	private:
		void parse() noexcept
		{
			for(auto& a : m_content)
			{
				auto pos_equ(a.find('='));
				if(pos_equ != std::string::npos)
				{
					auto pair(std::make_pair(a.substr(0, pos_equ), a.substr(pos_equ + 1, a.size() - pos_equ - 1)));
					if(!pair.first.empty() && !pair.second.empty())
						m_entrys.push_back(pair);
				}
			}
		}
	};
}

#endif // RJ_GLOBAL_CONFIG_PARSER_HPP
<commit_msg>config_parser: added empty()<commit_after>//
// Copyright (c) 2013 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GLOBAL_CONFIG_PARSER_HPP
#define RJ_GLOBAL_CONFIG_PARSER_HPP

#include <string>
#include <utility>
#include <vector>

namespace rj
{
	using config_entry = std::pair<std::string, std::string>;
	using config_entry_vec = std::vector<config_entry>;

	class config_parser
	{
		const std::vector<std::string>& m_content;
		config_entry_vec m_entrys;

	public:
		config_parser(const std::vector<std::string>& content) :
			m_content{content}
		{this->parse();}

		auto get_entrys() const noexcept
		-> const decltype(m_entrys)&
		{return m_entrys;}

		bool empty() const noexcept
		{return m_entrys.empty();}

	private:
		void parse() noexcept
		{
			for(auto& a : m_content)
			{
				auto pos_equ(a.find('='));
				if(pos_equ != std::string::npos)
				{
					auto pair(std::make_pair(a.substr(0, pos_equ), a.substr(pos_equ + 1, a.size() - pos_equ - 1)));
					if(!pair.first.empty() && !pair.second.empty())
						m_entrys.push_back(pair);
				}
			}
		}
	};
}

#endif // RJ_GLOBAL_CONFIG_PARSER_HPP
<|endoftext|>


<commit_before>/*
 *	This file is part of qpOASES.
 *
 *	qpOASES -- An Implementation of the Online Active Set Strategy.
 *	Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
 *	Christian Kirches et al. All rights reserved.
 *
 *	qpOASES is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	qpOASES is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *	See the GNU Lesser General Public License for more details.
 *
 *	You should have received a copy of the GNU Lesser General Public
 *	License along with qpOASES; if not, write to the Free Software
 *	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/**
 *	\file interfaces/matlab/qpOASES_matlab_utils.hpp
 *	\author Hans Joachim Ferreau, Alexander Buchner
 *	\version 3.2
 *	\date 2007-2015
 *
 *	Collects utility functions for Interface to Matlab(R) that
 *	enables to call qpOASES as a MEX function.
 *
 */

/* Work-around for settings where mexErrMsgTxt causes unexpected behaviour. */
#ifdef __AVOID_MEXERRMSGTXT__
	#define myMexErrMsgTxt( TEXT ) mexPrintf( "%s\n\n",(TEXT) );
#else
	#define myMexErrMsgTxt mexErrMsgTxt
#endif

#include "mex.h"
#include "matrix.h"
#include "string.h"
#include <vector>

/*
 * QProblem instance class
 */
class QPInstance
{
	private:
		static int_t s_nexthandle;

	public:
		QPInstance(	uint_t _nV = 0,
					uint_t _nC = 0,
					HessianType _hessianType = HST_UNKNOWN,
					BooleanType _isSimplyBounded = BT_FALSE,
					BooleanType _sparseLA = BT_FALSE
					);

		~QPInstance( );

		returnValue deleteQPMatrices();

		int_t getNV() const;
		int_t getNC() const;

		int_t handle;

		SQProblem* sqp;
		QProblemB* qpb;
		BooleanType isSimplyBounded;
		BooleanType sparseLA;

		SymmetricMatrix* H;
		Matrix* A;
		sparse_int_t* Hir;
		sparse_int_t* Hjc;
		sparse_int_t* Air;
		sparse_int_t* Ajc;
		real_t* Hv;
		real_t* Av;
};

/*
 *	end of file
 */
<commit_msg>added typeinfo header to Matlab interface as suggested in ticket #49<commit_after>/*
 *	This file is part of qpOASES.
 *
 *	qpOASES -- An Implementation of the Online Active Set Strategy.
 *	Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
 *	Christian Kirches et al. All rights reserved.
 *
 *	qpOASES is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	qpOASES is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *	See the GNU Lesser General Public License for more details.
 *
 *	You should have received a copy of the GNU Lesser General Public
 *	License along with qpOASES; if not, write to the Free Software
 *	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/**
 *	\file interfaces/matlab/qpOASES_matlab_utils.hpp
 *	\author Hans Joachim Ferreau, Alexander Buchner
 *	\version 3.2
 *	\date 2007-2015
 *
 *	Collects utility functions for Interface to Matlab(R) that
 *	enables to call qpOASES as a MEX function.
 *
 */

/* Work-around for settings where mexErrMsgTxt causes unexpected behaviour. */
#ifdef __AVOID_MEXERRMSGTXT__
	#define myMexErrMsgTxt( TEXT ) mexPrintf( "%s\n\n",(TEXT) );
#else
	#define myMexErrMsgTxt mexErrMsgTxt
#endif

/* Workaround for problem on Matlab 2012b
 * see https://github.com/robotology/codyco-superbuild/issues/84
 * see http://stackoverflow.com/questions/22440523/mex-files-using-xcode-5-1-under-os-x-10-9-with-matlab-2012a/22705789#22705789 */
/* #include <typeinfo> */

#include "mex.h"
#include "matrix.h"
#include "string.h"
#include <vector>

/*
 * QProblem instance class
 */
class QPInstance
{
	private:
		static int_t s_nexthandle;

	public:
		QPInstance(	uint_t _nV = 0,
					uint_t _nC = 0,
					HessianType _hessianType = HST_UNKNOWN,
					BooleanType _isSimplyBounded = BT_FALSE,
					BooleanType _sparseLA = BT_FALSE
					);

		~QPInstance( );

		returnValue deleteQPMatrices();

		int_t getNV() const;
		int_t getNC() const;

		int_t handle;

		SQProblem* sqp;
		QProblemB* qpb;
		BooleanType isSimplyBounded;
		BooleanType sparseLA;

		SymmetricMatrix* H;
		Matrix* A;
		sparse_int_t* Hir;
		sparse_int_t* Hjc;
		sparse_int_t* Air;
		sparse_int_t* Ajc;
		real_t* Hv;
		real_t* Av;
};

/*
 *	end of file
 */
<|endoftext|>


<commit_before>#include "arduino_serial.hpp"
#include <UartInterface.hpp>

#define ARDUINO_DEFAULT_SERIAL									1

#include <stdio.h>
#include <stdlib.h>

::uart::ConcreteUart UartCommand(ARDUINO_DEFAULT_SERIAL, &::arduino::serial::uart_callback);

namespace arduino
{
	namespace serial
	{

		ArduinoSerial Serial;

		void uart_callback (const uint8_t c)
		{
			Serial.uart_receive_fifo.push_back(c);
			return;
		}

		ArduinoSerial::ArduinoSerial()
		{
			return;
		}

		void ArduinoSerial::begin(int Speed)
		{
			UartCommand.Configure();
			this->uart_receive_fifo.clear();
			return;
		}

		void ArduinoSerial::write(const char c)
		{
			UartCommand.send((const unsigned char*)&c, sizeof(c));
		}

		void ArduinoSerial::print(const char* pString)
		{
			while (*pString)
			{
				UartCommand.send((const unsigned char*)&(pString[0]), sizeof(pString[0]));
				pString++;
			}
		}

		void ArduinoSerial::print(const char c)
		{
			UartCommand.send((const unsigned char*)&c, sizeof(c));
		}

		void ArduinoSerial::print(const int c, ArduinoFormat_T format)
		{
			char Buffer[32];
			memset(Buffer, 0, sizeof(Buffer));

			if (format == DEC)
			{
				sprintf(Buffer, "%i", c);
			}
			else if (format == HEX)
			{
				sprintf(Buffer, "%x", c);
			}
			else
			{
				sprintf(Buffer, "%x", c);
			}
			this->print(Buffer);

		}

		void ArduinoSerial::print(double d, int size)
		{
			char Buffer[16];
			memset(Buffer, 0, sizeof(Buffer));

			sprintf(Buffer, "%05f", d);

			this->print(Buffer);

		}

		void ArduinoSerial::println(const char c, ArduinoFormat_T format)
		{
			this->print(c, format);
			this->println();
		}

		void ArduinoSerial::println(const char* pString)
		{
			this->print(pString);
			this->println();
		}

		void ArduinoSerial::println()
		{
			this->print("\r\n");
		}

		int ArduinoSerial::available()
		{
			return this->uart_receive_fifo.size();
		}

		unsigned char ArduinoSerial::read()
		{
			uint8_t c;
			c = this->uart_receive_fifo.front();
			this->uart_receive_fifo.pop_front();
			return c;
		}

	} //namespace serial

} //namespace arduino
<commit_msg>(ARDUINO) Fix string.h include.<commit_after>#include "arduino_serial.hpp"
#include <UartInterface.hpp>

#define ARDUINO_DEFAULT_SERIAL									1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

::uart::ConcreteUart UartCommand(ARDUINO_DEFAULT_SERIAL, &::arduino::serial::uart_callback);

namespace arduino
{
	namespace serial
	{

		ArduinoSerial Serial;

		void uart_callback (const uint8_t c)
		{
			Serial.uart_receive_fifo.push_back(c);
			return;
		}

		ArduinoSerial::ArduinoSerial()
		{
			return;
		}

		void ArduinoSerial::begin(int Speed)
		{
			UartCommand.Configure();
			this->uart_receive_fifo.clear();
			return;
		}

		void ArduinoSerial::write(const char c)
		{
			UartCommand.send((const unsigned char*)&c, sizeof(c));
		}

		void ArduinoSerial::print(const char* pString)
		{
			while (*pString)
			{
				UartCommand.send((const unsigned char*)&(pString[0]), sizeof(pString[0]));
				pString++;
			}
		}

		void ArduinoSerial::print(const char c)
		{
			UartCommand.send((const unsigned char*)&c, sizeof(c));
		}

		void ArduinoSerial::print(const int c, ArduinoFormat_T format)
		{
			char Buffer[32];
			memset(Buffer, 0, sizeof(Buffer));

			if (format == DEC)
			{
				sprintf(Buffer, "%i", c);
			}
			else if (format == HEX)
			{
				sprintf(Buffer, "%x", c);
			}
			else
			{
				sprintf(Buffer, "%x", c);
			}
			this->print(Buffer);

		}

		void ArduinoSerial::print(double d, int size)
		{
			char Buffer[16];
			memset(Buffer, 0, sizeof(Buffer));

			sprintf(Buffer, "%05f", d);

			this->print(Buffer);

		}

		void ArduinoSerial::println(const char c, ArduinoFormat_T format)
		{
			this->print(c, format);
			this->println();
		}

		void ArduinoSerial::println(const char* pString)
		{
			this->print(pString);
			this->println();
		}

		void ArduinoSerial::println()
		{
			this->print("\r\n");
		}

		int ArduinoSerial::available()
		{
			return this->uart_receive_fifo.size();
		}

		unsigned char ArduinoSerial::read()
		{
			uint8_t c;
			c = this->uart_receive_fifo.front();
			this->uart_receive_fifo.pop_front();
			return c;
		}

	} //namespace serial

} //namespace arduino
<|endoftext|>


<commit_before>#ifndef MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH

#include "simplify.hh"
#include "complex.hh"
#include "variables.hh"
#include "zero.hh"
#include "multiplication.hh"
#include "integral_polynomial.hh"

namespace manifolds {
template <class T>
struct Simplification<Composition<Real, ImagN<T> >, /*com_re_i*/ 0> {
  static auto Combine(Composition<Real, ImagN<T> >) {
    SIMPLIFY_INFO("Simplifying Real part of "
                  "non-complex function");
    return zero;
  }
};

template <class T>
struct Simplification<Composition<Imag, ImagN<T> >, /*com_im_i*/ 0> {
  static auto Combine(Composition<Imag, ImagN<T> >) {
    return GetIPolynomial<1>();
  }
};

template <class T>
struct Simplification<Composition<Real, T>, /*com_re_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Real, T> t) {
    return get<1>(t.GetFunctions());
  }
};

template <class T>
struct Simplification<Composition<Imag, T>, /*com_im_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Imag, T> t) { return zero; }
};

template <class T>
struct Simplification<Composition<Phase, T>, /*com_ph_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Phase, T> t) {
    auto t2 = get<1>(t.GetFunctions());
    return MultiplyRaw(Sign()(t2), GetPolynomial(M_PI));
  }
};

template <class T>
struct Simplification<Composition<Phase, ImagN<T> >, /*com_ph_i*/ 0> {
  static auto Combine(Composition<Phase, ImagN<T> >) {
    return GetPolynomial(M_PI);
  }
};

template <class T>
struct Simplification<Composition<Norm, ImagN<T> >, /*com_nm_i*/ 0> {
  static auto Combine(Composition<Norm, ImagN<T> >) {
    return GetIPolynomial<1>();
  }
};

template <class T>
struct Simplification<Composition<Norm, T>, /*com_nm_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Norm, T> t) {
    return GetIPolynomial<0, 0, 1>()(get<1>(t.GetFunctions()));
  }
};

template <class T>
struct Simplification<Composition<Conjugate, ImagN<T> >, /*com_con_i*/ 0> {
  static auto Combine(Composition<Conjugate, ImagN<T> >) {
    return UnaryMinus<ImagN<T> >();
  }
};

template <class T>
struct Simplification<Composition<Conjugate, T>, /*com_con_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Conjugate, T> t) {
    return get<1>(t.GetFunctions());
  }
};

template <class T, class T2, T2... cs>
struct Simplification<
    Composition<IntegralPolynomial<std::integer_sequence<T2, cs...> >,
                ImagN<T> >,
    /**/ 0, typename std::enable_if<(sizeof...(cs) > 2)>::type> {

  typedef typename std::conditional<std::is_unsigned<T2>::value,
                                    typename std::make_signed<T2>::type,
                                    T2>::type Tout;

  template <Tout c0, Tout c1, Tout... c_outs>
  static auto Add(
      int_<1>,
      IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> > p) {
    return AddRaw(
        IntegralPolynomial<std::integer_sequence<Tout, c0> >(),
        MultiplyRaw(IntegralPolynomial<std::integer_sequence<Tout, c1> >(), I));
  }

  template <Tout c0, Tout c1, Tout... c_outs, int N>
  static auto Add(
      int_<N>,
      IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> >) {
    static const Tout c0_2 =
        c0 +
        ((N % 2 == 0)
             ? ((N % 4 == 0)
                    ? nth<N - 2,
                          std::integral_constant<Tout, c_outs>...>::type::value
                    : -nth<N - 2, std::integral_constant<
                                      Tout, c_outs>...>::type::value)
             : 0);
    static const Tout c1_2 =
        c1 +
        ((N % 2 == 1)
             ? ((N % 4 == 1)
                    ? nth<N - 2,
                          std::integral_constant<Tout, c_outs>...>::type::value
                    : -nth<N - 2, std::integral_constant<
                                      Tout, c_outs>...>::type::value)
             : 0);
    return Add(int_<N - 1>(),
               IntegralPolynomial<
                   std::integer_sequence<Tout, c0_2, c1_2, c_outs...> >());
  }

  static auto Combine(Composition<
      IntegralPolynomial<std::integer_sequence<T2, cs...> >, ImagN<T> >) {
    return Add(int_<sizeof...(cs) - 1>(),
               IntegralPolynomial<std::integer_sequence<Tout, (Tout)cs...> >());
  }
};

template <class... C, class Complex>
struct Simplification<Composition<ImagN<Complex>, C...>, /*com_i_cs*/ 0> {
  static auto Combine(Composition<ImagN<Complex>, C...>) { return I; }
};

    template <class F, class ... Fs>
    struct Simplification<
        Composition<
            F, Addition<Fs...> >, /*re_add_fs*/0,
        typename std::enable_if<
            std::is_same<F, Real>::value ||
            std::is_same<F, Imag>::value
            >::type>
    {
        template <std::size_t ... is>
        static auto Combine(Composition<
                                F, Addition<Fs...> > c,
                            std::integer_sequence<
                                std::size_t, is...>)
        {
            auto t = get<1>(c.GetFunctions()).GetFunctions();
            return AddRaw((F()(get<is>(t)))...);
        }

        static auto Combine(Composition<
                                F, Addition<Fs...> > c)
        {
            return Combine(c, std::index_sequence_for<Fs...>());
        }
    };

    template <class F, class ... Fs>
    struct Simplification<
        Composition<
            F, Multiplication<Fs...> >, /*re_add_fs*/0,
        typename std::enable_if<
            std::is_same<F, Real>::value ||
            std::is_same<F, Imag>::value
            >::type>
    {
        template <std::size_t ... is>
        static auto Combine(Composition<
                                F, Multiplication<Fs...> > c,
                            std::integer_sequence<
                                std::size_t, is...>)
        {
            auto t = get<1>(c.GetFunctions()).GetFunctions();
            return MultiplyRaw((F()(get<is>(t)))...);
        }

        static auto Combine(Composition<
                                F, Multiplication<Fs...> > c)
        {
            return Combine(c, std::index_sequence_for<Fs...>());
        }
    };
}

#endif
<commit_msg>Split Real and Imag parts of multiplication into separate simplifications<commit_after>#ifndef MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH
#define MANIFOLDS_FUNCTIONS_COMPLEX_SIMPLIFICATIONS_HH

#include "simplify.hh"
#include "complex.hh"
#include "variables.hh"
#include "zero.hh"
#include "multiplication.hh"
#include "integral_polynomial.hh"

namespace manifolds {
template <class T>
struct Simplification<Composition<Real, ImagN<T> >, /*com_re_i*/ 0> {
  static auto Combine(Composition<Real, ImagN<T> >) {
    SIMPLIFY_INFO("Simplifying Real part of "
                  "non-complex function");
    return zero;
  }
};

template <class T>
struct Simplification<Composition<Imag, ImagN<T> >, /*com_im_i*/ 0> {
  static auto Combine(Composition<Imag, ImagN<T> >) {
    return GetIPolynomial<1>();
  }
};

template <class T>
struct Simplification<Composition<Real, T>, /*com_re_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Real, T> t) {
    return get<1>(t.GetFunctions());
  }
};

template <class T>
struct Simplification<Composition<Imag, T>, /*com_im_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Imag, T> t) { return zero; }
};

template <class T>
struct Simplification<Composition<Phase, T>, /*com_ph_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Phase, T> t) {
    auto t2 = get<1>(t.GetFunctions());
    return GetPolynomial(-M_PI/2, M_PI/2)(Sign()(t2));
  }
};

template <class T>
struct Simplification<Composition<Phase, ImagN<T> >, /*com_ph_i*/ 0> {
  static auto Combine(Composition<Phase, ImagN<T> >) {
    return GetPolynomial(M_PI);
  }
};

template <class T>
struct Simplification<Composition<Norm, ImagN<T> >, /*com_nm_i*/ 0> {
  static auto Combine(Composition<Norm, ImagN<T> >) {
    return GetIPolynomial<1>();
  }
};

template <class T>
struct Simplification<Composition<Norm, T>, /*com_nm_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Norm, T> t) {
    return GetIPolynomial<0, 0, 1>()(get<1>(t.GetFunctions()));
  }
};

template <class T>
struct Simplification<Composition<Conjugate, ImagN<T> >, /*com_con_i*/ 0> {
  static auto Combine(Composition<Conjugate, ImagN<T> >) {
    return UnaryMinus<ImagN<T> >();
  }
};

template <class T>
struct Simplification<Composition<Conjugate, T>, /*com_con_f*/ 1,
                      typename std::enable_if<ComplexOutputType<T>::value ==
                                              NeverComplex>::type> {
  static auto Combine(Composition<Conjugate, T> t) {
    return get<1>(t.GetFunctions());
  }
};

template <class T, class T2, T2... cs>
struct Simplification<
    Composition<IntegralPolynomial<std::integer_sequence<T2, cs...> >,
                ImagN<T> >,
    /**/ 0, typename std::enable_if<(sizeof...(cs) > 2)>::type> {

  typedef typename std::conditional<std::is_unsigned<T2>::value,
                                    typename std::make_signed<T2>::type,
                                    T2>::type Tout;

  template <Tout c0, Tout c1, Tout... c_outs>
  static auto Add(
      int_<1>,
      IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> > p) {
    return AddRaw(
        IntegralPolynomial<std::integer_sequence<Tout, c0> >(),
        MultiplyRaw(IntegralPolynomial<std::integer_sequence<Tout, c1> >(), I));
  }

  template <Tout c0, Tout c1, Tout... c_outs, int N>
  static auto Add(
      int_<N>,
      IntegralPolynomial<std::integer_sequence<Tout, c0, c1, c_outs...> >) {
    static const Tout c0_2 =
        c0 +
        ((N % 2 == 0)
             ? ((N % 4 == 0)
                    ? nth<N - 2,
                          std::integral_constant<Tout, c_outs>...>::type::value
                    : -nth<N - 2, std::integral_constant<
                                      Tout, c_outs>...>::type::value)
             : 0);
    static const Tout c1_2 =
        c1 +
        ((N % 2 == 1)
             ? ((N % 4 == 1)
                    ? nth<N - 2,
                          std::integral_constant<Tout, c_outs>...>::type::value
                    : -nth<N - 2, std::integral_constant<
                                      Tout, c_outs>...>::type::value)
             : 0);
    return Add(int_<N - 1>(),
               IntegralPolynomial<
                   std::integer_sequence<Tout, c0_2, c1_2, c_outs...> >());
  }

  static auto Combine(Composition<
      IntegralPolynomial<std::integer_sequence<T2, cs...> >, ImagN<T> >) {
    return Add(int_<sizeof...(cs) - 1>(),
               IntegralPolynomial<std::integer_sequence<Tout, (Tout)cs...> >());
  }
};

template <class... C, class Complex>
struct Simplification<Composition<ImagN<Complex>, C...>, /*com_i_cs*/ 0> {
  static auto Combine(Composition<ImagN<Complex>, C...>) { return I; }
};

    template <class F, class ... Fs>
    struct Simplification<
        Composition<
            F, Addition<Fs...> >, /*re_add_fs*/0,
        typename std::enable_if<
            std::is_same<F, Real>::value ||
            std::is_same<F, Imag>::value
            >::type>
    {
        template <std::size_t ... is>
        static auto Combine(Composition<
                                F, Addition<Fs...> > c,
                            std::integer_sequence<
                                std::size_t, is...>)
        {
            auto t = get<1>(c.GetFunctions()).GetFunctions();
            return AddRaw((F()(get<is>(t)))...);
        }

        static auto Combine(Composition<
                                F, Addition<Fs...> > c)
        {
            return Combine(c, std::index_sequence_for<Fs...>());
        }
    };

    template <class F1, class F2>
    struct Simplification<
        Composition<
            Real, Multiplication<F1, F2> >, /*re_add_fs*/0>
    {
        static auto Combine(Composition<
                                Real, Multiplication<F1,F2> > c)
        {
            auto t = get<1>(c.GetFunctions()).GetFunctions();
            auto left = get<0>(t);
            auto right = get<1>(t);
            return SubRaw(MultiplyRaw(Real()(left), Real()(right)),
                          MultiplyRaw(Imag()(left), Imag()(right)));
        }
    };

    template <class F1, class F2>
    struct Simplification<
        Composition<
            Imag, Multiplication<F1, F2> >, /*im_add_fs*/0>
    {
        static auto Combine(Composition<
                                Imag, Multiplication<F1, F2> > c)
        {
            auto t = get<1>(c.GetFunctions()).GetFunctions();
            auto left = get<0>(t);
            auto right = get<1>(t);
            return AddRaw(MultiplyRaw(Real()(left), Imag()(right)),
                          MultiplyRaw(Imag()(left), Real()(right)));
        }
    };
}

#endif
<|endoftext|>


<commit_before>/*
 @ 0xCCCCCCCC
*/

#include "tcp_connection.h"

#include <WS2tcpip.h>

#include "kbase/basic_types.h"
#include "kbase/error_exception_util.h"
#include "kbase/logging.h"

#include "winsock_ctx.h"

TcpConnection::TcpConnection()
    : state_(State::WaitConnect)
{
    Internal = 0;
    InternalHigh = 0;
    Offset = 0;
    OffsetHigh = 0;
    hEvent = nullptr;
}

void TcpConnection::Conncect(ScopedSocketHandle&& conn_socket)
{
    ENSURE(CHECK, !conn_socket_).Require("Connection socket must be empty!");

    conn_socket_ = std::move(conn_socket);

    sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    int len = sizeof(client_addr);
    getpeername(conn_socket_.get(), reinterpret_cast<sockaddr*>(&client_addr), &len);

    inet_ntop(client_addr.sin_family, &client_addr.sin_addr, client_ip_, kClientIPSize);

    printf("Connects to %s on worker %u\n", client_ip_, GetCurrentThreadId());

    ReadRequest();
}

void TcpConnection::ReadRequest()
{
    state_ = State::WaitRequest;

    buf_info_.buf = io_buf_;
    buf_info_.len = kIOBufSize;
    DWORD flags = 0;

    auto rv = WSARecv(conn_socket_.get(), &buf_info_, 1, nullptr, &flags, this, nullptr);
    if (rv == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING)) {
        LOG(WARNING) << "WSARecv() failed: " << WSAGetLastError();
        // TODO: reset.
    }
}

void TcpConnection::WriteResponse()
{
    state_ = State::WaitResponse;
}

void TcpConnection::Disconnect()
{
    state_ = State::WaitReset;
    //winsock_ctx::DisconnectEx(conn_socket_.get(), this, 0, 0);
    conn_socket_.reset();
}

void TcpConnection::OnIOComplete(int64_t bytes_transferred)
{
    switch (state_) {
        case State::WaitRequest:
            OnReadRequestComplete(bytes_transferred);
            break;

        case State::WaitReset:
            OnDisconnectComplete();

        default:
            ENSURE(CHECK, kbase::NotReached())(kbase::enum_cast(state_)).Require();
            break;
    }
}

void TcpConnection::OnReadRequestComplete(int64_t bytes_transferred)
{
    if (bytes_transferred == 0) {
        Disconnect();
        return;
    }

    // TODO: implement request parse.

    std::string msg(io_buf_, bytes_transferred);

    printf("-> %s\n", msg.c_str());

    ReadRequest();
}

void TcpConnection::OnDisconnectComplete()
{
    printf("Client %s disconnected! on worker %u\n", client_ip_, GetCurrentThreadId());

    conn_socket_.reset();

    state_ = State::WaitConnect;
}

<commit_msg>Fix disconnection transition<commit_after>/*
 @ 0xCCCCCCCC
*/

#include "tcp_connection.h"

#include <WS2tcpip.h>

#include "kbase/basic_types.h"
#include "kbase/error_exception_util.h"
#include "kbase/logging.h"

#include "winsock_ctx.h"

TcpConnection::TcpConnection()
    : state_(State::WaitConnect)
{
    Internal = 0;
    InternalHigh = 0;
    Offset = 0;
    OffsetHigh = 0;
    hEvent = nullptr;
}

void TcpConnection::Conncect(ScopedSocketHandle&& conn_socket)
{
    ENSURE(CHECK, !conn_socket_).Require("Connection socket must be empty!");

    conn_socket_ = std::move(conn_socket);

    sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    int len = sizeof(client_addr);
    getpeername(conn_socket_.get(), reinterpret_cast<sockaddr*>(&client_addr), &len);

    inet_ntop(client_addr.sin_family, &client_addr.sin_addr, client_ip_, kClientIPSize);

    printf("Connects to %s on worker %u\n", client_ip_, GetCurrentThreadId());

    ReadRequest();
}

void TcpConnection::ReadRequest()
{
    state_ = State::WaitRequest;

    buf_info_.buf = io_buf_;
    buf_info_.len = kIOBufSize;
    DWORD flags = 0;

    auto rv = WSARecv(conn_socket_.get(), &buf_info_, 1, nullptr, &flags, this, nullptr);
    if (rv == SOCKET_ERROR && (WSAGetLastError() != ERROR_IO_PENDING)) {
        LOG(WARNING) << "WSARecv() failed: " << WSAGetLastError();
        // TODO: reset.
    }
}

void TcpConnection::WriteResponse()
{
    state_ = State::WaitResponse;
}

void TcpConnection::Disconnect()
{
    state_ = State::WaitReset;
    winsock_ctx::DisconnectEx(conn_socket_.get(), this, 0, 0);
}

void TcpConnection::OnIOComplete(int64_t bytes_transferred)
{
    switch (state_) {
        case State::WaitRequest:
            OnReadRequestComplete(bytes_transferred);
            break;

        case State::WaitReset:
            OnDisconnectComplete();
            break;

        default:
            ENSURE(CHECK, kbase::NotReached())(kbase::enum_cast(state_)).Require();
            break;
    }
}

void TcpConnection::OnReadRequestComplete(int64_t bytes_transferred)
{
    if (bytes_transferred == 0) {
        Disconnect();
        return;
    }

    // TODO: implement request parse.

    std::string msg(io_buf_, bytes_transferred);

    printf("-> %s\n", msg.c_str());

    ReadRequest();
}

void TcpConnection::OnDisconnectComplete()
{
    printf("Client %s disconnected on worker %u!\n", client_ip_, GetCurrentThreadId());

    conn_socket_.reset();

    state_ = State::WaitConnect;
}
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   DMCreditsController.cpp
 * Author: demensdeum
 *
 * Created on April 17, 2017, 11:46 PM
 */

#include "DMCreditsController.h"

#include <FlameSteelEngineGameToolkit/Data/Components/FSEGTFactory.h>

DMCreditsController::DMCreditsController() {

}

DMCreditsController::DMCreditsController(const DMCreditsController& orig) {
}

void DMCreditsController::beforeStart() {

    auto demensdeumLogo = std::make_shared<FSEObject>();

    auto model = FSEGTFactory::makeModelComponent(std::make_shared<string>("./data/graphics/models/cube/cube.bam"), 1, 1, 1);

    demensdeumLogo->addComponent(model);

    this->gameData->getGameObjects()->addObject(demensdeumLogo);
}

void DMCreditsController::step() {

    renderer->render(this->gameData);

}

DMCreditsController::~DMCreditsController() {
}

<commit_msg>Position and scale<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   DMCreditsController.cpp
 * Author: demensdeum
 *
 * Created on April 17, 2017, 11:46 PM
 */

#include "DMCreditsController.h"

#include <FlameSteelEngineGameToolkit/Data/Components/FSEGTFactory.h>

DMCreditsController::DMCreditsController() {

}

DMCreditsController::DMCreditsController(const DMCreditsController& orig) {
}

void DMCreditsController::beforeStart() {

//    auto demensdeumLogo = std::make_shared<FSEObject>();
//
//    auto model = FSEGTFactory::makeModelComponent(std::make_shared<string>("./data/graphics/models/cube/cube.bam"));
//
//    demensdeumLogo->addComponent(model);

    auto demensdeumLogo = FSEGTFactory::makeOnSceneObject(
            std::make_shared<string>("demensdeumLogo"),
            std::make_shared<string>("demensdeumLogo"),
            std::make_shared<string>(),
            std::make_shared<string>("./data/graphics/models/cube/cube.bam"),
            1, 1, 1,
            -8, 42, 0,
            0,
            0);

    this->gameData->getGameObjects()->addObject(demensdeumLogo);
}

void DMCreditsController::step() {

    renderer->render(this->gameData);

}

DMCreditsController::~DMCreditsController() {
}

<|endoftext|>


<commit_before>
/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#ifndef _Stroika_Foundation_Cache_SynchronizedTimedCache_inl_
#define _Stroika_Foundation_Cache_SynchronizedTimedCache_inl_ 1

namespace Stroika::Foundation::Cache {

    /*
     ********************************************************************************
     ************** SynchronizedTimedCache<KEY, VALUE, TRAITS> **********************
     ********************************************************************************
     */
	template <typename KEY, typename VALUE, typename TRAITS>
	inline SynchronizedTimedCache<KEY, VALUE, TRAITS>::SynchronizedTimedCache (Time::DurationSecondsType timeoutInSeconds)
		: inherited (timeoutInSeconds)
	{
	}
	template <typename KEY, typename VALUE, typename TRAITS>
	inline SynchronizedTimedCache<KEY, VALUE, TRAITS>::SynchronizedTimedCache (const SynchronizedTimedCache& src)
		: inherited (src)
	{
	}
	template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::SetTimeout (Time::DurationSecondsType timeoutInSeconds)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::SetTimeout (timeoutInSeconds);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline optional<VALUE> SynchronizedTimedCache<KEY, VALUE, TRAITS>::Lookup (typename Configuration::ArgByValueType<KEY> key)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        return inherited::Lookup (key);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    VALUE SynchronizedTimedCache<KEY, VALUE, TRAITS>::LookupValue (typename Configuration::ArgByValueType<KEY> key, const function<VALUE (typename Configuration::ArgByValueType<KEY>)>& cacheFiller)
    {
        /*
         *  The main reason for this class, is this logic: unlocking the shared lock and then fetching the new value (with a write lock).
         */
        auto&& lock = shared_lock{fMutex_};
        if (optional<VALUE> o = inherited::Lookup (key)) {
            return *o;
        }
        else {
            lock.unlock ();
            if (fHoldWriteLockDuringCacheFill) {
                // Avoid two threds calling cache for same key value at the same time
                auto&& newRWLock = lock_guard{fMutex_};
                VALUE  v         = cacheFiller (key);
                this->Add (key, v);
                return v;
            }
            else {
                // Avoid needlessly blocking lookups (shared_lock above) until after we've filled the cache (typically slow)
                // and keep it to minimum logically required (inherited add).
                VALUE  v         = cacheFiller (key);
                auto&& newRWLock = lock_guard{fMutex_};
                this->Add (key, v);
                return v;
            }
        }
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::Add (typename Configuration::ArgByValueType<KEY> key, typename Configuration::ArgByValueType<VALUE> result)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::Add (key, result);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::Remove (typename Configuration::ArgByValueType<KEY> key)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::Remove (key);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::clear ()
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::clear ();
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::DoBookkeeping ()
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::DoBookkeeping ();
    }

}

#endif /*_Stroika_Foundation_Cache_SynchronizedTimedCache_inl_*/
<commit_msg>fixed double lock/hang bug in Cache/SynchronizedTimedCache<commit_after>
/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#ifndef _Stroika_Foundation_Cache_SynchronizedTimedCache_inl_
#define _Stroika_Foundation_Cache_SynchronizedTimedCache_inl_ 1

namespace Stroika::Foundation::Cache {

    /*
     ********************************************************************************
     ************** SynchronizedTimedCache<KEY, VALUE, TRAITS> **********************
     ********************************************************************************
     */
	template <typename KEY, typename VALUE, typename TRAITS>
	inline SynchronizedTimedCache<KEY, VALUE, TRAITS>::SynchronizedTimedCache (Time::DurationSecondsType timeoutInSeconds)
		: inherited (timeoutInSeconds)
	{
	}
	template <typename KEY, typename VALUE, typename TRAITS>
	inline SynchronizedTimedCache<KEY, VALUE, TRAITS>::SynchronizedTimedCache (const SynchronizedTimedCache& src)
		: inherited (src)
	{
	}
	template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::SetTimeout (Time::DurationSecondsType timeoutInSeconds)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::SetTimeout (timeoutInSeconds);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline optional<VALUE> SynchronizedTimedCache<KEY, VALUE, TRAITS>::Lookup (typename Configuration::ArgByValueType<KEY> key)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        return inherited::Lookup (key);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    VALUE SynchronizedTimedCache<KEY, VALUE, TRAITS>::LookupValue (typename Configuration::ArgByValueType<KEY> key, const function<VALUE (typename Configuration::ArgByValueType<KEY>)>& cacheFiller)
    {
        /*
         *  The main reason for this class, is this logic: unlocking the shared lock and then fetching the new value (with a write lock).
         */
        auto&& lock = shared_lock{fMutex_};
        if (optional<VALUE> o = inherited::Lookup (key)) {
            return *o;
        }
        else {
            lock.unlock ();
            if (fHoldWriteLockDuringCacheFill) {
                // Avoid two threds calling cache for same key value at the same time
                auto&& newRWLock = lock_guard{fMutex_};
                VALUE  v         = cacheFiller (key);
                this->Add (key, v);
                return v;
            }
            else {
                // Avoid needlessly blocking lookups (shared_lock above) until after we've filled the cache (typically slow)
                // and keep it to minimum logically required (inherited add).
                VALUE  v         = cacheFiller (key);
                this->Add (key, v);
                return v;
            }
        }
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::Add (typename Configuration::ArgByValueType<KEY> key, typename Configuration::ArgByValueType<VALUE> result)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::Add (key, result);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::Remove (typename Configuration::ArgByValueType<KEY> key)
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::Remove (key);
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::clear ()
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::clear ();
    }
    template <typename KEY, typename VALUE, typename TRAITS>
    inline void SynchronizedTimedCache<KEY, VALUE, TRAITS>::DoBookkeeping ()
    {
        [[maybe_unused]] auto&& lock = lock_guard{fMutex_};
        inherited::DoBookkeeping ();
    }

}

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