<commit_before>#include <iostream>
#include <fstream>

#include <sys/stat.h>

#ifdef ENABLE_LLVM
#include <llvm/Support/ManagedStatic.h>
#endif

#include "environment.hpp"
#include "oop.hpp"
#include "type_info.hpp"
#include "exception.hpp"

#include "config.h"
#include "paths.h"

using namespace std;
using namespace rubinius;

/**
 * Main rbx entry point.
 *
 * The main function here handles the environment settings and command-line
 * arguments passed to it. It then boots the VM, runs the appropriate file
 * (`loader`), and returns 0 if no errors occur along the way.
 *
 * If there is an Assertion raised or an Exception, it prints the backtrace
 * supplied. This function is the wrapper for the entire VM, as it deals with
 * anything that could possibly happen to the VM. It's like the person
 * playing whack-a-mole, in that if something tries to come out of the VM
 * that's evil (such as a failed assertion or exception), it catches it and
 * skins it and shows it to the user.
 */
int main(int argc, char** argv) {
  int exit_code = 0;

  // Ensure to destruct an Environment before calling llvm_shutdown(), which
  // follows this block. Because Environment's destructor uses LLVM API, it
  // must precede llvm_shutdown().
  {
    Environment env(argc, argv);
    env.setup_cpp_terminate();

    try {
      if(const char* var = getenv("RBX_OPTIONS")) {
        env.load_string(var);
      }

      if(const char* path = getenv("RBX_OPTFILE")) {
        env.load_conf(path);
      }

      env.run_from_filesystem();
    } catch(Assertion *e) {
      std::cout << "VM Assertion:" << std::endl;
      std::cout << "  " << e->reason << std::endl << std::endl;
      e->print_backtrace();

      std::cout << std::endl << "Ruby backtrace:" << std::endl;
      env.state->vm()->print_backtrace();
      delete e;
      exit_code = 1;
    } catch(RubyException &e) {
      std::cout << "Ruby Exception hit toplevel:\n";
      // Prints Ruby backtrace, and VM backtrace if captured
      e.show(env.state);
      exit_code = 1;
    } catch(TypeError &e) {

      /* TypeError's here are dealt with specially so that they can deliver
       * more information, such as _why_ there was a type error issue.
       *
       * This has the same name as the RubyException TypeError (run `5 + "string"`
       * as an example), but these are NOT the same - this exception is raised
       * internally when cNil gets passed to an array method, for instance, when
       * an array was expected.
       */
      std::cout << "Type Error detected:" << std::endl;
      TypeInfo* wanted = env.state->vm()->find_type(e.type);

      if(!e.object->reference_p()) {
        std::cout << "  Tried to use non-reference value " << e.object;
      } else {
        TypeInfo* was = env.state->vm()->find_type(e.object->type_id());
        std::cout << "  Tried to use object of type " <<
          was->type_name << " (" << was->type << ")";
      }

      std::cout << " as type " << wanted->type_name << " (" <<
        wanted->type << ")" << std::endl;

      e.print_backtrace();

      std::cout << "Ruby backtrace:" << std::endl;
      env.state->vm()->print_backtrace();
      exit_code = 1;
    } catch(MissingRuntime& e) {
      std::cerr << std::endl;
      std::cerr << e.what() << std::endl;
      std::cerr << "Rubinius was configured to find the directories relative to:" << std::endl;
      std::cerr << std::endl << "  " << RBX_PREFIX_PATH << std::endl << std::endl;
      std::cerr << "Set the environment variable RBX_PREFIX_PATH to the directory";
      std::cerr << std::endl;
      std::cerr << "that is the prefix of the following runtime directories:" << std::endl;
      std::cerr << std::endl;
      std::cerr << "      BIN_PATH: " << RBX_BIN_PATH << std::endl;
      std::cerr << "  RUNTIME_PATH: " << RBX_RUNTIME_PATH << std::endl;
      std::cerr << "   KERNEL_PATH: " << RBX_KERNEL_PATH << std::endl;
      std::cerr << "      LIB_PATH: " << RBX_LIB_PATH << std::endl;
      std::cerr << "   VENDOR_PATH: " << RBX_VENDOR_PATH << std::endl;
      std::cerr << "     GEMS_PATH: " << RBX_GEMS_PATH << std::endl;
      std::cerr << std::endl;
      exit_code = 1;
    } catch(BadKernelFile& e) {
      std::cout << "ERROR: Unable to load: " << e.what() << std::endl << std::endl;
      std::cout << "Please run the following commands to rebuild:" << std::endl;
      std::cout << "  rake clean" << std::endl;
      std::cout << "  rake or rake install" << std::endl << std::endl;
      std::cout << "If the problem persists, please open an issue at:" << std::endl;
      std::cout << "  http://github.com/rubinius/rubinius\n";
      exit_code = 1;
    } catch(VMException &e) {
      std::cout << "Unknown VM exception detected." << std::endl;
      e.print_backtrace();
      exit_code = 1;
    } catch(std::runtime_error& e) {
      std::cout << "Runtime exception: " << e.what() << std::endl;
      exit_code = 1;
    }

    if(!exit_code) {
      env.halt(env.state);
      exit_code = env.exit_code(env.state);
    }
  }

#ifdef ENABLE_LLVM
  llvm::llvm_shutdown();
#endif

  return exit_code;
}
<commit_msg>Fix crash on unexpected abort / VM exit<commit_after>#include <iostream>
#include <fstream>

#include <sys/stat.h>

#ifdef ENABLE_LLVM
#include <llvm/Support/ManagedStatic.h>
#endif

#include "environment.hpp"
#include "oop.hpp"
#include "type_info.hpp"
#include "exception.hpp"

#include "config.h"
#include "paths.h"

using namespace std;
using namespace rubinius;

/**
 * Main rbx entry point.
 *
 * The main function here handles the environment settings and command-line
 * arguments passed to it. It then boots the VM, runs the appropriate file
 * (`loader`), and returns 0 if no errors occur along the way.
 *
 * If there is an Assertion raised or an Exception, it prints the backtrace
 * supplied. This function is the wrapper for the entire VM, as it deals with
 * anything that could possibly happen to the VM. It's like the person
 * playing whack-a-mole, in that if something tries to come out of the VM
 * that's evil (such as a failed assertion or exception), it catches it and
 * skins it and shows it to the user.
 */
int main(int argc, char** argv) {
  int exit_code = 0;

  // Ensure to destruct an Environment before calling llvm_shutdown(), which
  // follows this block. Because Environment's destructor uses LLVM API, it
  // must precede llvm_shutdown().
  {
    Environment env(argc, argv);
    env.setup_cpp_terminate();

    try {
      if(const char* var = getenv("RBX_OPTIONS")) {
        env.load_string(var);
      }

      if(const char* path = getenv("RBX_OPTFILE")) {
        env.load_conf(path);
      }

      env.run_from_filesystem();
    } catch(Assertion *e) {
      std::cout << "VM Assertion:" << std::endl;
      std::cout << "  " << e->reason << std::endl << std::endl;
      e->print_backtrace();

      std::cout << std::endl << "Ruby backtrace:" << std::endl;
      env.state->vm()->print_backtrace();
      delete e;
      exit_code = 1;
    } catch(RubyException &e) {
      std::cout << "Ruby Exception hit toplevel:\n";
      // Prints Ruby backtrace, and VM backtrace if captured
      e.show(env.state);
      exit_code = 1;
    } catch(TypeError &e) {

      /* TypeError's here are dealt with specially so that they can deliver
       * more information, such as _why_ there was a type error issue.
       *
       * This has the same name as the RubyException TypeError (run `5 + "string"`
       * as an example), but these are NOT the same - this exception is raised
       * internally when cNil gets passed to an array method, for instance, when
       * an array was expected.
       */
      std::cout << "Type Error detected:" << std::endl;
      TypeInfo* wanted = env.state->vm()->find_type(e.type);

      if(!e.object->reference_p()) {
        std::cout << "  Tried to use non-reference value " << e.object;
      } else {
        TypeInfo* was = env.state->vm()->find_type(e.object->type_id());
        std::cout << "  Tried to use object of type " <<
          was->type_name << " (" << was->type << ")";
      }

      std::cout << " as type " << wanted->type_name << " (" <<
        wanted->type << ")" << std::endl;

      e.print_backtrace();

      std::cout << "Ruby backtrace:" << std::endl;
      env.state->vm()->print_backtrace();
      exit_code = 1;
    } catch(MissingRuntime& e) {
      std::cerr << std::endl;
      std::cerr << e.what() << std::endl;
      std::cerr << "Rubinius was configured to find the directories relative to:" << std::endl;
      std::cerr << std::endl << "  " << RBX_PREFIX_PATH << std::endl << std::endl;
      std::cerr << "Set the environment variable RBX_PREFIX_PATH to the directory";
      std::cerr << std::endl;
      std::cerr << "that is the prefix of the following runtime directories:" << std::endl;
      std::cerr << std::endl;
      std::cerr << "      BIN_PATH: " << RBX_BIN_PATH << std::endl;
      std::cerr << "  RUNTIME_PATH: " << RBX_RUNTIME_PATH << std::endl;
      std::cerr << "   KERNEL_PATH: " << RBX_KERNEL_PATH << std::endl;
      std::cerr << "      LIB_PATH: " << RBX_LIB_PATH << std::endl;
      std::cerr << "   VENDOR_PATH: " << RBX_VENDOR_PATH << std::endl;
      std::cerr << "     GEMS_PATH: " << RBX_GEMS_PATH << std::endl;
      std::cerr << std::endl;
      exit_code = 1;
    } catch(BadKernelFile& e) {
      std::cout << "ERROR: Unable to load: " << e.what() << std::endl << std::endl;
      std::cout << "Please run the following commands to rebuild:" << std::endl;
      std::cout << "  rake clean" << std::endl;
      std::cout << "  rake or rake install" << std::endl << std::endl;
      std::cout << "If the problem persists, please open an issue at:" << std::endl;
      std::cout << "  http://github.com/rubinius/rubinius\n";
      exit_code = 1;
    } catch(VMException &e) {
      std::cout << "Unknown VM exception detected." << std::endl;
      e.print_backtrace();
      exit_code = 1;
    } catch(std::runtime_error& e) {
      std::cout << "Runtime exception: " << e.what() << std::endl;
      exit_code = 1;
    }

    env.halt(env.state);
    if(!exit_code) {
      exit_code = env.exit_code(env.state);
    }
  }

#ifdef ENABLE_LLVM
  llvm::llvm_shutdown();
#endif

  return exit_code;
}
<|endoftext|>


<commit_before>#include "llvm/jit_operations.hpp"
#include "llvm/access_memory.hpp"

#include "builtin/access_variable.hpp"

namespace rubinius {
  class Inliner {
    JITOperations& ops_;
    InlineCache* cache_;
    int count_;
    BasicBlock* after_;

  public:

    Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after)
      : ops_(ops)
      , cache_(cache)
      , count_(count)
      , after_(after)
    {}

    Value* recv() {
      return ops_.stack_back(count_);
    }

    Value* arg(int which) {
      return ops_.stack_back(count_ - which);
    }

    void consider() {
      executor callee = cache_->method->execute;

      if(callee == Primitives::tuple_at && count_ == 1) {
        call_tuple_at();
      } else if(callee == Primitives::tuple_put && count_ == 2) {
        call_tuple_put();

      // If the cache has only ever had one class, inline!
      } else if(cache_->classes_seen() == 1) {
        AccessManagedMemory memguard(ops_.state());
        Executable* meth = cache_->method;

        if(AccessVariable* acc = try_as<AccessVariable>(meth)) {
          inline_ivar_access(cache_->tracked_class(0), acc);
        }
      }
    }

    void inline_ivar_access(Class* klass, AccessVariable* acc) {
      if(acc->write()->true_p()) return;
      if(count_ != 0) return;

      acc->add_inliner(ops_.vmmethod());

      ops_.state()->add_accessor_inlined();

      Value* self = ops_.stack_top();

      BasicBlock* use_send = ops_.new_block("use_send");
      ops_.check_reference_class(self, klass->class_id(), use_send);

      // Figure out if we should use the table ivar lookup or
      // the slot ivar lookup.

      TypeInfo* ti = klass->type_info();
      TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index());

      Value* ivar = 0;

      if(it != ti->slots.end()) {
        int offset = ti->slot_locations[it->second];
        ivar = ops_.get_object_slot(ops_.stack_top(), offset);
      } else {
        Signature sig2(ops_.state(), "Object");
        sig2 << "VM";
        sig2 << "Object";
        sig2 << "Object";

        Value* call_args2[] = {
          ops_.vm(),
          ops_.stack_top(),
          ops_.constant(acc->name())
        };

        ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar",
            ops_.current_block());
      }

      ops_.stack_pop();
      ops_.stack_push(ivar);

      ops_.create_branch(after_);
      ops_.set_block(use_send);

      after_->moveAfter(use_send);
    }

    void call_tuple_at() {
      Value* rec = recv();

      // bool is_tuple = recv->flags & mask;

      Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type);

      BasicBlock* is_tuple = ops_.new_block("is_tuple");
      BasicBlock* access =   ops_.new_block("tuple_at");
      BasicBlock* is_other = ops_.new_block("is_other");

      ops_.create_conditional_branch(is_tuple, is_other, cmp);

      ops_.set_block(is_tuple);

      Value* index_val = arg(0);

      Value* fix_cmp = ops_.check_if_fixnum(index_val);
      // Check that index is not over the end of the Tuple

      Value* tup = ops_.upcast(rec, "Tuple");

      Value* index = ops_.tag_strip32(index_val);
      Value* full_size = ops_.get_tuple_size(tup);
      Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds");

      // Combine fix_cmp and size_cmp to validate entry into access code
      Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp");
      ops_.create_conditional_branch(access, is_other, access_cmp);

      ops_.set_block(access);

      ops_.stack_remove(2);

      Value* idx[] = {
        ConstantInt::get(Type::Int32Ty, 0),
        ConstantInt::get(Type::Int32Ty, offset::tuple_field),
        index
      };

      Value* gep = ops_.create_gep(tup, idx, 3, "field_pos");

      ops_.stack_push(ops_.create_load(gep, "tuple_at"));

      ops_.create_branch(after_);

      ops_.set_block(is_other);
    }

    void call_tuple_put() {
      Value* rec = recv();

      Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type);

      BasicBlock* is_tuple = ops_.new_block("is_tuple");
      BasicBlock* access =   ops_.new_block("tuple_put");
      BasicBlock* is_other = ops_.new_block("is_other");

      ops_.create_conditional_branch(is_tuple, is_other, cmp);

      ops_.set_block(is_tuple);

      Value* index_val = arg(0);
      Value* fix_cmp = ops_.check_if_fixnum(index_val);

      Value* tup = ops_.upcast(rec, "Tuple");

      Value* index = ops_.tag_strip32(index_val);
      Value* full_size = ops_.get_tuple_size(tup);
      Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds");

      // Combine fix_cmp and size_cmp to validate entry into access code
      Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp");
      ops_.create_conditional_branch(access, is_other, access_cmp);

      ops_.set_block(access);

      Value* value = arg(1);
      ops_.stack_remove(3);

      Value* idx[] = {
        ConstantInt::get(Type::Int32Ty, 0),
        ConstantInt::get(Type::Int32Ty, offset::tuple_field),
        index
      };

      Value* gep = ops_.create_gep(tup, idx, 3, "field_pos");

      ops_.create_store(value, gep);
      ops_.write_barrier(tup, value);
      ops_.stack_push(value);

      ops_.create_branch(after_);

      ops_.set_block(is_other);
    }
  };

}
<commit_msg>Disable accessor inlining for now<commit_after>#include "llvm/jit_operations.hpp"
#include "llvm/access_memory.hpp"

#include "builtin/access_variable.hpp"

namespace rubinius {
  class Inliner {
    JITOperations& ops_;
    InlineCache* cache_;
    int count_;
    BasicBlock* after_;

  public:

    Inliner(JITOperations& ops, InlineCache* cache, int count, BasicBlock* after)
      : ops_(ops)
      , cache_(cache)
      , count_(count)
      , after_(after)
    {}

    Value* recv() {
      return ops_.stack_back(count_);
    }

    Value* arg(int which) {
      return ops_.stack_back(count_ - which);
    }

    void consider() {
      executor callee = cache_->method->execute;

      if(callee == Primitives::tuple_at && count_ == 1) {
        call_tuple_at();
      } else if(callee == Primitives::tuple_put && count_ == 2) {
        call_tuple_put();

      // If the cache has only ever had one class, inline!
      /*
      } else if(cache_->classes_seen() == 1) {
        AccessManagedMemory memguard(ops_.state());
        Executable* meth = cache_->method;

        if(AccessVariable* acc = try_as<AccessVariable>(meth)) {
          inline_ivar_access(cache_->tracked_class(0), acc);
        }
        */
      }
    }

    void inline_ivar_access(Class* klass, AccessVariable* acc) {
      if(acc->write()->true_p()) return;
      if(count_ != 0) return;

      acc->add_inliner(ops_.vmmethod());

      ops_.state()->add_accessor_inlined();

      Value* self = ops_.stack_top();

      BasicBlock* use_send = ops_.new_block("use_send");
      ops_.check_reference_class(self, klass->class_id(), use_send);

      // Figure out if we should use the table ivar lookup or
      // the slot ivar lookup.

      TypeInfo* ti = klass->type_info();
      TypeInfo::Slots::iterator it = ti->slots.find(acc->name()->index());

      Value* ivar = 0;

      if(it != ti->slots.end()) {
        int offset = ti->slot_locations[it->second];
        ivar = ops_.get_object_slot(ops_.stack_top(), offset);
      } else {
        Signature sig2(ops_.state(), "Object");
        sig2 << "VM";
        sig2 << "Object";
        sig2 << "Object";

        Value* call_args2[] = {
          ops_.vm(),
          ops_.stack_top(),
          ops_.constant(acc->name())
        };

        ivar = sig2.call("rbx_get_ivar", call_args2, 3, "ivar",
            ops_.current_block());
      }

      ops_.stack_pop();
      ops_.stack_push(ivar);

      ops_.create_branch(after_);
      ops_.set_block(use_send);

      after_->moveAfter(use_send);
    }

    void call_tuple_at() {
      Value* rec = recv();

      // bool is_tuple = recv->flags & mask;

      Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type);

      BasicBlock* is_tuple = ops_.new_block("is_tuple");
      BasicBlock* access =   ops_.new_block("tuple_at");
      BasicBlock* is_other = ops_.new_block("is_other");

      ops_.create_conditional_branch(is_tuple, is_other, cmp);

      ops_.set_block(is_tuple);

      Value* index_val = arg(0);

      Value* fix_cmp = ops_.check_if_fixnum(index_val);
      // Check that index is not over the end of the Tuple

      Value* tup = ops_.upcast(rec, "Tuple");

      Value* index = ops_.tag_strip32(index_val);
      Value* full_size = ops_.get_tuple_size(tup);
      Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds");

      // Combine fix_cmp and size_cmp to validate entry into access code
      Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp");
      ops_.create_conditional_branch(access, is_other, access_cmp);

      ops_.set_block(access);

      ops_.stack_remove(2);

      Value* idx[] = {
        ConstantInt::get(Type::Int32Ty, 0),
        ConstantInt::get(Type::Int32Ty, offset::tuple_field),
        index
      };

      Value* gep = ops_.create_gep(tup, idx, 3, "field_pos");

      ops_.stack_push(ops_.create_load(gep, "tuple_at"));

      ops_.create_branch(after_);

      ops_.set_block(is_other);
    }

    void call_tuple_put() {
      Value* rec = recv();

      Value* cmp = ops_.check_type_bits(rec, rubinius::Tuple::type);

      BasicBlock* is_tuple = ops_.new_block("is_tuple");
      BasicBlock* access =   ops_.new_block("tuple_put");
      BasicBlock* is_other = ops_.new_block("is_other");

      ops_.create_conditional_branch(is_tuple, is_other, cmp);

      ops_.set_block(is_tuple);

      Value* index_val = arg(0);
      Value* fix_cmp = ops_.check_if_fixnum(index_val);

      Value* tup = ops_.upcast(rec, "Tuple");

      Value* index = ops_.tag_strip32(index_val);
      Value* full_size = ops_.get_tuple_size(tup);
      Value* size_cmp = ops_.create_less_than(index, full_size, "is_in_bounds");

      // Combine fix_cmp and size_cmp to validate entry into access code
      Value* access_cmp = ops_.create_and(fix_cmp, size_cmp, "access_cmp");
      ops_.create_conditional_branch(access, is_other, access_cmp);

      ops_.set_block(access);

      Value* value = arg(1);
      ops_.stack_remove(3);

      Value* idx[] = {
        ConstantInt::get(Type::Int32Ty, 0),
        ConstantInt::get(Type::Int32Ty, offset::tuple_field),
        index
      };

      Value* gep = ops_.create_gep(tup, idx, 3, "field_pos");

      ops_.create_store(value, gep);
      ops_.write_barrier(tup, value);
      ops_.stack_push(value);

      ops_.create_branch(after_);

      ops_.set_block(is_other);
    }
  };

}
<|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2011
 * filename : main.cpp
 * author   : Evgeny Proydakov
 * email	: lord.tiran@gmail.com
 * date     : 16.06.2011
 * bref     : Test rdo_common
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <boost/regex.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdocommon.h"
#include "rdo_common/rdofile.h"
#include "rdo_common/rdotime.h"
#include "rdo_common/test/rdo_common_test/resource.h"

#include <config-tiles.h>
// ===============================================================================

#define BOOST_TEST_MODULE test_rdo_common
#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test_rdo_common)

BOOST_AUTO_TEST_CASE(test_rdo_common_1)
{
	// TODO HELP ME !!!!
	tstring str1 = rdo::format(IDS_STRING101);
	tstring str2 = rdo::format(IDS_STRING102, 22);
	tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str());
}

BOOST_AUTO_TEST_CASE(test_create_file)
{
	BOOST_CHECK(rdo::File::create(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_exist_file)
{
	BOOST_CHECK(rdo::File::exist(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_read_only_file)
{
	BOOST_CHECK(!rdo::File::read_only(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_remove_file)
{
	BOOST_CHECK(rdo::File::unlink(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_rdo_check_data)
{
	// TODO EDIT REGEX
	rdo::Time time1     = rdo::Time::local();
	tstring   time_str = time1.asString();

	boost::regex expression("(.*)");
	boost::cmatch what;
	BOOST_CHECK(boost::regex_match(time_str.c_str(), what, expression));
}

BOOST_AUTO_TEST_SUITE_END()<commit_msg> - библиотечные инклюды располагаются в INCLUDES  - инклюды проекта располагаются SYNOPSIS  - инклюды проекта указываются от корня сорсов<commit_after>/*
 * copyright: (c) RDO-Team, 2011
 * filename : main.cpp
 * author   : Evgeny Proydakov
 * email	: lord.tiran@gmail.com
 * date     : 16.06.2011
 * bref     : Test rdo_common
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <boost/regex.hpp>
#define BOOST_TEST_MODULE test_rdo_common
#include <boost/test/included/unit_test.hpp>
// ====================================================================== SYNOPSIS
#include "rdo_common/rdocommon.h"
#include "rdo_common/rdofile.h"
#include "rdo_common/rdotime.h"
#include "rdo_common/test/rdo_common_test/resource.h"
#include "rdo_common/test/rdo_common_test/config-tiles.h"
// ===============================================================================

BOOST_AUTO_TEST_SUITE(test_rdo_common)

BOOST_AUTO_TEST_CASE(test_rdo_common_1)
{
	// TODO HELP ME !!!!
	tstring str1 = rdo::format(IDS_STRING101);
	tstring str2 = rdo::format(IDS_STRING102, 22);
	tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str());
}

BOOST_AUTO_TEST_CASE(test_create_file)
{
	BOOST_CHECK(rdo::File::create(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_exist_file)
{
	BOOST_CHECK(rdo::File::exist(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_read_only_file)
{
	BOOST_CHECK(!rdo::File::read_only(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_remove_file)
{
	BOOST_CHECK(rdo::File::unlink(_T(tstring(resource_directory) + tstring(test_file_name))));
}

BOOST_AUTO_TEST_CASE(test_rdo_check_data)
{
	// TODO EDIT REGEX
	rdo::Time time1     = rdo::Time::local();
	tstring   time_str = time1.asString();

	boost::regex expression("(.*)");
	boost::cmatch what;
	BOOST_CHECK(boost::regex_match(time_str.c_str(), what, expression));
}

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>

#include "geometry/point.hpp"
#include "geometry/triangle.hpp"

#include "triangulation/figure_definition.hpp"
#include "triangulation/triangulation.hpp"

struct HUI : public FigureDefinition {
	int parameter(double x, double y) {
		//return !(y > x + 3 || y > 12 - x || (y > 2 && y < 4 && y < x && y < 9 - x));
		return
		(y<=1 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) ||
		(y>=1 && y<=2 && (y<=x && y<=6-x)) ||
		(y>=2 && y<=3 && (y>=4-x && y>=x-2)) ||
		(y>=3 && y<=4 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) ||

		(y<=2 && y<=x-6 && y>=x-8) ||
		(y>=2 && y<=3 && (y>=10-x && y>=x-8)) ||
		(y>=3 && y<=4 && ((y<=x-6 && y>=x-8) || (y>=10-x && y<=12-x))) ||

		(y<=4 && x>=12 && x<=14) ||
		(x>=14 && x<=16 && y>=x-14 && y<=x-12) ||
		(y<=4 && x>=16 && x<=18) ||

		(y>=19-x && y>=x-11);
	}
};

HUI hui;

// Triangulacia nahui
Triangulation triangulation(&hui);

void print(void) {
	FILE *gmain;

	gmain = fopen("main", "w");
	fprintf(gmain, "plot 'data' with lines\npause mouse close\n");
	fclose(gmain);

	triangulation.dump("data");

	system("gnuplot main");
	unlink("main");
	unlink("data");
}

void demo() {
	triangulation.make_grid(19, 6);
	print();
	triangulation.make_it_smaller();
	print();
	triangulation.make_it_smaller();
	print();
}

int main() {
	triangulation.make_grid(19, 6);
	triangulation.make_it_smaller();
	triangulation.make_it_smaller();
	triangulation.write(stdout);
	return 0;
}
<commit_msg>Better defaults in triangulate.cpp<commit_after>#include <cstdio>
#include <cstdlib>

#include "geometry/point.hpp"
#include "geometry/triangle.hpp"

#include "triangulation/figure_definition.hpp"
#include "triangulation/triangulation.hpp"

struct HUI : public FigureDefinition {
	int parameter(double x, double y) {
		//return !(y > x + 3 || y > 12 - x || (y > 2 && y < 4 && y < x && y < 9 - x));
		return
		(y<=1 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) ||
		(y>=1 && y<=2 && (y<=x && y<=6-x)) ||
		(y>=2 && y<=3 && (y>=4-x && y>=x-2)) ||
		(y>=3 && y<=4 && ((y<=x && y>=x-2) || (y>=4-x && y<=6-x))) ||

		(y<=2 && y<=x-6 && y>=x-8) ||
		(y>=2 && y<=3 && (y>=10-x && y>=x-8)) ||
		(y>=3 && y<=4 && ((y<=x-6 && y>=x-8) || (y>=10-x && y<=12-x))) ||

		(y<=4 && x>=12 && x<=14) ||
		(x>=14 && x<=16 && y>=x-14 && y<=x-12) ||
		(y<=4 && x>=16 && x<=18) ||

		(y>=19-x && y>=x-11);
	}
};

HUI hui;

// Triangulacia nahui
Triangulation triangulation(&hui);

void print(void) {
	FILE *gmain;

	gmain = fopen("main", "w");
	fprintf(gmain, "plot 'data' with lines\npause mouse close\n");
	fclose(gmain);

	triangulation.dump("data");

	system("gnuplot main");
	unlink("main");
	unlink("data");
}

void demo() {
	triangulation.make_grid(19, 6);
	print();
	triangulation.make_it_smaller();
	print();
	triangulation.make_it_smaller();
	print();
}

void run() {
	triangulation.make_grid(19, 6);
	triangulation.make_it_smaller();
	triangulation.make_it_smaller();
	triangulation.write(stdout);
}

int main() {
	demo();
	return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2013 Roman Kurbatov
 *
 * 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.
 *
 * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
 * project. See git revision history for detailed changes. */

#include "netConfigWidget.h"

#include <QtNetwork/QNetworkInterface>
#include <QtNetwork/QNetworkAddressEntry>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QAbstractSocket>
#include <QtGui/QKeyEvent>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QScrollBar>
#else
	#include <QtWidgets/QScrollBar>
#endif

#include <QtCore/QDebug>

#include <trikWiFi/trikWiFi.h>
#include <trikWiFi/wpaConfigurer.h>

using namespace trikGui;

using namespace trikWiFi;

NetConfigWidget::NetConfigWidget(QString const &configPath, QWidget *parent)
	: QWidget(parent)
	, mWiFi(new TrikWiFi("/tmp/trikwifi", "/run/wpa_supplicant/wlan0", this))
	, mConnectionState(notConnected)
{
	setAttribute(Qt::WA_DeleteOnClose);
	setWindowState(Qt::WindowFullScreen);

	WpaConfigurer::configureWpaSupplicant(configPath + "wpa-config.xml", *mWiFi);

	QList<NetworkConfiguration> const networksFromWpaSupplicant = mWiFi->listNetworks();
	foreach (NetworkConfiguration const &networkConfiguration, networksFromWpaSupplicant) {
		mNetworksAvailableForConnection.insert(networkConfiguration.ssid, networkConfiguration.id);
	}

	connect(mWiFi.data(), SIGNAL(scanFinished()), this, SLOT(scanForAvailableNetworksDoneSlot()));
	connect(mWiFi.data(), SIGNAL(connected()), this, SLOT(connectedSlot()));
	connect(mWiFi.data(), SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));

	mWiFi->scan();

	mConnectionIconLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

	mIpLabel.setText(tr("IP:"));
	mIpLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

	mAvailableNetworksLabel.setText(tr("Available networks:"));

	mAvailableNetworksView.setModel(&mAvailableNetworksModel);
	mAvailableNetworksView.setSelectionMode(QAbstractItemView::SingleSelection);

	mIpAddressLayout.addWidget(&mConnectionIconLabel);
	mIpAddressLayout.addWidget(&mIpLabel);
	mIpAddressLayout.addWidget(&mIpValueLabel);

	mMainLayout.addLayout(&mIpAddressLayout);
	mMainLayout.addWidget(&mAvailableNetworksLabel);
	mMainLayout.addWidget(&mAvailableNetworksView);
	setLayout(&mMainLayout);

	Status const connectionStatus = mWiFi->status();
	mConnectionState = connectionStatus.connected ? connected : notConnected;
	setConnectionStatus(connectionStatus);
}

NetConfigWidget::~NetConfigWidget()
{
}

QString NetConfigWidget::menuEntry()
{
	return tr("Network config");
}

void NetConfigWidget::scanForAvailableNetworksDoneSlot()
{
	mAvailableNetworksModel.clear();
	foreach (ScanResult const &result, mWiFi->scanResults()) {
		mAvailableNetworksModel.appendRow(new QStandardItem(result.ssid));
	}

	updateConnectionStatusesInNetworkList();
}

void NetConfigWidget::connectedSlot()
{
	mConnectionState = connected;
	setConnectionStatus(mWiFi->status());
}

void NetConfigWidget::disconnectedSlot()
{
	if (mConnectionState != connecting) {
		mConnectionState = notConnected;
	}

	setConnectionStatus(mWiFi->status());

	// Now to determine reason of disconnect --- maybe the network is out of range now.
	mWiFi->scan();
}

void NetConfigWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
	case Qt::Key_Meta:
	case Qt::Key_Left: {
		close();
		break;
	}
	case Qt::Key_Enter: {
		connectToSelectedNetwork();
	}
	default: {
		QWidget::keyPressEvent(event);
		break;
	}
	}
}

void NetConfigWidget::setConnectionStatus(trikWiFi::Status const &status)
{
	QPixmap pixmap;
	switch (mConnectionState) {
	case connected:
		pixmap.load("://resources/connected.png");
		mIpValueLabel.setText(status.ipAddress);
		mCurrentSsid = status.ssid;
		break;
	case connecting:
		pixmap.load("://resources/unknownConnectionStatus.png");
		mIpValueLabel.setText(tr("connecting..."));
		mCurrentSsid = "";
		break;
	case notConnected:
		pixmap.load("://resources/notConnected.png");
		mIpValueLabel.setText(tr("no connection"));
		mCurrentSsid = "";
		break;
	}

	mConnectionIconLabel.setPixmap(pixmap);
	updateConnectionStatusesInNetworkList();
}

void NetConfigWidget::updateConnectionStatusesInNetworkList()
{
	for (int i = 0; i < mAvailableNetworksModel.rowCount(); ++i) {
		QStandardItem * const item = mAvailableNetworksModel.item(i);
		QFont font = item->font();
		font.setBold(false);
		item->setFont(font);
		if (item->text() == mCurrentSsid) {
			item->setIcon(QIcon("://resources/connectedToNetwork.png"));
			font.setBold(true);
			item->setFont(font);
		} else if (mNetworksAvailableForConnection.contains(item->text())) {
			item->setIcon(QIcon("://resources/notConnectedToNetwork.png"));
		} else {
			item->setIcon(QIcon("://resources/connectionToNetworkImpossible.png"));
		}
	}

	mAvailableNetworksView.setFocus();
	mAvailableNetworksView.selectionModel()->select(
			mAvailableNetworksModel.index(0, 0)
			, QItemSelectionModel::ClearAndSelect
			);
}

void NetConfigWidget::connectToSelectedNetwork()
{
	QModelIndexList const selected = mAvailableNetworksView.selectionModel()->selectedIndexes();
	if (selected.size() != 1) {
		return;
	}

	QString const ssid = mAvailableNetworksModel.itemFromIndex(selected[0])->text();
	if (ssid == mCurrentSsid) {
		return;
	}

	if (!mNetworksAvailableForConnection.contains(ssid)) {
		return;
	}

	mConnectionState = connecting;

	mWiFi->connect(mNetworksAvailableForConnection[ssid]);
}
<commit_msg>Updating connection state when connecting to a network for a first time<commit_after>/* Copyright 2013 Roman Kurbatov
 *
 * 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.
 *
 * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime
 * project. See git revision history for detailed changes. */

#include "netConfigWidget.h"

#include <QtNetwork/QNetworkInterface>
#include <QtNetwork/QNetworkAddressEntry>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QAbstractSocket>
#include <QtGui/QKeyEvent>

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
	#include <QtGui/QScrollBar>
#else
	#include <QtWidgets/QScrollBar>
#endif

#include <QtCore/QDebug>

#include <trikWiFi/trikWiFi.h>
#include <trikWiFi/wpaConfigurer.h>

using namespace trikGui;

using namespace trikWiFi;

NetConfigWidget::NetConfigWidget(QString const &configPath, QWidget *parent)
	: QWidget(parent)
	, mWiFi(new TrikWiFi("/tmp/trikwifi", "/run/wpa_supplicant/wlan0", this))
	, mConnectionState(notConnected)
{
	setAttribute(Qt::WA_DeleteOnClose);
	setWindowState(Qt::WindowFullScreen);

	WpaConfigurer::configureWpaSupplicant(configPath + "wpa-config.xml", *mWiFi);

	QList<NetworkConfiguration> const networksFromWpaSupplicant = mWiFi->listNetworks();
	foreach (NetworkConfiguration const &networkConfiguration, networksFromWpaSupplicant) {
		mNetworksAvailableForConnection.insert(networkConfiguration.ssid, networkConfiguration.id);
	}

	connect(mWiFi.data(), SIGNAL(scanFinished()), this, SLOT(scanForAvailableNetworksDoneSlot()));
	connect(mWiFi.data(), SIGNAL(connected()), this, SLOT(connectedSlot()));
	connect(mWiFi.data(), SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));

	mWiFi->scan();

	mConnectionIconLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

	mIpLabel.setText(tr("IP:"));
	mIpLabel.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

	mAvailableNetworksLabel.setText(tr("Available networks:"));

	mAvailableNetworksView.setModel(&mAvailableNetworksModel);
	mAvailableNetworksView.setSelectionMode(QAbstractItemView::SingleSelection);

	mIpAddressLayout.addWidget(&mConnectionIconLabel);
	mIpAddressLayout.addWidget(&mIpLabel);
	mIpAddressLayout.addWidget(&mIpValueLabel);

	mMainLayout.addLayout(&mIpAddressLayout);
	mMainLayout.addWidget(&mAvailableNetworksLabel);
	mMainLayout.addWidget(&mAvailableNetworksView);
	setLayout(&mMainLayout);

	Status const connectionStatus = mWiFi->status();
	mConnectionState = connectionStatus.connected ? connected : notConnected;
	setConnectionStatus(connectionStatus);
}

NetConfigWidget::~NetConfigWidget()
{
}

QString NetConfigWidget::menuEntry()
{
	return tr("Network config");
}

void NetConfigWidget::scanForAvailableNetworksDoneSlot()
{
	mAvailableNetworksModel.clear();
	foreach (ScanResult const &result, mWiFi->scanResults()) {
		mAvailableNetworksModel.appendRow(new QStandardItem(result.ssid));
	}

	updateConnectionStatusesInNetworkList();
}

void NetConfigWidget::connectedSlot()
{
	mConnectionState = connected;
	setConnectionStatus(mWiFi->status());
}

void NetConfigWidget::disconnectedSlot()
{
	if (mConnectionState != connecting) {
		mConnectionState = notConnected;
	}

	setConnectionStatus(mWiFi->status());

	// Now to determine reason of disconnect --- maybe the network is out of range now.
	mWiFi->scan();
}

void NetConfigWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
	case Qt::Key_Meta:
	case Qt::Key_Left: {
		close();
		break;
	}
	case Qt::Key_Enter: {
		connectToSelectedNetwork();
	}
	default: {
		QWidget::keyPressEvent(event);
		break;
	}
	}
}

void NetConfigWidget::setConnectionStatus(trikWiFi::Status const &status)
{
	QPixmap pixmap;
	switch (mConnectionState) {
	case connected:
		pixmap.load("://resources/connected.png");
		mIpValueLabel.setText(status.ipAddress);
		mCurrentSsid = status.ssid;
		break;
	case connecting:
		pixmap.load("://resources/unknownConnectionStatus.png");
		mIpValueLabel.setText(tr("connecting..."));
		mCurrentSsid = "";
		break;
	case notConnected:
		pixmap.load("://resources/notConnected.png");
		mIpValueLabel.setText(tr("no connection"));
		mCurrentSsid = "";
		break;
	}

	mConnectionIconLabel.setPixmap(pixmap);
	updateConnectionStatusesInNetworkList();
}

void NetConfigWidget::updateConnectionStatusesInNetworkList()
{
	for (int i = 0; i < mAvailableNetworksModel.rowCount(); ++i) {
		QStandardItem * const item = mAvailableNetworksModel.item(i);
		QFont font = item->font();
		font.setBold(false);
		item->setFont(font);
		if (item->text() == mCurrentSsid) {
			item->setIcon(QIcon("://resources/connectedToNetwork.png"));
			font.setBold(true);
			item->setFont(font);
		} else if (mNetworksAvailableForConnection.contains(item->text())) {
			item->setIcon(QIcon("://resources/notConnectedToNetwork.png"));
		} else {
			item->setIcon(QIcon("://resources/connectionToNetworkImpossible.png"));
		}
	}

	mAvailableNetworksView.setFocus();
	mAvailableNetworksView.selectionModel()->select(
			mAvailableNetworksModel.index(0, 0)
			, QItemSelectionModel::ClearAndSelect
			);
}

void NetConfigWidget::connectToSelectedNetwork()
{
	QModelIndexList const selected = mAvailableNetworksView.selectionModel()->selectedIndexes();
	if (selected.size() != 1) {
		return;
	}

	QString const ssid = mAvailableNetworksModel.itemFromIndex(selected[0])->text();
	if (ssid == mCurrentSsid) {
		return;
	}

	if (!mNetworksAvailableForConnection.contains(ssid)) {
		return;
	}

	mConnectionState = connecting;

	setConnectionStatus(Status());

	mWiFi->connect(mNetworksAvailableForConnection[ssid]);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Jonathan Anderson
 *
 * 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 <sstream>

#include "capsicum.h"

using namespace capsh;

using std::ostringstream;
using std::string;

bool capsh::inCapabilityMode() throw(CError)
{
	unsigned int mode;

	if (cap_getmode(&mode) < 0) throw CError("cap_getmode()");
	return (mode != 0);
}

void capsh::assertNotInCapabilityMode(const string& action)
	throw(CError, CapabilityModeException)
{
	if (inCapabilityMode())
		throw CapabilityModeException(action);
}

string capsh::rightsString(cap_rights_t rights)
{
	ostringstream oss;

	if (rights & CAP_READ)				oss << "CAP_READ ";
	if (rights & CAP_WRITE)				oss << "CAP_WRITE ";
	if (rights & CAP_SEEK)				oss << "CAP_SEEK ";
	if (rights & CAP_GETPEERNAME)		oss << "CAP_GETPEERNAME ";
	if (rights & CAP_GETSOCKNAME)		oss << "CAP_GETSOCKNAME ";
	if (rights & CAP_FCHFLAGS)			oss << "CAP_FCHFLAGS ";
	if (rights & CAP_IOCTL)				oss << "CAP_IOCTL ";
	if (rights & CAP_FSTAT)				oss << "CAP_FSTAT ";
	if (rights & CAP_MMAP)				oss << "CAP_MMAP ";
	if (rights & CAP_FCNTL)				oss << "CAP_FCNTL ";
	if (rights & CAP_POLL_KEVENT)		oss << "CAP_POLL_KEVENT ";
	if (rights & CAP_FSYNC)				oss << "CAP_FSYNC ";
	if (rights & CAP_FCHOWN)			oss << "CAP_FCHOWN ";
	if (rights & CAP_FCHMOD)			oss << "CAP_FCHMOD ";
	if (rights & CAP_FTRUNCATE)		oss << "CAP_FTRUNCATE ";
	if (rights & CAP_FLOCK)				oss << "CAP_FLOCK ";
	if (rights & CAP_FSTATFS)			oss << "CAP_FSTATFS ";
	if (rights & CAP_FEXECVE)			oss << "CAP_FEXECVE ";
	if (rights & CAP_FPATHCONF)		oss << "CAP_FPATHCONF ";
	if (rights & CAP_FUTIMES)			oss << "CAP_FUTIMES ";
	if (rights & CAP_ACL_GET)			oss << "CAP_ACL_GET ";
	if (rights & CAP_ACL_SET)			oss << "CAP_ACL_SET ";
	if (rights & CAP_ACL_DELETE)		oss << "CAP_ACL_DELETE ";
	if (rights & CAP_ACL_CHECK)		oss << "CAP_ACL_CHECK ";
	if (rights & CAP_EXTATTR_GET)		oss << "CAP_EXTATTR_GET ";
	if (rights & CAP_EXTATTR_SET)		oss << "CAP_EXTATTR_SET ";
	if (rights & CAP_EXTATTR_DELETE)	oss << "CAP_EXTATTR_DELETE ";
	if (rights & CAP_EXTATTR_LIST)	oss << "CAP_EXTATTR_LIST ";
	if (rights & CAP_MAC_GET)			oss << "CAP_MAC_GET ";
	if (rights & CAP_MAC_SET)			oss << "CAP_MAC_SET ";
	if (rights & CAP_ACCEPT)			oss << "CAP_ACCEPT ";
	if (rights & CAP_CONNECT)			oss << "CAP_CONNECT ";
	if (rights & CAP_BIND)				oss << "CAP_BIND ";
	if (rights & CAP_GETSOCKOPT)		oss << "CAP_GETSOCKOPT ";
	if (rights & CAP_SETSOCKOPT)		oss << "CAP_SETSOCKOPT ";
	if (rights & CAP_LISTEN)			oss << "CAP_LISTEN ";
	if (rights & CAP_SHUTDOWN)			oss << "CAP_SHUTDOWN ";
	if (rights & CAP_PEELOFF)			oss << "CAP_PEELOFF ";
	if (rights & CAP_LOOKUP)			oss << "CAP_LOOKUP ";
	if (rights & CAP_SEM_POST)			oss << "CAP_SEM_POST ";
	if (rights & CAP_SEM_WAIT)			oss << "CAP_SEM_WAIT ";
	if (rights & CAP_SEM_GETVALUE)	oss << "CAP_SEM_GETVALUE ";
	if (rights & CAP_POST_KEVENT)		oss << "CAP_POST_KEVENT ";
	if (rights & CAP_PDGETPID)			oss << "CAP_PDGETPID ";
	if (rights & CAP_PDKILL)			oss << "CAP_PDKILL ";
	if (rights & CAP_MAPEXEC)			oss << "CAP_MAPEXEC ";
	if (rights & CAP_TTYHOOK)			oss << "CAP_TTYHOOK ";
	if (rights & CAP_FCHDIR)			oss << "CAP_FCHDIR ";
	if (rights & CAP_FSCK)				oss << "CAP_FSCK ";
	if (rights & CAP_CREATE)			oss << "CAP_CREATE ";
	if (rights & CAP_DELETE)			oss << "CAP_DELETE ";
	if (rights & CAP_MKDIR)				oss << "CAP_MKDIR ";
	if (rights & CAP_RMDIR)				oss << "CAP_RMDIR ";
	if (rights & CAP_MKFIFO)			oss << "CAP_MKFIFO ";

	return oss.str();
}

<commit_msg>CAP_KEVENT -> CAP_POST_EVENT, etc.<commit_after>/*
 * Copyright 2011 Jonathan Anderson
 *
 * 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 <sstream>

#include "capsicum.h"

using namespace capsh;

using std::ostringstream;
using std::string;

bool capsh::inCapabilityMode() throw(CError)
{
	unsigned int mode;

	if (cap_getmode(&mode) < 0) throw CError("cap_getmode()");
	return (mode != 0);
}

void capsh::assertNotInCapabilityMode(const string& action)
	throw(CError, CapabilityModeException)
{
	if (inCapabilityMode())
		throw CapabilityModeException(action);
}

string capsh::rightsString(cap_rights_t rights)
{
	ostringstream oss;

	if (rights & CAP_READ)				oss << "CAP_READ ";
	if (rights & CAP_WRITE)				oss << "CAP_WRITE ";
	if (rights & CAP_SEEK)				oss << "CAP_SEEK ";
	if (rights & CAP_GETPEERNAME)		oss << "CAP_GETPEERNAME ";
	if (rights & CAP_GETSOCKNAME)		oss << "CAP_GETSOCKNAME ";
	if (rights & CAP_FCHFLAGS)			oss << "CAP_FCHFLAGS ";
	if (rights & CAP_IOCTL)				oss << "CAP_IOCTL ";
	if (rights & CAP_FSTAT)				oss << "CAP_FSTAT ";
	if (rights & CAP_MMAP)				oss << "CAP_MMAP ";
	if (rights & CAP_FCNTL)				oss << "CAP_FCNTL ";
	if (rights & CAP_POLL_EVENT)		oss << "CAP_POLL_KEVENT ";
	if (rights & CAP_FSYNC)				oss << "CAP_FSYNC ";
	if (rights & CAP_FCHOWN)			oss << "CAP_FCHOWN ";
	if (rights & CAP_FCHMOD)			oss << "CAP_FCHMOD ";
	if (rights & CAP_FTRUNCATE)		oss << "CAP_FTRUNCATE ";
	if (rights & CAP_FLOCK)				oss << "CAP_FLOCK ";
	if (rights & CAP_FSTATFS)			oss << "CAP_FSTATFS ";
	if (rights & CAP_FEXECVE)			oss << "CAP_FEXECVE ";
	if (rights & CAP_FPATHCONF)		oss << "CAP_FPATHCONF ";
	if (rights & CAP_FUTIMES)			oss << "CAP_FUTIMES ";
	if (rights & CAP_ACL_GET)			oss << "CAP_ACL_GET ";
	if (rights & CAP_ACL_SET)			oss << "CAP_ACL_SET ";
	if (rights & CAP_ACL_DELETE)		oss << "CAP_ACL_DELETE ";
	if (rights & CAP_ACL_CHECK)		oss << "CAP_ACL_CHECK ";
	if (rights & CAP_EXTATTR_GET)		oss << "CAP_EXTATTR_GET ";
	if (rights & CAP_EXTATTR_SET)		oss << "CAP_EXTATTR_SET ";
	if (rights & CAP_EXTATTR_DELETE)	oss << "CAP_EXTATTR_DELETE ";
	if (rights & CAP_EXTATTR_LIST)	oss << "CAP_EXTATTR_LIST ";
	if (rights & CAP_MAC_GET)			oss << "CAP_MAC_GET ";
	if (rights & CAP_MAC_SET)			oss << "CAP_MAC_SET ";
	if (rights & CAP_ACCEPT)			oss << "CAP_ACCEPT ";
	if (rights & CAP_CONNECT)			oss << "CAP_CONNECT ";
	if (rights & CAP_BIND)				oss << "CAP_BIND ";
	if (rights & CAP_GETSOCKOPT)		oss << "CAP_GETSOCKOPT ";
	if (rights & CAP_SETSOCKOPT)		oss << "CAP_SETSOCKOPT ";
	if (rights & CAP_LISTEN)			oss << "CAP_LISTEN ";
	if (rights & CAP_SHUTDOWN)			oss << "CAP_SHUTDOWN ";
	if (rights & CAP_PEELOFF)			oss << "CAP_PEELOFF ";
	if (rights & CAP_LOOKUP)			oss << "CAP_LOOKUP ";
	if (rights & CAP_SEM_POST)			oss << "CAP_SEM_POST ";
	if (rights & CAP_SEM_WAIT)			oss << "CAP_SEM_WAIT ";
	if (rights & CAP_SEM_GETVALUE)	oss << "CAP_SEM_GETVALUE ";
	if (rights & CAP_POST_EVENT)		oss << "CAP_POST_KEVENT ";
	if (rights & CAP_PDGETPID)			oss << "CAP_PDGETPID ";
	if (rights & CAP_PDKILL)			oss << "CAP_PDKILL ";
	if (rights & CAP_MAPEXEC)			oss << "CAP_MAPEXEC ";
	if (rights & CAP_TTYHOOK)			oss << "CAP_TTYHOOK ";
	if (rights & CAP_FCHDIR)			oss << "CAP_FCHDIR ";
	if (rights & CAP_FSCK)				oss << "CAP_FSCK ";
	if (rights & CAP_CREATE)			oss << "CAP_CREATE ";
	if (rights & CAP_DELETE)			oss << "CAP_DELETE ";
	if (rights & CAP_MKDIR)				oss << "CAP_MKDIR ";
	if (rights & CAP_RMDIR)				oss << "CAP_RMDIR ";
	if (rights & CAP_MKFIFO)			oss << "CAP_MKFIFO ";

	return oss.str();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdgrffilter.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 17:24:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_SDGRFFILTER_HXX
#define _SD_SDGRFFILTER_HXX

#include <tools/errinf.hxx>
#include "sdfilter.hxx"

// ---------------
// - SdCGMFilter -
// ---------------

class SdGRFFilter : public SdFilter
{
public:
    SdGRFFilter (
        SfxMedium& rMedium,
        ::sd::DrawDocShell& rDocShell,
        sal_Bool bShowProgress );
    virtual ~SdGRFFilter (void);

    sal_Bool        Import();
    sal_Bool        Export();

    static void             HandleGraphicFilterError( USHORT nFilterError, ULONG nStreamError = ERRCODE_NONE );

private:

    static GDIMetaFile      ImplRemoveClipRegionActions( const GDIMetaFile& rMtf );
    static BitmapEx         ImplGetBitmapFromMetaFile( const GDIMetaFile& rMtf, BOOL bTransparent, const Size* pSizePixel = NULL );

    bool mbHideSpell;

};

#endif // _SD_SDGRFFILTER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.242); FILE MERGED 2005/09/05 13:20:00 rt 1.5.242.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sdgrffilter.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:59:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SD_SDGRFFILTER_HXX
#define _SD_SDGRFFILTER_HXX

#include <tools/errinf.hxx>
#include "sdfilter.hxx"

// ---------------
// - SdCGMFilter -
// ---------------

class SdGRFFilter : public SdFilter
{
public:
    SdGRFFilter (
        SfxMedium& rMedium,
        ::sd::DrawDocShell& rDocShell,
        sal_Bool bShowProgress );
    virtual ~SdGRFFilter (void);

    sal_Bool        Import();
    sal_Bool        Export();

    static void             HandleGraphicFilterError( USHORT nFilterError, ULONG nStreamError = ERRCODE_NONE );

private:

    static GDIMetaFile      ImplRemoveClipRegionActions( const GDIMetaFile& rMtf );
    static BitmapEx         ImplGetBitmapFromMetaFile( const GDIMetaFile& rMtf, BOOL bTransparent, const Size* pSizePixel = NULL );

    bool mbHideSpell;

};

#endif // _SD_SDGRFFILTER_HXX
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <cassert>
#include "sampler.h"
#include "vec2.h"
#include "bsdf.h"

using namespace std;

struct sas
{
  sas() : tp(0), n(0) { }
  scalar tp;
  int n;
};

scalar solid_angle_area(scalar t0, scalar t1, scalar p0, scalar p1)
{
  return (t1 - t0) * (cos(p0) - cos(p1));
}

scalar solid_angle_weighted_area(scalar t0, scalar t1, scalar p0, scalar p1)
{
  return (t1 - t0) * (cos(2 * p0) - cos(2 * p1)) * 0.5;
}

void compare_bsdf(const BRDF& brdf, uint num_samples)
{
  UniformSampler sampler;

  Vec3 incoming_dir = Vec3{0.0f, sqrt(0.5), sqrt(0.5)};

  const int theta_grid = 1;
  const int phi_grid = 1000;

  sas r[theta_grid][phi_grid];

  for (auto i = 0u; i < num_samples; ++i)
  {
    // compute the pdf
    scalar p;
    scalar refl;
    Vec3 dir = brdf.sample(incoming_dir, sampler, p, refl);

    scalar theta, phi;
    dir.to_euler(theta, phi);

    int theta_i = theta / (2 * PI) * theta_grid ;
    int phi_i = phi / (PI / 2) * phi_grid ;
    assert(0 <= theta_i  && theta_i < theta_grid);
    assert(0 <= phi_i  && phi_i < phi_grid);
    r[theta_i][phi_i].n += 1;
    r[theta_i][phi_i].tp += p;
  }

  const int num_cells = theta_grid * phi_grid;

  scalar total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar disp = num_cells * scalar(r[y][x].n) / num_samples;
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      scalar b = num_cells * scalar(r[y][x].n) / num_samples;
      scalar disp = a - b;
      cout << setw(12) << disp * 100;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

}

int main(int argc, char** args)
{
  //compare_bsdf(OrenNayar(1.0, 0.3), 100000000);
  UniformSampler sampler;
  for (int i = 0; i < 1000; ++i)
  {
    auto v = uniform_sample_disc(sampler.sample_2d());
    cout << v[0] << " " << v[1] << endl;
  }
}
<commit_msg>Adds sampling tests<commit_after>#include <iostream>
#include <iomanip>
#include <cassert>
#include "materials/multilayered.h"
#include "geometries.h"
#include "sampler.h"
#include "vec2.h"
#include "bsdf.h"

using namespace std;

struct sas
{
  sas() : tp(0), n(0) { }
  scalar tp;
  int n;
};

scalar solid_angle_area(scalar t0, scalar t1, scalar p0, scalar p1)
{
  return (t1 - t0) * (cos(p0) - cos(p1));
}

scalar solid_angle_weighted_area(scalar t0, scalar t1, scalar p0, scalar p1)
{
  return (t1 - t0) * (cos(2 * p0) - cos(2 * p1)) * 0.5;
}

void compare_bsdf(const BRDF& brdf, uint num_samples)
{
  UniformSampler sampler;

  Vec3 incoming_dir = Vec3{0.0f, sqrt(0.5), sqrt(0.5)};

  const int theta_grid = 1;
  const int phi_grid = 1000;

  sas r[theta_grid][phi_grid];

  for (auto i = 0u; i < num_samples; ++i)
  {
    // compute the pdf
    scalar p;
    scalar refl;
    Vec3 dir = brdf.sample(incoming_dir, sampler, p, refl);

    scalar theta, phi;
    dir.to_euler(theta, phi);

    int theta_i = theta / (2 * PI) * theta_grid ;
    int phi_i = phi / (PI / 2) * phi_grid ;
    assert(0 <= theta_i  && theta_i < theta_grid);
    assert(0 <= phi_i  && phi_i < phi_grid);
    r[theta_i][phi_i].n += 1;
    r[theta_i][phi_i].tp += p;
  }

  const int num_cells = theta_grid * phi_grid;

  scalar total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar disp = num_cells * scalar(r[y][x].n) / num_samples;
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      scalar b = num_cells * scalar(r[y][x].n) / num_samples;
      scalar disp = a - b;
      cout << setw(12) << disp * 100;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;
}

void compare_tld(const GTR& tld, uint num_samples)
{
  UniformSampler sampler;

  const int theta_grid = 1;
  const int phi_grid = 100;

  sas r[theta_grid][phi_grid];

  for (auto i = 0u; i < num_samples; ++i)
  {
    // compute the pdf
    scalar p;
    Vec3 dir = tld.sample_micronormal(sampler, p);

    scalar theta, phi;
    dir.to_euler(theta, phi);

    int theta_i = theta / (2 * PI) * theta_grid ;
    int phi_i = phi / (PI / 2) * phi_grid ;
    assert(0 <= theta_i  && theta_i < theta_grid);
    assert(0 <= phi_i  && phi_i < phi_grid);
    r[theta_i][phi_i].n += 1;
    r[theta_i][phi_i].tp += p;
  }

  const int num_cells = theta_grid * phi_grid;

  scalar total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar disp = num_cells * scalar(r[y][x].n) / num_samples;
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar disp = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      cout << setw(12) << disp;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;

  total_integral = 0;
  for (int y = 0; y < theta_grid; ++y)
  {
    scalar t0 = y * 2 * PI / theta_grid;
    scalar t1 = (y + 1)* 2 * PI / theta_grid;
    for (int x = 0; x < phi_grid; ++x)
    {
      scalar p0 = x * 0.5 * PI / phi_grid;
      scalar p1 = (x + 1) * 0.5 * PI / phi_grid;
      scalar a = r[y][x].n == 0 ? 0 : num_cells * (r[y][x].tp / r[y][x].n) * solid_angle_area(t0, t1, p0, p1);
      scalar b = num_cells * scalar(r[y][x].n) / num_samples;
      scalar disp = a - b;
      cout << setw(12) << disp * 100;
      total_integral += disp;
    }
    cout << endl;
  }
  cout << total_integral / num_cells << endl << endl;
}

scalar compute_rho_hd(shared_ptr<Material> mat, const Vec3& incoming, uint num_samples)
{
  spectrum r;

  auto p = make_shared<Plane>(Vec3(0, 0, 1), 0.0);
  Shape s(p, mat);
  Ray ray(incoming, -incoming);
  UniformSampler sampler;

  auto t = p->intersect(ray);
  assert(t.is());
  Intersection isect(&s, 0, ray, t.get());

  uint valid_samples = 0;

  for (auto i = 0u; i < num_samples; ++i)
  {
    scalar p;
    spectrum reflectance;
    Vec3 d = mat->sample_bsdf(isect, -ray.direction.normal(), sampler, p, reflectance);
    if (p == 0)
      continue;
    r += reflectance / p * d.z;
    ++valid_samples;
  }

  return (r / scalar(num_samples)).luminance();
}

int main(int argc, char** args)
{
  using namespace refraction_index;

  //compare_bsdf(OrenNayar(1.0, 0.3), 100000000);
  //auto mat = make_shared<MirrorMaterial>();
  auto base_mat = make_shared<RoughColorMaterial>(0.0, spectrum(0.0));
  auto mat = make_shared<MaterialTLDAdapter>(AIR, CROWN_GLASS,
                                             make_shared<GTR>(0.001));
  vector<scalar> angles({0.0, 5.0, 10.0, 20.0, 30.0, 45.0, 60.0, 80.0, 85.0, 89.0});

  for (auto deg: angles)
  {
    scalar angle = deg * PI / 180.0;
    auto incoming = Vec3(sin(angle), 0.0, cos(angle)).normal();

    cerr << setw(4) << deg << ": " << compute_rho_hd(mat, incoming, 1000000)
         << " "
         << fresnel_reflectance_schlick(incoming, Vec3::z_axis, AIR, CROWN_GLASS)
         << endl;
  }

//  compare_tld(GTR(0.1), 10000000);
  return 0;
}
<|endoftext|>


<commit_before>#include "includes/peciman.h"
#include <graphics.h>

int CanMovePeciman(pacmanController peciman, int nextDirection) // Untuk mencek apakah ada tembok atau tidak, jika tidak maka akan return true
{
    switch(nextDirection) {
        case RIGHT : return levelMap[peciman.pos.x+1][peciman.pos.y].Wall == REMPTY;
        case LEFT : return levelMap[peciman.pos.x-1][peciman.pos.y].Wall == REMPTY;
        case UP : return levelMap[peciman.pos.x][peciman.pos.y-1].Wall == REMPTY;
        case DOWN : return levelMap[peciman.pos.x][peciman.pos.y+1].Wall == REMPTY;
    }
}

void DrawPacman(pacmanController peciman)
{
    int posX = peciman.pos.x * GRIDSIZE;
    //peciman.pos.x *= GRIDSIZE;
    int posY = peciman.pos.y * GRIDSIZE;
    switch (peciman.direction) {
      case UP:
          if (peciman.state == 1) // if open
          {
            readimagefile("assets/images/PacmanUpOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);

          }
          else  // close
          {
            readimagefile("assets/images/PacmanUpClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
          }
      break;

      case DOWN:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanDownOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else // close
              {
                readimagefile("assets/images/PacmanDownClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }

      break;

      case RIGHT:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanRightOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else // close
              {
                readimagefile("assets/images/PacmanRightClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              break;

      case LEFT:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanLeftOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else// close
              {
                readimagefile("assets/images/PacmanLeftClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
      break;
    }
    if (CanMovePeciman(peciman , peciman.nextDirection))
    {
        peciman.direction = peciman.nextDirection;
    }
}

void InitPacman (pacmanController *peciman, int i, int j) // keadaan awal peciman
{
    peciman->pos.x = i;
    peciman->pos.y = j;
    peciman->direction = RIGHT;
    peciman->nextDirection = RIGHT;
    peciman->state = 1;
}

void changeState(pacmanController *peciman)
{
    if (peciman->state == 0)
    {
      peciman->state = 1; // change to open
    }
    else
    {
      peciman->state = 0; // change to close
    }
}

void BlackSquare(int posX, int posY)
{
    setcolor(0);
    bar(posX * GRIDSIZE, posY* GRIDSIZE, (posX * GRIDSIZE) + GRIDSIZE, posY*GRIDSIZE + GRIDSIZE);
}

void Move(pacmanController *peciman)
{
    setfillstyle(SOLID_FILL, 0);
    switch(peciman->direction)
    {
        case RIGHT :
            if (peciman->pos.x == 19){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 0;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            }

            else if(levelMap[peciman->pos.x+1][peciman->pos.y].Wall == 0){ // Cek apakah ada tembok atau tidak dan print ke array index selanjutnya
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.x++;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;

        case LEFT :
            if (peciman->pos.x == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 19 ;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            }

            else if(levelMap[peciman->pos.x-1][peciman->pos.y].Wall == 0 ){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.x--;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            break;

        case UP :
            if (peciman->pos.y == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 19;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            }

            else if(levelMap[peciman->pos.x][peciman->pos.y-1].Wall == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.y--;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;

        case DOWN :
            if (peciman->pos.y == 19){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.y = 0;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            }

            else if(levelMap[peciman->pos.x][peciman->pos.y+1].Wall == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.y++;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;
    }
    DrawPacman(*peciman); // men-draw pacman sesuai dengan arah yang telah ditentukan
}
<commit_msg>Remove some useless code<commit_after>#include "includes/peciman.h"
#include <graphics.h>

int CanMovePeciman(pacmanController peciman, int nextDirection) // Untuk mencek apakah ada tembok atau tidak, jika tidak maka akan return true
{
    switch(nextDirection) {
        case RIGHT : return levelMap[peciman.pos.x+1][peciman.pos.y].Wall == REMPTY;
        case LEFT : return levelMap[peciman.pos.x-1][peciman.pos.y].Wall == REMPTY;
        case UP : return levelMap[peciman.pos.x][peciman.pos.y-1].Wall == REMPTY;
        case DOWN : return levelMap[peciman.pos.x][peciman.pos.y+1].Wall == REMPTY;
    }
}

void DrawPacman(pacmanController peciman)
{
    int posX = peciman.pos.x * GRIDSIZE;
    //peciman.pos.x *= GRIDSIZE;
    int posY = peciman.pos.y * GRIDSIZE;
    switch (peciman.direction) {
      case UP:
          if (peciman.state == 1) // if open
          {
            readimagefile("assets/images/PacmanUpOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);

          }
          else  // close
          {
            readimagefile("assets/images/PacmanUpClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
          }
      break;

      case DOWN:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanDownOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else // close
              {
                readimagefile("assets/images/PacmanDownClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }

      break;

      case RIGHT:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanRightOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else // close
              {
                readimagefile("assets/images/PacmanRightClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              break;

      case LEFT:
              if (peciman.state == 1) // if open
              {
                readimagefile("assets/images/PacmanLeftOpen.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
              else// close
              {
                readimagefile("assets/images/PacmanLeftClose.bmp", posX, posY, posX + GRIDSIZE, posY + GRIDSIZE);
              }
      break;
    }
    if (CanMovePeciman(peciman , peciman.nextDirection))
    {
        peciman.direction = peciman.nextDirection;
    }
}

void InitPacman (pacmanController *peciman, int i, int j) // keadaan awal peciman
{
    peciman->pos.x = i;
    peciman->pos.y = j;
    peciman->direction = RIGHT;
    peciman->nextDirection = peciman->direction;
    peciman->state = 1;
}

void changeState(pacmanController *peciman)
{
    if (peciman->state == 0)
    {
      peciman->state = 1; // change to open
    }
    else
    {
      peciman->state = 0; // change to close
    }
}

void BlackSquare(int posX, int posY)
{
    setcolor(0);
    bar(posX * GRIDSIZE, posY* GRIDSIZE, (posX * GRIDSIZE) + GRIDSIZE, posY*GRIDSIZE + GRIDSIZE);
}

void Move(pacmanController *peciman)
{
    setfillstyle(SOLID_FILL, 0);
    switch(peciman->direction)
    {
        case RIGHT :
            if (peciman->pos.x == 19){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 0;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            else if(levelMap[peciman->pos.x+1][peciman->pos.y].Wall == 0){ // Cek apakah ada tembok atau tidak dan print ke array index selanjutnya
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.x++;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;

        case LEFT :
            if (peciman->pos.x == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 19 ;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            else if(levelMap[peciman->pos.x-1][peciman->pos.y].Wall == 0 ){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.x--;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            break;

        case UP :
            if (peciman->pos.y == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.x = 19;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            else if(levelMap[peciman->pos.x][peciman->pos.y-1].Wall == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.y--;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;

        case DOWN :
            if (peciman->pos.y == 19){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            peciman->pos.y = 0;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }

            else if(levelMap[peciman->pos.x][peciman->pos.y+1].Wall == 0){
            BlackSquare(peciman->pos.x, peciman->pos.y);
            levelMap[peciman->pos.x][peciman->pos.y].Object = REMPTY;
            peciman->pos.y++;
            levelMap[peciman->pos.x][peciman->pos.y].Object = RPACMAN;
            }
            break;
    }
    DrawPacman(*peciman); // men-draw pacman sesuai dengan arah yang telah ditentukan
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "vao.h"

bool gl::vao::use_vao = true;

gl::vao::vao()
{
	if (!use_vao)
		return;

	glGenVertexArrays(1, *this);
}

gl::vao::~vao()
{
	if (!use_vao)
		return;

	glDeleteVertexArrays(1, *this);
}

void gl::vao::setup_attrib(gl::buffer &buffer, int attrib, int size, int type, int stride, int offset)
{
	if (use_vao) {
		bind();
		buffer.bind(buffer::ARRAY_BUFFER);
		glVertexAttribPointer(attrib, size, type, GL_FALSE, stride, reinterpret_cast<void*>(offset));
		glEnableVertexAttribArray(attrib);
	}
	else {
		params.push_back({buffer, attrib, size, type, stride, offset});
		active = nullptr;
	}
}

void gl::vao::setup_ebo(buffer &e)
{
	if (use_vao) {
		bind();
		e.bind(buffer::ELEMENT_ARRAY_BUFFER);
	}
	else {
		ebo = &e;
		active = nullptr;
	}
}

void gl::vao::bind()
{
	if (active == this)
		return;
	active = this;

	if (use_vao) {
		glBindVertexArray(*this);
	}
	else {
		for (attrib_params &param : params) {
			param.buffer.bind(gl::buffer::ARRAY_BUFFER);
			glVertexAttribPointer(param.attrib, param.size, param.type, GL_FALSE, param.stride, reinterpret_cast<void*>(param.offset));
			glEnableVertexAttribArray(param.attrib);
		}

		for (size_t i = params.size(); i < 4; i++)
			glDisableVertexAttribArray(i);

		if (ebo)
			ebo->bind(gl::buffer::ELEMENT_ARRAY_BUFFER);
		else
			gl::buffer::unbind(gl::buffer::ELEMENT_ARRAY_BUFFER);
	}
}

void gl::vao::unbind()
{
	active = nullptr;
}
<commit_msg>really unbind vao<commit_after>#include "stdafx.h"
#include "vao.h"

bool gl::vao::use_vao = true;

gl::vao::vao()
{
	if (!use_vao)
		return;

	glGenVertexArrays(1, *this);
}

gl::vao::~vao()
{
	if (!use_vao)
		return;

	unbind();
	glDeleteVertexArrays(1, *this);
}

void gl::vao::setup_attrib(gl::buffer &buffer, int attrib, int size, int type, int stride, int offset)
{
	if (use_vao) {
		bind();
		buffer.bind(buffer::ARRAY_BUFFER);
		glVertexAttribPointer(attrib, size, type, GL_FALSE, stride, reinterpret_cast<void*>(offset));
		glEnableVertexAttribArray(attrib);
	}
	else {
		params.push_back({buffer, attrib, size, type, stride, offset});
		active = nullptr;
	}
}

void gl::vao::setup_ebo(buffer &e)
{
	if (use_vao) {
		bind();
		e.bind(buffer::ELEMENT_ARRAY_BUFFER);
	}
	else {
		ebo = &e;
		active = nullptr;
	}
}

void gl::vao::bind()
{
	if (active == this)
		return;
	active = this;

	if (use_vao) {
		glBindVertexArray(*this);
	}
	else {
		for (attrib_params &param : params) {
			param.buffer.bind(gl::buffer::ARRAY_BUFFER);
			glVertexAttribPointer(param.attrib, param.size, param.type, GL_FALSE, param.stride, reinterpret_cast<void*>(param.offset));
			glEnableVertexAttribArray(param.attrib);
		}

		for (size_t i = params.size(); i < 4; i++)
			glDisableVertexAttribArray(i);

		if (ebo)
			ebo->bind(gl::buffer::ELEMENT_ARRAY_BUFFER);
		else
			gl::buffer::unbind(gl::buffer::ELEMENT_ARRAY_BUFFER);
	}
}

void gl::vao::unbind()
{
	active = nullptr;
	if (use_vao) {
		glBindVertexArray(0);
	}
	else {
		for (size_t i = 0; i < 4; i++)
			glDisableVertexAttribArray(i);
	}
}
<|endoftext|>


<commit_before>#include "uspeech.h"

char signal::getPhoneme(){
	sample();
	if(power()>SILENCE){
		int k = complexity(power());
		overview[6] = overview[5];
		overview[5] = overview[4];
		overview[4] = overview[3];
		overview[3] = overview[2];
		overview[2] = overview[1];
		overview[1] = overview[0];
		overview[0] = k;
		int coeff = 0;
		char f = 0;
		while(f<6){
			coeff += overview[f];
			f++;
		}
		coeff /= 7;
#if F_DETECTION > 0
        micPower = 0.05 * maxPower() + (1 - 0.05) * micPower;
        if (micPower>37) {
            return 'f';
        }
#endif
		if(coeff<30 && coeff>20){
			return 'u';
		}
		else {
			if(coeff<33){
				return 'e';
			}
			else{
				if(coeff<46){
					return 'o';
				}
				else{
					if(coeff<60){
						return 'v';
					}
					else{
						if(coeff<80){
							return 'h';
						}
						else{
							if(coeff>80){
								return 's';
							}
							else{
								return 'm';
							}
						}
					}
				}
			}
		}
	}
	else{
		return ' ';
	}
}
void signal::formantAnal(){
	int i = 0;
	int k = 0;
	while(i<18){
		if((long)(filters[i]-filters[i-1]) > 0 & (long)(filters[i]-filters[i+1]) < 0){
			if(k < 3){
				formants[k] = i;
			}
		}
		i++;
	}
}<commit_msg>Added comments<commit_after>#include "uspeech.h"
/**
* The recognizer function
*/
char signal::getPhoneme(){
	sample();
	if(power()>SILENCE){
		//Low pass filter for noise removal
		int k = complexity(power());
		overview[6] = overview[5];
		overview[5] = overview[4];
		overview[4] = overview[3];
		overview[3] = overview[2];
		overview[2] = overview[1];
		overview[1] = overview[0];
		overview[0] = k;
		int coeff = 0;
		char f = 0;
		while(f<6){
			coeff += overview[f];
			f++;
		}
		coeff /= 7;
		//Serial.println(coeff); //Use this for debugging
#if F_DETECTION > 0
        micPower = 0.05 * maxPower() + (1 - 0.05) * micPower;
        //Serial.println(micPower)//If you are having trouble with fs

        if (micPower > 37/*Replace this value (37) with your own*/) {
            return 'f';
        }
#endif
	//Twiddle with the numbers here if your getting false triggers
	//This is the main recognizer part
		if(coeff<30 && coeff>20){
			return 'u';
		}
		else {
			if(coeff<33){
				return 'e';
			}
			else{
				if(coeff<46){
					return 'o';
				}
				else{
					if(coeff<60){
						return 'v';
					}
					else{
						if(coeff<80){
							return 'h';
						}
						else{
							if(coeff>80){
								return 's';
							}
							else{
								return 'm';
							}
						}
					}
				}
			}
		}
	}
	else{
		return ' ';
	}
}
void signal::formantAnal(){
	int i = 0;
	int k = 0;
	while(i<18){
		if((long)(filters[i]-filters[i-1]) > 0 & (long)(filters[i]-filters[i+1]) < 0){
			if(k < 3){
				formants[k] = i;
			}
		}
		i++;
	}
}
<|endoftext|>