<commit_before>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>

#include <usTestingConfig.h>

#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"

#include <assert.h>

#include <set>

US_USE_NAMESPACE

namespace {

std::string GetResourceContent(const ModuleResource& resource)
{
  std::string line;
  ModuleResourceStream rs(resource);
  std::getline(rs, line);
  return line;
}

struct ResourceComparator {
  bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
  {
    return mr1 < mr2;
  }
};

void testResourceOperators(Module* module)
{
  std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
  US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
  US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}

void testResourcesWithStaticImport(Module* module)
{
  ModuleResource resource = module->GetResource("res.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
  std::string line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")

  resource = module->GetResource("dynamic.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")

  resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "static", "Check dynamic resource content")

  std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
  std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
  US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  line = GetResourceContent(resources[1]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
  US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  // skip foo.txt
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  // skip special_chars.dummy.txt
  line = GetResourceContent(resources[5]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}

} // end unnamed namespace

int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
  US_TEST_BEGIN("StaticModuleResourceTest");

  ModuleContext* mc = GetModuleContext();
  assert(mc);

#ifdef US_BUILD_SHARED_LIBS
  SharedLibraryHandle libB("TestModuleB");

  try
  {
    libB.Load();
  }
  catch (const std::exception& e)
  {
    US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
  }

  Module* module = ModuleRegistry::GetModule("TestModuleB Module");
  US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")

  US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
  Module* module = mc->GetModule();
#endif

  testResourceOperators(module);
  testResourcesWithStaticImport(module);

#ifdef US_BUILD_SHARED_LIBS
  ModuleResource resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")

  libB.Unload();

  US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif

  US_TEST_END()
}
<commit_msg>Fix unused variable error in release builds.<commit_after>/*=============================================================================

  Library: CppMicroServices

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>

#include <usTestingConfig.h>

#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"

#include <assert.h>

#include <set>

US_USE_NAMESPACE

namespace {

std::string GetResourceContent(const ModuleResource& resource)
{
  std::string line;
  ModuleResourceStream rs(resource);
  std::getline(rs, line);
  return line;
}

struct ResourceComparator {
  bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
  {
    return mr1 < mr2;
  }
};

void testResourceOperators(Module* module)
{
  std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
  US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
  US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}

void testResourcesWithStaticImport(Module* module)
{
  ModuleResource resource = module->GetResource("res.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
  std::string line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")

  resource = module->GetResource("dynamic.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")

  resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
  line = GetResourceContent(resource);
  US_TEST_CONDITION(line == "static", "Check dynamic resource content")

  std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
  std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
  US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  line = GetResourceContent(resources[1]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
  US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
  line = GetResourceContent(resources[0]);
  US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
  // skip foo.txt
  line = GetResourceContent(resources[2]);
  US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
  line = GetResourceContent(resources[3]);
  US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
  // skip special_chars.dummy.txt
  line = GetResourceContent(resources[5]);
  US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}

} // end unnamed namespace

int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
  US_TEST_BEGIN("StaticModuleResourceTest");

  assert(GetModuleContext());

#ifdef US_BUILD_SHARED_LIBS
  SharedLibraryHandle libB("TestModuleB");

  try
  {
    libB.Load();
  }
  catch (const std::exception& e)
  {
    US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
  }

  Module* module = ModuleRegistry::GetModule("TestModuleB Module");
  US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")

  US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
  Module* module = mc->GetModule();
#endif

  testResourceOperators(module);
  testResourcesWithStaticImport(module);

#ifdef US_BUILD_SHARED_LIBS
  ModuleResource resource = module->GetResource("static.txt");
  US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")

  libB.Unload();

  US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif

  US_TEST_END()
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>

using namespace std;

void userin(string &);
void print(const string);

void userin(string &s)
{
	getline(cin,s);
	return;
}

void print(const string s)
{
	cout << "Your message is as follows:" << endl;
	cout << s << endl;
}

int main()
{
	string uin;

	userin(uin);
	print(uin);

	return 0;
}
<commit_msg>added post confirmation<commit_after>#include <iostream>
#include <string>

using namespace std;

void userin(string &);
void print(const string);

void userin(string &s)
{
	getline(cin,s);

	return;
}

void print(const string s)
{
	char check = ' ';
	bool cont = false;

	cout << "Your message is as follows:" << endl;
	cout << s << endl;

	cout << "Your message will tweet as follows:" << endl;
	cout << s << "(" << s.size() << "/#" <<  endl;

	while(!cont)
	{
		cout << "Do you wish to post? (Y or N then hit enter): ";
		cin >> check;

		if((check == 'Y') || (check == 'y') || (check == 'N') || (check == 'n'))
		{
			cont = true;
		}
		else
		{
			cout << "Please enter a valid choice. Y or y for yes, N or n for no." << endl;
		}
	}

	if(check == 'Y' || check == 'y')
	{
		//post to twitter. push to twitter push library
	}

	return;
}

int main()
{
	string uin;

	userin(uin);
	print(uin);

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
#include <map>
#include <typeinfo>
#include <stdexcept>
#include <cstdlib>
#include <ctype.h>

#define PRINT_LINE (std::cout << "line: " << __LINE__ << std::endl)

enum TokenType{
  TOKEN_BRACKET_OPEN,
  TOKEN_BRACKET_CLOSE,
  TOKEN_SYMBOL,
  TOKEN_STRING,
  TOKEN_INTEGER,
  TOKEN_NIL,
};

class Token {
public:
  TokenType type;
  std::string value;

  Token(TokenType atype) : type(atype), value(std::string()) {
  }

  Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {
  }

  std::string str() {
    std::stringstream ss;
    ss << "Token(" << type << ", " << value << ")";
    return ss.str();
  }
};

namespace Lisp {
  class Expression;
}

// memory allocated exprs
std::list<Lisp::Expression*> objects;

namespace Lisp {
  class Expression {
  public:
    Expression() {
      objects.push_back(this);
    }
    virtual ~Expression() {}

    virtual std::string lisp_str() = 0;
  };

  class CallFunction : public Expression {
  public:
    std::string name;
    std::vector<Expression*> args;

    CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}

    std::string lisp_str() {
      std::stringstream ss;
      ss << "(" << name << " ";
      for(Expression* arg : args) {
        ss << arg->lisp_str() << " ";
      }
      ss << ")";
      return ss.str();
    }
  };

  class String : public Expression {
  public:
    std::string value;

    String(std::string &avalue) : value(avalue) {}

    std::string lisp_str() { return '"' + value + '"'; }
  };

  class Integer : public Expression {
  public:
    unsigned long value;

    Integer(std::string &avalue)  : value(std::atol(avalue.c_str())) {}
    Integer(unsigned long avalue) : value(avalue) {}

    std::string lisp_str() { return std::to_string(value); }
  };

  class Symbol : public Expression {
  public:
    std::string value;

    Symbol(std::string &avalue) : value(avalue) {}

    std::string lisp_str() { return value; }
  };

  class List : public Expression {
  public:
    std::vector<Expression*> values;

    List(std::vector<Expression*> &avalues) : values(avalues) {}

    std::string lisp_str() {
      std::stringstream ss;
      ss << "(";
      for(Expression* value : values) {
        ss << value->lisp_str() << " ";
      }
      ss << ")";
      return ss.str();
    }
  };

  // TODO: RubyみたくExpression*に埋め込みたい
  class Nil : public Expression {
  public:
    Nil() {}

    std::string lisp_str() { return "nil"; }
  };

  class T : public Expression {
  public:
    T() {}

    std::string lisp_str() { return "T"; }
  };

  class Parser {
  public:
    std::vector<Expression*> parse(const std::string &code) {
      tokens = tokenize(code);

      /*for(auto tok : tokens) {
        std::cout << tok->str() << std::endl;
      }*/

      std::vector<Expression*> exprs;
      while(!tokens.empty()) {
        exprs.push_back(parse_expr());
      }
      return exprs;
    }

  private:
    std::list<Token*> tokens;

    inline Token* cur_token() {
      return tokens.empty() ? nullptr : tokens.front();
    }

    void consume_token() {
      auto ctoken = cur_token();
      if(ctoken) delete ctoken;

      if(!tokens.empty()) tokens.pop_front();
    }

    Expression* parse_call_fun() {
      consume_token();
      if(cur_token()->type != TOKEN_SYMBOL) {
        //TODO: raise an error
      }
      std::string name;
      name = cur_token()->value;

      consume_token();
      std::vector<Expression*> args;
      for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {
        args.push_back(parse_expr());
      }

      consume_token();

      return new CallFunction(name, args);
    }

    Expression* parse_expr() {
      switch(cur_token()->type) {
        case TOKEN_BRACKET_OPEN:
          return parse_call_fun();
        case TOKEN_STRING:
          return new String(cur_token()->value);
        case TOKEN_NIL:
          return new Nil();
        case TOKEN_SYMBOL:
          return new Symbol(cur_token()->value);
        case TOKEN_INTEGER:
          return new Integer(cur_token()->value);
        default:
          throw std::logic_error("unknown token: " + std::to_string(cur_token()->type));
          return nullptr;
      }
    }

    bool is_symbol(char c) {
      return isalnum(c) && isalpha(c);
    }

    bool is_number(char c) {
      return isdigit(c);
    }

    std::list<Token*> tokenize(const std::string &code) {
      std::list<Token*> tokens;

      for(size_t i = 0 ; i < code.size() - 1 ; i++) { //TODO: -1を修正(EOFっぽい?)
        char ch = code[i];
        if(ch == '(')
          tokens.push_back(new Token(TOKEN_BRACKET_OPEN));
        else if(ch == ')')
          tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));
        else if(ch == '"') { // string
          i++;

          size_t token_len = 0;
          while(code[i + token_len] != '"') {
            token_len++;
            if(i + token_len >= code.size()) {
              //TODO: raise an error
            }
          }
          tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));
          i += token_len;
        }
        else if(ch == ' ' || ch == '\n')
          ;//skip
        else if(is_number(ch)) {
          size_t token_len = 0;
          while(is_number(code[i + token_len])) {
            token_len++;
            // TODO: raise an error
          }

          std::string token_val = code.substr(i, token_len);
          tokens.push_back(new Token(TOKEN_INTEGER, token_val));

          i += token_len;
        }
        else { // symbol
          size_t token_len = 0;
          while(is_symbol(code[i + token_len])) {
            token_len++;
            if(i + token_len >= code.size()) {
              //TODO: raise an error
            }
          }

          std::string token_val = code.substr(i, token_len);
          TokenType token_type;
          if(token_val == "nil")
            token_type = TOKEN_NIL;
          else
            token_type = TOKEN_SYMBOL;

          if(token_type == TOKEN_SYMBOL)
            tokens.push_back(new Token(TOKEN_SYMBOL, token_val));
          else
            tokens.push_back(new Token(token_type));

          i += token_len - 1;
        }
      }

      return tokens;
    }
  };

  class Evaluator {
    std::map<std::string, Expression*> env;

    Expression* eval_expr(Expression* expr) {
      const std::type_info& id = typeid(*expr);
      if(id == typeid(CallFunction)) {
        auto call_fun = (CallFunction*)expr;
        auto name = call_fun->name;
        if(name == "print") {
          std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;
          return new Nil();
        }
        else if(name == "setq") {
          env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];
          return new Nil();
        }
        else if(name == "atom") {
          auto val = evaluate(call_fun->args[0]);
          if(typeid(*val) != typeid(List)) return new T();
          else return new Nil();
        }
        else if(name == "list") {
          auto args = call_fun->args;
          for(size_t i = 0 ; i < args.size() ; i++) {
            args[i] = evaluate(args[i]);
          }
          return new List(args);
        }
      }
      else if(id == typeid(Symbol)) {
        return env[((Symbol*)expr)->value];
      }

      return expr;
    }

  public:
    Expression* evaluate(Expression* expr) {
      return eval_expr(expr);
    }
  };
}

int main() {
  using namespace std;

  string code;
  //code.reserve(1024);

  char ch;
  while((ch = cin.get()) != std::char_traits<char>::eof()) {
    code.push_back(ch);
  }

  Lisp::Parser parser;
  auto exprs = parser.parse(code);

  Lisp::Evaluator evaluator;
  for(size_t i = 0 ; i < exprs.size() ; i++) {
    exprs[i] = evaluator.evaluate(exprs[i]);
  }

  // fake GC
  for(auto expr : objects) {
    delete expr;
  }

  return 0;
}
<commit_msg>+関数を実装した<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
#include <map>
#include <typeinfo>
#include <stdexcept>
#include <cstdlib>
#include <ctype.h>

#define PRINT_LINE (std::cout << "line: " << __LINE__ << std::endl)

enum TokenType{
  TOKEN_BRACKET_OPEN,
  TOKEN_BRACKET_CLOSE,
  TOKEN_SYMBOL,
  TOKEN_STRING,
  TOKEN_INTEGER,
  TOKEN_NIL,
};

class Token {
public:
  TokenType type;
  std::string value;

  Token(TokenType atype) : type(atype), value(std::string()) {
  }

  Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {
  }

  std::string str() {
    std::stringstream ss;
    ss << "Token(" << type << ", " << value << ")";
    return ss.str();
  }
};

namespace Lisp {
  class Expression;
}

// memory allocated exprs
std::list<Lisp::Expression*> objects;

namespace Lisp {
  class Expression {
  public:
    Expression() {
      objects.push_back(this);
    }
    virtual ~Expression() {}

    virtual std::string lisp_str() = 0;
  };

  class CallFunction : public Expression {
  public:
    std::string name;
    std::vector<Expression*> args;

    CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}

    std::string lisp_str() {
      std::stringstream ss;
      ss << "(" << name << " ";
      for(Expression* arg : args) {
        ss << arg->lisp_str() << " ";
      }
      ss << ")";
      return ss.str();
    }
  };

  class String : public Expression {
  public:
    std::string value;

    String(std::string &avalue) : value(avalue) {}

    std::string lisp_str() { return '"' + value + '"'; }
  };

  class Integer : public Expression {
  public:
    unsigned long value;

    Integer(std::string &avalue)  : value(std::atol(avalue.c_str())) {}
    Integer(unsigned long avalue) : value(avalue) {}

    std::string lisp_str() { return std::to_string(value); }
  };

  class Symbol : public Expression {
  public:
    std::string value;

    Symbol(std::string &avalue) : value(avalue) {}

    std::string lisp_str() { return value; }
  };

  class List : public Expression {
  public:
    std::vector<Expression*> values;

    List(std::vector<Expression*> &avalues) : values(avalues) {}

    std::string lisp_str() {
      std::stringstream ss;
      ss << "(";
      for(Expression* value : values) {
        ss << value->lisp_str() << " ";
      }
      ss << ")";
      return ss.str();
    }
  };

  // TODO: RubyみたくExpression*に埋め込みたい
  class Nil : public Expression {
  public:
    Nil() {}

    std::string lisp_str() { return "nil"; }
  };

  class T : public Expression {
  public:
    T() {}

    std::string lisp_str() { return "T"; }
  };

  class Parser {
  public:
    std::vector<Expression*> parse(const std::string &code) {
      tokens = tokenize(code);

      /*for(auto tok : tokens) {
        std::cout << tok->str() << std::endl;
      }*/

      std::vector<Expression*> exprs;
      while(!tokens.empty()) {
        exprs.push_back(parse_expr());
      }
      return exprs;
    }

  private:
    std::list<Token*> tokens;

    inline Token* cur_token() {
      return tokens.empty() ? nullptr : tokens.front();
    }

    void consume_token() {
      auto ctoken = cur_token();
      if(ctoken) delete ctoken;

      if(!tokens.empty()) tokens.pop_front();
    }

    Expression* parse_call_fun() {
      consume_token();
      if(cur_token()->type != TOKEN_SYMBOL) {
        //TODO: raise an error
      }
      std::string name;
      name = cur_token()->value;

      consume_token();
      std::vector<Expression*> args;
      for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {
        args.push_back(parse_expr());
      }

      consume_token();

      return new CallFunction(name, args);
    }

    Expression* parse_expr() {
      switch(cur_token()->type) {
        case TOKEN_BRACKET_OPEN:
          return parse_call_fun();
        case TOKEN_STRING:
          return new String(cur_token()->value);
        case TOKEN_NIL:
          return new Nil();
        case TOKEN_SYMBOL:
          return new Symbol(cur_token()->value);
        case TOKEN_INTEGER:
          return new Integer(cur_token()->value);
        default:
          throw std::logic_error("unknown token: " + std::to_string(cur_token()->type));
          return nullptr;
      }
    }

    bool is_symbol(char c) {
      return !isspace(c);
    }

    bool is_number(char c) {
      return isdigit(c);
    }

    std::list<Token*> tokenize(const std::string &code) {
      std::list<Token*> tokens;

      for(size_t i = 0 ; i < code.size() - 1 ; i++) { //TODO: -1を修正(EOFっぽい?)
        char ch = code[i];
        if(ch == '(')
          tokens.push_back(new Token(TOKEN_BRACKET_OPEN));
        else if(ch == ')')
          tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));
        else if(ch == '"') { // string
          i++;

          size_t token_len = 0;
          while(code[i + token_len] != '"') {
            token_len++;
            if(i + token_len >= code.size()) {
              //TODO: raise an error
            }
          }
          tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));
          i += token_len;
        }
        else if(ch == ' ' || ch == '\n')
          ;//skip
        else if(is_number(ch)) {
          size_t token_len = 0;
          while(is_number(code[i + token_len])) {
            token_len++;
            // TODO: raise an error
          }

          std::string token_val = code.substr(i, token_len);
          tokens.push_back(new Token(TOKEN_INTEGER, token_val));

          i += token_len;
        }
        else { // symbol
          size_t token_len = 0;
          while(is_symbol(code[i + token_len])) {
            token_len++;
            if(i + token_len >= code.size()) {
              //TODO: raise an error
            }
          }

          std::string token_val = code.substr(i, token_len);
          TokenType token_type;
          if(token_val == "nil")
            token_type = TOKEN_NIL;
          else
            token_type = TOKEN_SYMBOL;

          if(token_type == TOKEN_SYMBOL)
            tokens.push_back(new Token(TOKEN_SYMBOL, token_val));
          else
            tokens.push_back(new Token(token_type));

          i += token_len - 1;
        }
      }

      return tokens;
    }
  };

  class Evaluator {
    std::map<std::string, Expression*> env;

    Expression* eval_expr(Expression* expr) {
      const std::type_info& id = typeid(*expr);
      if(id == typeid(CallFunction)) {
        auto call_fun = (CallFunction*)expr;
        auto name = call_fun->name;
        if(name == "print") {
          std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;
          return new Nil();
        }
        else if(name == "setq") {
          env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];
          return new Nil();
        }
        else if(name == "atom") {
          auto val = evaluate(call_fun->args[0]);
          if(typeid(*val) != typeid(List)) return new T();
          else return new Nil();
        }
        else if(name == "+") {
          Integer* sum = new Integer(0);
          for(auto arg : call_fun->args) {
            sum->value += ((Integer*)evaluate(arg))->value;
          }
          return sum;
        }
        else if(name == "list") {
          auto args = call_fun->args;
          for(size_t i = 0 ; i < args.size() ; i++) {
            args[i] = evaluate(args[i]);
          }
          return new List(args);
        }
      }
      else if(id == typeid(Symbol)) {
        return env[((Symbol*)expr)->value];
      }

      return expr;
    }

  public:
    Expression* evaluate(Expression* expr) {
      return eval_expr(expr);
    }
  };
}

int main() {
  using namespace std;

  string code;
  //code.reserve(1024);

  char ch;
  while((ch = cin.get()) != std::char_traits<char>::eof()) {
    code.push_back(ch);
  }

  Lisp::Parser parser;
  auto exprs = parser.parse(code);

  Lisp::Evaluator evaluator;
  for(size_t i = 0 ; i < exprs.size() ; i++) {
    exprs[i] = evaluator.evaluate(exprs[i]);
  }

  // fake GC
  for(auto expr : objects) {
    delete expr;
  }

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sfxurl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dv $ $Date: 2001-07-12 07:43:50 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#include <filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>

SfxUrlDialog::SfxUrlDialog( Window *pParent )
    : ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
      aEdit( this, ResId(RID_URLOPEN_URL) ),
      aCancel( this, ResId(RID_URLOPEN_CANCEL) ),
      aOk( this, ResId(RID_URLOPEN_OK) )
{
    FreeResource();
}
<commit_msg>INTEGRATION: CWS ooo20040704 (1.2.562); FILE MERGED 2004/06/28 13:04:54 waratah 1.2.562.1: #i30812# reorder declaration to match header declares<commit_after>/*************************************************************************
 *
 *  $RCSfile: sfxurl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 15:40:54 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#include <filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>

SfxUrlDialog::SfxUrlDialog( Window *pParent )
    : ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
      aEdit( this, ResId(RID_URLOPEN_URL) ),
      aOk( this, ResId(RID_URLOPEN_OK) ),
      aCancel( this, ResId(RID_URLOPEN_CANCEL) )
{
    FreeResource();
}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include <limits.h>
#include <string.h>
#include "condor_debug.h"
#include "condor_daemon_core.h"
#include "forkwork.h"

// Instantiate the list of Cron Jobs

// Fork worker class constructor
ForkWorker::ForkWorker( void )
{
	valid = 0x5a5a;
	pid = -1;
	parent = -1;
}

// Fork worker class destructor
ForkWorker::~ForkWorker( void )
{
	if ( valid != 0x5a5a ) {
		dprintf( D_ALWAYS, "ForkWorker: delete invalid!!\n" );
	}
	valid = 0;
}

// Fork off a real worker job
ForkStatus
ForkWorker::Fork( void )
{
# ifndef WIN32
	// Fork
	pid = fork( );

	if ( pid < 0 ) {
		dprintf( D_ALWAYS, "ForkWorker::Fork: Fork failed\n" );
		return FORK_FAILED;
	} else if ( 0 == pid ) {
			// We should really be using DC::Create_Thread() for this.
			// However, since we're not, we need to call this method
			// to tell DC we're a forked child and that we want to
			// exit via exec(), not using exit(), so that destructors
			// don't get called...
		daemonCore->Forked_Child_Wants_Exit_By_Exec( true );
		parent = getppid( );
		pid = -1;
		return FORK_CHILD;
	} else {
		// Parent
		parent = getpid( );
		dprintf( D_JOB, "ForkWorker::Fork: New child of %d = %d\n",
				 parent,  pid );
		return FORK_PARENT;
	}
# else
	return FORK_FAILED;
# endif
}

// Fork work constructor
ForkWork::ForkWork( int max_workers )
{
# ifdef WIN32
	max_workers = 0;
# endif
	maxWorkers = max_workers;
	reaperId = -1;
	childExit = false;
}

// Finish initialization
int
ForkWork::Initialize( void )
{
	if( reaperId != -1 ) {
			// already initialized
		return 0;
	}

	// Register my reaper
	reaperId = daemonCore->Register_Reaper(
		"ForkWork_Reaper",
		(ReaperHandlercpp) &ForkWork::Reaper,
		"ForkWork Reaper",
		this );
    daemonCore->Set_Default_Reaper( reaperId );
	return 0;
}

// Fork work denstructor
ForkWork::~ForkWork( void )
{
	// Kill 'em all
	DeleteAll( );
}

// Set max # of children
void
ForkWork::setMaxWorkers( int max_workers )
{
# ifdef WIN32
	max_workers = 0;
# endif
	maxWorkers = max_workers;
	if ( workerList.Number() > maxWorkers ) {
		dprintf( D_JOB, "Warning: # forked workers exceeds max\n" );
	}
}

// Kill & delete all running workers
int
ForkWork::DeleteAll( void )
{
	ForkWorker	*worker;

	// Kill 'em all
	KillAll( true );

	// Walk through the list
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		workerList.DeleteCurrent( );
		delete worker;
	}
	return 0;
}

// Kill all running jobs
int
ForkWork::KillAll( bool force )
{
	ForkWorker	*worker;
	int		mypid = getpid();
	int		num_killed = 0;

	// Walk through the list
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		// If I'm the parent, kill it
		if ( mypid == worker->getParent() ) {
			num_killed++;
			if ( force ) {
				daemonCore->Send_Signal( worker->getPid(), SIGKILL );
			} else {
				daemonCore->Send_Signal( worker->getPid(), SIGTERM );
			}
		}
	}

	// If we killed some, log it...
	if ( num_killed ) {
		dprintf( D_JOB, "ForkWork %d: Killed %d jobs\n",
				 mypid, workerList.Number() );
	}
	return 0;
}

// Try to fork off another worker
ForkStatus
ForkWork::NewJob( void )
{
	// Any open slots?
	if ( workerList.Number() >= maxWorkers ) {
		if ( maxWorkers ) {
			dprintf( D_JOB, "ForkWork: busy\n" );
		}
		return FORK_BUSY;
	}

	// Fork off the child
	ForkWorker	*worker = new ForkWorker( );
	ForkStatus status = worker->Fork( );

	// Ok, let's see what happenned..
	if ( FORK_PARENT == status ) {
		workerList.Append( worker );
		return FORK_PARENT;
	} else if ( FORK_FAILED == status ) {
		delete worker;
		return FORK_FAILED;
	} else {
		delete worker;
		return FORK_CHILD;
	}
}

// Child worker is done
void
ForkWork::WorkerDone( int exit_status )
{
	dprintf( D_JOB,
			 "ForkWork: Child %d done, status %d\n",
			 getpid(), exit_status );
	exit( exit_status );
}

// Child reaper
int
ForkWork::Reaper( int exitPid, int /*exitStatus*/ )
{
	ForkWorker	*worker;

	// Let's find out if it's one of our children...
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		if ( worker->getPid() == exitPid ) {
			workerList.DeleteCurrent( );
			delete worker;
		return 0;
		}
	}
	return 0;
}
<commit_msg>Add basic logging to denote active workers. ===VersionHistory:None===<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include <limits.h>
#include <string.h>
#include "condor_debug.h"
#include "condor_daemon_core.h"
#include "forkwork.h"

// Instantiate the list of Cron Jobs

// Fork worker class constructor
ForkWorker::ForkWorker( void )
{
	valid = 0x5a5a;
	pid = -1;
	parent = -1;
}

// Fork worker class destructor
ForkWorker::~ForkWorker( void )
{
	if ( valid != 0x5a5a ) {
		dprintf( D_ALWAYS, "ForkWorker: delete invalid!!\n" );
	}
	valid = 0;
}

// Fork off a real worker job
ForkStatus
ForkWorker::Fork( void )
{
# ifndef WIN32
	// Fork
	pid = fork( );

	if ( pid < 0 ) {
		dprintf( D_ALWAYS, "ForkWorker::Fork: Fork failed\n" );
		return FORK_FAILED;
	} else if ( 0 == pid ) {
			// We should really be using DC::Create_Thread() for this.
			// However, since we're not, we need to call this method
			// to tell DC we're a forked child and that we want to
			// exit via exec(), not using exit(), so that destructors
			// don't get called...
		daemonCore->Forked_Child_Wants_Exit_By_Exec( true );
		parent = getppid( );
		pid = -1;
		return FORK_CHILD;
	} else {
		// Parent
		parent = getpid( );
		dprintf( D_JOB, "ForkWorker::Fork: New child of %d = %d\n",
				 parent,  pid );
		return FORK_PARENT;
	}
# else
	return FORK_FAILED;
# endif
}

// Fork work constructor
ForkWork::ForkWork( int max_workers )
{
# ifdef WIN32
	max_workers = 0;
# endif
	maxWorkers = max_workers;
	reaperId = -1;
	childExit = false;
}

// Finish initialization
int
ForkWork::Initialize( void )
{
	if( reaperId != -1 ) {
			// already initialized
		return 0;
	}

	// Register my reaper
	reaperId = daemonCore->Register_Reaper(
		"ForkWork_Reaper",
		(ReaperHandlercpp) &ForkWork::Reaper,
		"ForkWork Reaper",
		this );
    daemonCore->Set_Default_Reaper( reaperId );
	return 0;
}

// Fork work denstructor
ForkWork::~ForkWork( void )
{
	// Kill 'em all
	DeleteAll( );
}

// Set max # of children
void
ForkWork::setMaxWorkers( int max_workers )
{
# ifdef WIN32
	max_workers = 0;
# endif
	maxWorkers = max_workers;
	if ( workerList.Number() > maxWorkers ) {
		dprintf( D_JOB, "Warning: # forked workers exceeds max\n" );
	}
}

// Kill & delete all running workers
int
ForkWork::DeleteAll( void )
{
	ForkWorker	*worker;

	// Kill 'em all
	KillAll( true );

	// Walk through the list
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		workerList.DeleteCurrent( );
		delete worker;
	}
	return 0;
}

// Kill all running jobs
int
ForkWork::KillAll( bool force )
{
	ForkWorker	*worker;
	int		mypid = getpid();
	int		num_killed = 0;

	// Walk through the list
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		// If I'm the parent, kill it
		if ( mypid == worker->getParent() ) {
			num_killed++;
			if ( force ) {
				daemonCore->Send_Signal( worker->getPid(), SIGKILL );
			} else {
				daemonCore->Send_Signal( worker->getPid(), SIGTERM );
			}
		}
	}

	// If we killed some, log it...
	if ( num_killed ) {
		dprintf( D_JOB, "ForkWork %d: Killed %d jobs\n",
				 mypid, workerList.Number() );
	}
	return 0;
}

// Try to fork off another worker
ForkStatus
ForkWork::NewJob( void )
{
	ForkStatus status = FORK_BUSY;

	// Any open slots?
	if ( workerList.Number() >= maxWorkers ) {
		if ( maxWorkers ) {
			dprintf( D_JOB, "ForkWork: busy\n" );
		}
	}
	else
	{
	  // Fork off the child
	  ForkWorker	*worker = new ForkWorker( );
	  status = worker->Fork( );

	  // Ok, let's see what happenned..
	  if ( FORK_PARENT == status ) {
		  workerList.Append( worker );
	  } else if ( FORK_FAILED == status ) {
		  delete worker;
	  } else {
		  delete worker;
		  status = FORK_CHILD;
	  }
	}

	dprintf( D_ALWAYS, "Number of Active Workers %d\n", workerList.Number());

	return status;
}

// Child worker is done
void
ForkWork::WorkerDone( int exit_status )
{
	dprintf( D_JOB,
			 "ForkWork: Child %d done, status %d\n",
			 getpid(), exit_status );
	exit( exit_status );
}

// Child reaper
int
ForkWork::Reaper( int exitPid, int /*exitStatus*/ )
{
	ForkWorker	*worker;

	// Let's find out if it's one of our children...
	workerList.Rewind( );
	while ( workerList.Next( worker ) ) {
		if ( worker->getPid() == exitPid ) {
			workerList.DeleteCurrent( );
			delete worker;
		return 0;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#include "matrix_pseudoinverse_test.hpp"
#include <vmmlib/matrix_pseudoinverse.hpp>

#include <sstream>
#include <stdint.h>

namespace vmml
{

	bool
	matrix_pseudoinverse_test::run()
	{
		bool ok = false;

		compute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;
		matrix< 6, 4, float > input;
		double data[] = { 0.8147, 0.9058, 0.1270, 0.9134,
			0.6324, 0.0975, 0.2785, 0.5469,
			0.9575, 0.9649, 0.1576, 0.9706,
			0.9572, 0.4854, 0.8003, 0.1419,
			0.4218, 0.9157, 0.7922, 0.9595,
			0.6557, 0.0357, 0.8491, 0.9340};
		input.set( data, data + 24);
		matrix< 6, 4, float > pseudoinverse_transposed_control;
		double data2[] = { 0.1880, 0.1967, -0.4289, 0.1703,
			0.5039, -0.5719, -0.2487, 0.2746,
			0.3297, 0.1597, -0.4866, 0.1270,
			0.6085, 0.2728, 0.5149, -0.9327,
			-0.9104, 0.6751, 0.6790, 0.1391,
			0.0213, -0.7584, 0.2949, 0.6102 };
		pseudoinverse_transposed_control.set( data2, data2 + 24);

		matrix< 6, 4, float > pseudoinverse_transposed;
		compute_pinv( input, pseudoinverse_transposed );

		if ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))
		{
			log( "matrix compute pseudo inverse ", true  );
		} else
		{
			std::stringstream error;
			error
			<< "matrix compute pseudo inverse: " << std::endl
			<< "inverse matrix (transposed) should be: " << std::endl << pseudoinverse_transposed_control << std::endl
			<< "inverse matrix (transposed) is: " << std::endl << pseudoinverse_transposed << std::endl;

			log_error( error.str() );
		}

		ok = true;
		return ok;
	}

} // namespace vmml<commit_msg>- added more tests for matrix_pseudoinverse <commit_after>#include "matrix_pseudoinverse_test.hpp"
#include <vmmlib/matrix_pseudoinverse.hpp>

#include <sstream>
#include <stdint.h>

namespace vmml
{

	bool
	matrix_pseudoinverse_test::run()
	{
		bool ok = false;

		compute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;
		matrix< 6, 4, float > input;
		double data[] = { 0.8147, 0.9058, 0.1270, 0.9134,
			0.6324, 0.0975, 0.2785, 0.5469,
			0.9575, 0.9649, 0.1576, 0.9706,
			0.9572, 0.4854, 0.8003, 0.1419,
			0.4218, 0.9157, 0.7922, 0.9595,
			0.6557, 0.0357, 0.8491, 0.9340};
		input.set( data, data + 24);
		matrix< 6, 4, float > pseudoinverse_transposed_control;
		double data2[] = { 0.1880, 0.1967, -0.4289, 0.1703,
			0.5039, -0.5719, -0.2487, 0.2746,
			0.3297, 0.1597, -0.4866, 0.1270,
			0.6085, 0.2728, 0.5149, -0.9327,
			-0.9104, 0.6751, 0.6790, 0.1391,
			0.0213, -0.7584, 0.2949, 0.6102 };
		pseudoinverse_transposed_control.set( data2, data2 + 24);

		matrix< 6, 4, float > pseudoinverse_transposed;
                compute_pinv( input, pseudoinverse_transposed );

                matrix< 4, 6, float > pseudoinverse = transpose( pseudoinverse_transposed );
                matrix< 6, 6, float > control;
                control.multiply( input, pseudoinverse);

		if ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))
		{
			log( "matrix compute pseudo inverse ", true  );
		} else
		{
			std::stringstream error;
			error
			<< "matrix compute pseudo inverse: " << std::endl
			<< "inverse matrix (transposed) should be: " << std::endl << pseudoinverse_transposed_control << std::endl
			<< "inverse matrix (transposed) is: " << std::endl << pseudoinverse_transposed << std::endl
			<< "identiy matrix (control) is: " << std::endl << control << std::endl;

			log_error( error.str() );
		}

		ok = true;
		return ok;
	}

} // namespace vmml<|endoftext|>


<commit_before>#include <chrono>
#include "depthai/depthai.hpp"

/////////////////////////
// TEST
// ImageManipNode test
////////////////////////
int main(){

    using namespace std;
    using namespace std::chrono;
    using namespace std::chrono_literals;

    // Create pipeline
    dai::Pipeline p;

    auto xin = p.create<dai::node::XLinkIn>();
    auto imageManip = p.create<dai::node::ImageManip>();
    auto xout = p.create<dai::node::XLinkOut>();

    // resize
    const int originalWidth = 640, originalHeight = 360;
    const int width = 337, height = 225;

    // Properties
    xin->setStreamName("in");
    xout->setStreamName("out");
    imageManip->setResize(width, height);

    // Link plugins CAM -> XLINK
    xin->out.link(imageManip->inputImage);
    imageManip->out.link(xout->input);

    // Wait 5 seconds for device
    auto wait = steady_clock::now();
    bool found;
    dai::DeviceInfo deviceInfo;

    do{
        std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();

        if(found) {
            dai::Device d(p, deviceInfo);
            d.startPipeline();

            auto in = d.getInputQueue("in");
            auto out = d.getOutputQueue("out");

            // Send 10 messages
            for(int i = 0; i < 10; i++){
                // Create 'rgb interleaved' frame
                dai::ImgFrame inFrame;
                inFrame.getData().resize(originalWidth * originalHeight * 3);
                inFrame.setWidth(originalWidth);
                inFrame.setHeight(originalHeight);
                inFrame.setType(dai::RawImgFrame::Type::RGB888i);

                // Send the frame
                in->send(inFrame);

                // Retrieve the resized frame
                auto outFrame = out->get<dai::ImgFrame>();

                // Check that out frame is resized
                if(outFrame->getWidth() != width || outFrame->getHeight() != height){
                    return -1;
                }
            }

            // Exit with success error code
            return 0;
        }

        this_thread::sleep_for(1s);
    } while(!found && steady_clock::now() - wait < 5s );

    // Otherwise exit with error
    return -1;
}<commit_msg>Fixed ImageManip test<commit_after>#include <chrono>
#include "depthai/depthai.hpp"

/////////////////////////
// TEST
// ImageManipNode test
////////////////////////
int main(){

    using namespace std;
    using namespace std::chrono;
    using namespace std::chrono_literals;

    // Create pipeline
    dai::Pipeline p;

    auto xin = p.create<dai::node::XLinkIn>();
    auto imageManip = p.create<dai::node::ImageManip>();
    auto xout = p.create<dai::node::XLinkOut>();

    // resize
    const int originalWidth = 640, originalHeight = 360;
    const int width = 337, height = 225;

    // Properties
    xin->setStreamName("in");
    xout->setStreamName("out");
    imageManip->setResize(width, height);

    // Link plugins CAM -> XLINK
    xin->out.link(imageManip->inputImage);
    imageManip->out.link(xout->input);

    // Wait 5 seconds for device
    auto wait = steady_clock::now();
    bool found;
    dai::DeviceInfo deviceInfo;

    do{
        std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();

        if(found) {
            dai::Device d(p, deviceInfo);
            d.startPipeline();

            auto in = d.getInputQueue("in");
            auto out = d.getOutputQueue("out");

            // Send 10 messages
            for(int i = 0; i < 10; i++){
                // Create 'rgb interleaved' frame
                dai::ImgFrame inFrame;
                inFrame.getData().resize(originalWidth * originalHeight * 3);
                inFrame.setWidth(originalWidth);
                inFrame.setHeight(originalHeight);
                inFrame.setType(dai::RawImgFrame::Type::RGB888p);

                // Send the frame
                in->send(inFrame);

                // Retrieve the resized frame
                auto outFrame = out->get<dai::ImgFrame>();

                // Check that out frame is resized
                if(outFrame->getWidth() != width || outFrame->getHeight() != height){
                    return -1;
                }
            }

            // Exit with success error code
            return 0;
        }

        this_thread::sleep_for(1s);
    } while(!found && steady_clock::now() - wait < 5s );

    // Otherwise exit with error
    return -1;
}<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/simple_optimizer.h"

#include "common/logger.h"

namespace peloton {
namespace optimizer {

SimpleOptimizer::SimpleOptimizer() {
}
;

SimpleOptimizer::~SimpleOptimizer() {
}
;

std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
    const std::unique_ptr<parser::AbstractParse>& parse_tree) {

  if (parse_tree.get() == nullptr)
    return NULL;
  std::shared_ptr<planner::AbstractPlan> plan_tree;

  std::unique_ptr<planner::AbstractPlan> child_plan;

  // TODO: Transform the parse tree

  // One to one Mapping
  auto parse_item_node_type = parse_tree->GetParseNodeType();

  switch(parse_item_node_type){
    case PARSE_NODE_TYPE_SCAN:
      child_plan = new planner::SeqScanPlan();
      break;
  }

//  if (child_plan != nullptr) {
//      if (plan_tree != nullptr)
//        plan_tree->AddChild(child_plan);
//      else
//        plan_tree = child_plan;
//    }
  return plan_tree;
}

}  // namespace optimizer
}  // namespace peloton
<commit_msg>Added parser header to SimpleOptimizer<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"

#include "common/logger.h"

namespace peloton {
namespace optimizer {

SimpleOptimizer::SimpleOptimizer() {
}
;

SimpleOptimizer::~SimpleOptimizer() {
}
;

std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
    const std::unique_ptr<parser::AbstractParse>& parse_tree) {

  if (parse_tree.get() == nullptr)
    return NULL;
  std::shared_ptr<planner::AbstractPlan> plan_tree;

  std::unique_ptr<planner::AbstractPlan> child_plan;

  // TODO: Transform the parse tree

  // One to one Mapping
  auto parse_item_node_type = parse_tree->GetParseNodeType();

  switch(parse_item_node_type){
    case PARSE_NODE_TYPE_SCAN:
      child_plan = new planner::SeqScanPlan();
      break;
  }

//  if (child_plan != nullptr) {
//      if (plan_tree != nullptr)
//        plan_tree->AddChild(child_plan);
//      else
//        plan_tree = child_plan;
//    }
  return plan_tree;
}

}  // namespace optimizer
}  // namespace peloton
<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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 "paddle/fluid/inference/tensorrt/engine.h"

#include <NvInfer.h>
#include <cuda.h>
#include <glog/logging.h>
#include <string>
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/helper.h"
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace inference {
namespace tensorrt {

int TensorRTEngine::runtime_batch_ = 1;

void TensorRTEngine::InitNetwork() {
  freshDeviceId();
  infer_builder_.reset(createInferBuilder(&logger_));

  if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
    infer_networkv2_.reset(infer_builder_->createNetworkV2(
        1U << static_cast<int>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
    infer_builder_config_.reset(infer_builder_->createBuilderConfig());
    infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;
    optim_profile_ = infer_builder_->createOptimizationProfile();
#endif
  } else {
    infer_network_.reset(infer_builder_->createNetwork());
  }
}

void TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,
                             cudaStream_t stream) {
  freshDeviceId();
  auto infer_context = context();
  if (!with_dynamic_shape()) {
    infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);
  } else {
#if IS_TRT_VERSION_GE(6000)
    infer_context->enqueueV2(buffers->data(), stream, nullptr);
#endif
  }
  SetRuntimeBatch(batch_size);
}

void TensorRTEngine::FreezeNetwork() {
  freshDeviceId();
  VLOG(3) << "TRT to freeze network";
  PADDLE_ENFORCE(infer_builder_ != nullptr,
                 "Call InitNetwork first to initialize network.");
  PADDLE_ENFORCE_EQ(network() != nullptr, true,
                    platform::errors::InvalidArgument(
                        "Call InitNetwork first to initialize network."));
  // build engine.
  infer_builder_->setMaxBatchSize(max_batch_);
  infer_builder_->setMaxWorkspaceSize(max_workspace_);
  bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);
#if IS_TRT_VERSION_GE(5000)
  if (enable_fp16) {
    bool support_fp16 = infer_builder_->platformHasFastFp16();
    infer_builder_->setFp16Mode(support_fp16);
    if (!support_fp16) {
      LOG(INFO) << "You specify FP16 mode, but the hardware do not support "
                   "FP16 speed up, use FP32 instead.";
    } else {
      LOG(INFO) << "Run Paddle-TRT FP16 mode";
    }
  }
#else
  if (enable_fp16)
    LOG(INFO) << "Using FP16 in Paddle-TRT must ensure that the version of TRT "
                 "is at least 5."
                 "So, use FP32 to run.";
#endif
  bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);

  if (enable_int8) {
    infer_builder_->setInt8Mode(true);
    if (calibrator_) {
      infer_builder_->setInt8Calibrator(calibrator_);
    } else {
      infer_builder_->setInt8Calibrator(nullptr);

#if IS_TRT_VERSION_GE(5000)
      infer_builder_->setStrictTypeConstraints(true);
      for (auto &quant_range : quant_dynamic_range_) {
        auto tensor = quant_range.first;
        float range = quant_range.second;
        tensor->setDynamicRange(-range, range);
      }

      std::unordered_set<nvinfer1::ITensor *> all_t;
      for (int i = 0; i < network()->getNbLayers(); i++) {
        auto layer = network()->getLayer(i);
        for (int j = 0; j < layer->getNbOutputs(); j++) {
          all_t.insert(layer->getOutput(j));
        }
      }
      for (int i = 0; i < network()->getNbInputs(); i++) {
        all_t.insert(network()->getInput(i));
      }

      for (auto &t : all_t) {
        if (!quant_dynamic_range_.count(t)) {
          VLOG(3) << "We are in trt int8 mode(not calibration), scale not set"
                  << " for tensor " << t->getName()
                  << ", this might be ok when trt does not need this range";
        }
      }
      auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {
        for (int j = 0; j < layer->getNbInputs(); j++) {
          auto *temp_in = layer->getInput(j);
          if (!temp_in->dynamicRangeIsSet()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its input("
                    << temp_in->getName() << ") doesn't have dynamic range.";
            return false;
          }
        }
        for (int j = 0; j < layer->getNbOutputs(); j++) {
          auto *temp_out = layer->getOutput(j);
          if (temp_out->isNetworkOutput()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its output("
                    << temp_out->getName() << ") is the output of the network.";
            return false;
          }
          if (!temp_out->dynamicRangeIsSet()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its output("
                    << temp_out->getName() << ") doesn't have dynamic range.";
            return false;
          }
        }
        return true;
      };
      // If a layer's output is the network's output, or not all of its inputs
      // and outputs have scales,
      // this layer's precision and output type are set to float32.
      // This step has no effect if this layer is fused during TRT optimization.
      for (int i = 0; i < network()->getNbLayers(); i++) {
        auto layer = network()->getLayer(i);
        if (!is_layer_int8(layer)) {
          layer->setPrecision(nvinfer1::DataType::kFLOAT);
        }
      }
#endif
    }
  }

  if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
    LOG(INFO) << "Run Paddle-TRT Dynamic Shape mode.";
    for (auto &input : min_input_shape_) {
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,
          Vec2TRT_Dims(input.second, input.first, true));
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,
          Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,
          Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));
    }
    infer_builder_config_->addOptimizationProfile(optim_profile_);
    if (WithFp16()) {
      infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
      if (disable_trt_plugin_fp16()) {
        LOG(INFO) << "NOTE: In order to achieve higher accuracy, you have "
                     "disabled the fp16 mode of TRT Plugin,\n"
                  << "you can reopen it with "
                     "'config.SetDynamicShapeInfo(min_shape, max_shape, "
                     "opt_shape, false /*disable_trt_plugin_fp16*/)'";
      }
    }
    infer_engine_.reset(infer_builder_->buildEngineWithConfig(
        *network(), *infer_builder_config_));
#endif
  } else {
    infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));
  }
  PADDLE_ENFORCE(infer_engine_ != nullptr, "build cuda engine failed!");
}

nvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,
                                                nvinfer1::DataType dtype,
                                                const nvinfer1::Dims &dims) {
  PADDLE_ENFORCE_EQ(network() != nullptr, true,
                    platform::errors::InvalidArgument(
                        "The TRT network should be initialized first."));
  auto *input = network()->addInput(name.c_str(), dtype, dims);
  PADDLE_ENFORCE(input, "infer network add input %s failed", name);
  PADDLE_ENFORCE(input->isNetworkInput());
  TensorRTEngine::SetITensor(name, input);
  return input;
}

void TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,
                                   const std::string &name) {
  auto *output = layer->getOutput(offset);
  SetITensor(name, output);
  PADDLE_ENFORCE(output != nullptr);
  output->setName(name.c_str());
  PADDLE_ENFORCE(!output->isNetworkInput());
  network()->markOutput(*output);
  PADDLE_ENFORCE(output->isNetworkOutput());
}

void TensorRTEngine::DeclareOutput(const std::string &name) {
  auto *output = TensorRTEngine::GetITensor(name);
  PADDLE_ENFORCE(output != nullptr);
  output->setName(name.c_str());
  PADDLE_ENFORCE(!output->isNetworkInput());
  network()->markOutput(*output);
}

void TensorRTEngine::SetITensor(const std::string &name,
                                nvinfer1::ITensor *tensor) {
  PADDLE_ENFORCE(tensor != nullptr);
  PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), "duplicate ITensor name %s",
                    name);
  itensor_map_[name] = tensor;
}

nvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {
  PADDLE_ENFORCE(itensor_map_.count(name), "no ITensor %s", name);
  return itensor_map_[name];
}

void TensorRTEngine::SetRuntimeBatch(size_t batch_size) {
  runtime_batch_ = batch_size;
}

float *TensorRTEngine::GetWeightCPUData(const std::string &name,
                                        framework::Tensor *weight_tensor,
                                        bool enable_int8,
                                        const std::vector<float> &scale) {
  static int name_suffix_counter = 0;
  std::string name_suffix = std::to_string(name_suffix_counter);
  std::string splitter = "__";
  std::string name_with_suffix = name + splitter + name_suffix;
  platform::CPUPlace cpu_place;
  PADDLE_ENFORCE_EQ(
      weight_map.count(name_with_suffix), 0,
      "During TRT Op converter: We set weight %s with the same name "
      "twice into the weight_map",
      name_with_suffix);
  weight_map[name_with_suffix].reset(new framework::Tensor());
  weight_map[name_with_suffix]->Resize(weight_tensor->dims());
  TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());
  float *weight_data =
      weight_map[name_with_suffix]->mutable_data<float>(cpu_place);
  name_suffix_counter += 1;
  return weight_data;
}

int TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }

nvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(
    nvinfer1::ITensor *const *inputs, int num_inputs,
    plugin::PluginTensorRT *plugin) {
  owned_plugin_.emplace_back(plugin);
  return network()->addPluginExt(inputs, num_inputs, *plugin);
}

void TensorRTEngine::freshDeviceId() {
  int count;
  cudaGetDeviceCount(&count);
  PADDLE_ENFORCE_LT(device_id_, count);
  cudaSetDevice(device_id_);
}

}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
<commit_msg>add macro check for using TRT api dynamicRangeIsSet() (#25694)<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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 "paddle/fluid/inference/tensorrt/engine.h"

#include <NvInfer.h>
#include <cuda.h>
#include <glog/logging.h>
#include <string>
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/helper.h"
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace inference {
namespace tensorrt {

int TensorRTEngine::runtime_batch_ = 1;

void TensorRTEngine::InitNetwork() {
  freshDeviceId();
  infer_builder_.reset(createInferBuilder(&logger_));

  if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
    infer_networkv2_.reset(infer_builder_->createNetworkV2(
        1U << static_cast<int>(
            nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
    infer_builder_config_.reset(infer_builder_->createBuilderConfig());
    infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;
    optim_profile_ = infer_builder_->createOptimizationProfile();
#endif
  } else {
    infer_network_.reset(infer_builder_->createNetwork());
  }
}

void TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,
                             cudaStream_t stream) {
  freshDeviceId();
  auto infer_context = context();
  if (!with_dynamic_shape()) {
    infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);
  } else {
#if IS_TRT_VERSION_GE(6000)
    infer_context->enqueueV2(buffers->data(), stream, nullptr);
#endif
  }
  SetRuntimeBatch(batch_size);
}

void TensorRTEngine::FreezeNetwork() {
  freshDeviceId();
  VLOG(3) << "TRT to freeze network";
  PADDLE_ENFORCE(infer_builder_ != nullptr,
                 "Call InitNetwork first to initialize network.");
  PADDLE_ENFORCE_EQ(network() != nullptr, true,
                    platform::errors::InvalidArgument(
                        "Call InitNetwork first to initialize network."));
  // build engine.
  infer_builder_->setMaxBatchSize(max_batch_);
  infer_builder_->setMaxWorkspaceSize(max_workspace_);
  bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);
#if IS_TRT_VERSION_GE(5000)
  if (enable_fp16) {
    bool support_fp16 = infer_builder_->platformHasFastFp16();
    infer_builder_->setFp16Mode(support_fp16);
    if (!support_fp16) {
      LOG(INFO) << "You specify FP16 mode, but the hardware do not support "
                   "FP16 speed up, use FP32 instead.";
    } else {
      LOG(INFO) << "Run Paddle-TRT FP16 mode";
    }
  }
#else
  if (enable_fp16)
    LOG(INFO) << "Using FP16 in Paddle-TRT must ensure that the version of TRT "
                 "is at least 5."
                 "So, use FP32 to run.";
#endif
  bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);

  if (enable_int8) {
    infer_builder_->setInt8Mode(true);
    if (calibrator_) {
      infer_builder_->setInt8Calibrator(calibrator_);
    } else {
      infer_builder_->setInt8Calibrator(nullptr);

#if IS_TRT_VERSION_GE(5000)
      infer_builder_->setStrictTypeConstraints(true);
      for (auto &quant_range : quant_dynamic_range_) {
        auto tensor = quant_range.first;
        float range = quant_range.second;
        tensor->setDynamicRange(-range, range);
      }

      std::unordered_set<nvinfer1::ITensor *> all_t;
      for (int i = 0; i < network()->getNbLayers(); i++) {
        auto layer = network()->getLayer(i);
        for (int j = 0; j < layer->getNbOutputs(); j++) {
          all_t.insert(layer->getOutput(j));
        }
      }
      for (int i = 0; i < network()->getNbInputs(); i++) {
        all_t.insert(network()->getInput(i));
      }

      for (auto &t : all_t) {
        if (!quant_dynamic_range_.count(t)) {
          VLOG(3) << "We are in trt int8 mode(not calibration), scale not set"
                  << " for tensor " << t->getName()
                  << ", this might be ok when trt does not need this range";
        }
      }
#if IS_TRT_VERSION_GE(5122)
      auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {
        for (int j = 0; j < layer->getNbInputs(); j++) {
          auto *temp_in = layer->getInput(j);
          if (!temp_in->dynamicRangeIsSet()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its input("
                    << temp_in->getName() << ") doesn't have dynamic range.";
            return false;
          }
        }
        for (int j = 0; j < layer->getNbOutputs(); j++) {
          auto *temp_out = layer->getOutput(j);
          if (temp_out->isNetworkOutput()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its output("
                    << temp_out->getName() << ") is the output of the network.";
            return false;
          }
          if (!temp_out->dynamicRangeIsSet()) {
            VLOG(1) << "Layer(Name: " << layer->getName()
                    << ") is set to float32 because its output("
                    << temp_out->getName() << ") doesn't have dynamic range.";
            return false;
          }
        }
        return true;
      };
      // If a layer's output is the network's output, or not all of its inputs
      // and outputs have scales,
      // this layer's precision and output type are set to float32.
      // This step has no effect if this layer is fused during TRT optimization.
      for (int i = 0; i < network()->getNbLayers(); i++) {
        auto layer = network()->getLayer(i);
        if (!is_layer_int8(layer)) {
          layer->setPrecision(nvinfer1::DataType::kFLOAT);
        }
      }
#else
      LOG(WARNING) << "If your TensorRT version is lower than 5.1.2.2, you "
                      "must provide quantization scales for all tensors using "
                      "TRT to run.";
#endif
#endif
    }
  }

  if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
    LOG(INFO) << "Run Paddle-TRT Dynamic Shape mode.";
    for (auto &input : min_input_shape_) {
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,
          Vec2TRT_Dims(input.second, input.first, true));
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,
          Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));
      optim_profile_->setDimensions(
          input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,
          Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));
    }
    infer_builder_config_->addOptimizationProfile(optim_profile_);
    if (WithFp16()) {
      infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
      if (disable_trt_plugin_fp16()) {
        LOG(INFO) << "NOTE: In order to achieve higher accuracy, you have "
                     "disabled the fp16 mode of TRT Plugin,\n"
                  << "you can reopen it with "
                     "'config.SetDynamicShapeInfo(min_shape, max_shape, "
                     "opt_shape, false /*disable_trt_plugin_fp16*/)'";
      }
    }
    infer_engine_.reset(infer_builder_->buildEngineWithConfig(
        *network(), *infer_builder_config_));
#endif
  } else {
    infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));
  }
  PADDLE_ENFORCE(infer_engine_ != nullptr, "build cuda engine failed!");
}

nvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,
                                                nvinfer1::DataType dtype,
                                                const nvinfer1::Dims &dims) {
  PADDLE_ENFORCE_EQ(network() != nullptr, true,
                    platform::errors::InvalidArgument(
                        "The TRT network should be initialized first."));
  auto *input = network()->addInput(name.c_str(), dtype, dims);
  PADDLE_ENFORCE(input, "infer network add input %s failed", name);
  PADDLE_ENFORCE(input->isNetworkInput());
  TensorRTEngine::SetITensor(name, input);
  return input;
}

void TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,
                                   const std::string &name) {
  auto *output = layer->getOutput(offset);
  SetITensor(name, output);
  PADDLE_ENFORCE(output != nullptr);
  output->setName(name.c_str());
  PADDLE_ENFORCE(!output->isNetworkInput());
  network()->markOutput(*output);
  PADDLE_ENFORCE(output->isNetworkOutput());
}

void TensorRTEngine::DeclareOutput(const std::string &name) {
  auto *output = TensorRTEngine::GetITensor(name);
  PADDLE_ENFORCE(output != nullptr);
  output->setName(name.c_str());
  PADDLE_ENFORCE(!output->isNetworkInput());
  network()->markOutput(*output);
}

void TensorRTEngine::SetITensor(const std::string &name,
                                nvinfer1::ITensor *tensor) {
  PADDLE_ENFORCE(tensor != nullptr);
  PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), "duplicate ITensor name %s",
                    name);
  itensor_map_[name] = tensor;
}

nvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {
  PADDLE_ENFORCE(itensor_map_.count(name), "no ITensor %s", name);
  return itensor_map_[name];
}

void TensorRTEngine::SetRuntimeBatch(size_t batch_size) {
  runtime_batch_ = batch_size;
}

float *TensorRTEngine::GetWeightCPUData(const std::string &name,
                                        framework::Tensor *weight_tensor,
                                        bool enable_int8,
                                        const std::vector<float> &scale) {
  static int name_suffix_counter = 0;
  std::string name_suffix = std::to_string(name_suffix_counter);
  std::string splitter = "__";
  std::string name_with_suffix = name + splitter + name_suffix;
  platform::CPUPlace cpu_place;
  PADDLE_ENFORCE_EQ(
      weight_map.count(name_with_suffix), 0,
      "During TRT Op converter: We set weight %s with the same name "
      "twice into the weight_map",
      name_with_suffix);
  weight_map[name_with_suffix].reset(new framework::Tensor());
  weight_map[name_with_suffix]->Resize(weight_tensor->dims());
  TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());
  float *weight_data =
      weight_map[name_with_suffix]->mutable_data<float>(cpu_place);
  name_suffix_counter += 1;
  return weight_data;
}

int TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }

nvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(
    nvinfer1::ITensor *const *inputs, int num_inputs,
    plugin::PluginTensorRT *plugin) {
  owned_plugin_.emplace_back(plugin);
  return network()->addPluginExt(inputs, num_inputs, *plugin);
}

void TensorRTEngine::freshDeviceId() {
  int count;
  cudaGetDeviceCount(&count);
  PADDLE_ENFORCE_LT(device_id_, count);
  cudaSetDevice(device_id_);
}

}  // namespace tensorrt
}  // namespace inference
}  // namespace paddle
<|endoftext|>


<commit_before>#include "../../../SDP.hxx"
#include "../../../../Timers.hxx"

El::BigFloat dot(const Block_Vector &a, const Block_Vector &b);

void compute_objectives(const SDP &sdp, const Block_Vector &x,
                        const Block_Vector &y, El::BigFloat &primal_objective,
                        El::BigFloat &dual_objective,
                        El::BigFloat &duality_gap, Timers &timers)
{
  auto &objectives_timer(timers.add_and_start("run.objectives"));
  primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);
  // dual_objective_b is duplicated amongst the processors.  y is
  // duplicated amongst the blocks, but it is possible for some
  // processors to have no blocks.  In principle, we only need to
  // compute the dot product on the first block, but then we would
  // have to make sure that we compute that product over all
  // processors that own that block.
  if(!y.blocks.empty())
    {
      dual_objective = sdp.objective_const
                       + El::Dotu(sdp.dual_objective_b, y.blocks.front());
    }
  El::mpi::Broadcast(&dual_objective, 1, 0, El::mpi::COMM_WORLD);

  duality_gap
    = Abs(primal_objective - dual_objective)
      / Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));

  objectives_timer.stop();
}
<commit_msg>Use a simpler version of El::mpi::Broadcast()<commit_after>#include "../../../SDP.hxx"
#include "../../../../Timers.hxx"

El::BigFloat dot(const Block_Vector &a, const Block_Vector &b);

void compute_objectives(const SDP &sdp, const Block_Vector &x,
                        const Block_Vector &y, El::BigFloat &primal_objective,
                        El::BigFloat &dual_objective,
                        El::BigFloat &duality_gap, Timers &timers)
{
  auto &objectives_timer(timers.add_and_start("run.objectives"));
  primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);
  // dual_objective_b is duplicated amongst the processors.  y is
  // duplicated amongst the blocks, but it is possible for some
  // processors to have no blocks.  In principle, we only need to
  // compute the dot product on the first block, but then we would
  // have to make sure that we compute that product over all
  // processors that own that block.
  if(!y.blocks.empty())
    {
      dual_objective = sdp.objective_const
                       + El::Dotu(sdp.dual_objective_b, y.blocks.front());
    }
  El::mpi::Broadcast(dual_objective, 0, El::mpi::COMM_WORLD);

  duality_gap
    = Abs(primal_objective - dual_objective)
      / Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));

  objectives_timer.stop();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dynamicregister.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "dynamicregister.hxx"
#include <osl/process.h>
// #include <osl/mutex.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include "filehelper.hxx"

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

DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions)
        :m_pModule(new ::osl::Module()),
         m_suDLLName(_sDLLName),
         m_aOptions(_aOptions)
{
    // create and load the module (shared library)
    rtl::OUString suFile = FileHelper::convertPath( _sDLLName );
    rtl::OString sDLLName = rtl::OUStringToOString(suFile, RTL_TEXTENCODING_ASCII_US);
    if (_aOptions.hasOpt("-verbose"))
    {
        fprintf(stderr, "Try to load '%s'.\n", sDLLName.getStr());
    }

    if (! m_pModule->load(suFile, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))
    {
        sDLLName = rtl::OUStringToOString(_sDLLName, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr());
    }
}

DynamicLibraryHelper::~DynamicLibraryHelper()
{
    delete m_pModule;
}

<commit_msg>INTEGRATION: CWS ause093 (1.9.6); FILE MERGED 2008/05/07 11:10:44 lla 1.9.6.3: #i88845# cleanup, for load library locally or absolutely 2008/05/06 12:08:20 hjs 1.9.6.2: #i88845# set of changes from lla to get specified library loaded 2008/05/06 06:42:35 lla 1.9.6.1: #i88845# changes for macosx usage<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dynamicregister.cxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "dynamicregister.hxx"
#include <osl/process.h>
// #include <osl/mutex.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include "filehelper.hxx"

#include <unistd.h>

#if defined(WIN32)
#include <direct.h>    /* w.g. _chdir() */
#endif

namespace fixes
{
    void changedir(const char* _sPath)
    {
#if defined(WIN32)
        // chdir(_sPath) is marked depricated since Visual C++ 2005
        // use _chdir instead
        ::_chdir(_sPath);
#else
        ::chdir(_sPath);
#endif
    }
}

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

DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _suDLLName, GetOpt & _aOptions)
        :m_pModule(new ::osl::Module()),
         m_suDLLName(_suDLLName),
         m_aOptions(_aOptions)
{
    // create and load the module (shared library)
    m_suAbsolutePathFile = FileHelper::convertPath( _suDLLName );

    // due to some problems on mac OS
    // we split the absolute pathname to path and filename
    // change to the path and load the filename direct
    // then change back to the old path.
    rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("/"));
    sal_Int32 nPos = m_suAbsolutePathFile.lastIndexOf(suPathSeparator);
    if (nPos != -1)
    {
        m_suAbsolutePath = m_suAbsolutePathFile.copy(0, nPos);
        m_suFilename = m_suAbsolutePathFile.copy(nPos + 1);
    }
    else
    {
        // Should never happen.
        rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePathFile, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "There is a problem with path '%s'.\n", sPath.getStr());
        exit(1);
    }

    if (getOptions().hasOpt("-absolutepath"))
    {
        fprintf(stderr, "Hint: Use absolute path to load test library.\n");
        loadLibraryFromAbsolutePath();
    }
    else if (getOptions().hasOpt("-localpath"))
    {
        fprintf(stderr, "Hint: make a chdir() to the test library, then try to load the test library without given path.\n");
        loadLibraryFromLocalPath();
    }
    else
    {

// PLEASE DON'T CHANGE THIS STUPID STRUCTURE, JUST ADD YOUR ENVIRONMENT
#if defined(LINUX)
        loadLibraryFromAbsolutePath();
        // will fail if load local

#elif defined(SOLARIS)
        loadLibraryFromAbsolutePath();
        // will also be right if load local

#elif defined(WIN32)
        loadLibraryFromAbsolutePath();
        // will fail if load local

#elif defined(MACOSX)
        loadLibraryFromLocalPath();
        // will fail if local absolute
#else
        // default is load absolute
        loadLibraryFromAbsolutePath();
#endif
}
}

void DynamicLibraryHelper::showFilenameIfVerbose()
{
    if (getOptions().hasOpt("-verbose"))
    {
        rtl::OString sFilename = rtl::OUStringToOString(m_suFilename, RTL_TEXTENCODING_ASCII_US);
        rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePath, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "Try to load '%s' from '%s'.\n", sFilename.getStr(), sPath.getStr());

        // check filename
    }
}

void DynamicLibraryHelper::realLoadLibrary(rtl::OUString const& _suLibToLoad)
{
    if (! m_pModule->load(_suLibToLoad, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))
    {
        rtl::OString sDLLName = rtl::OUStringToOString(m_suDLLName, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr());
    }
}

void DynamicLibraryHelper::loadLibraryFromAbsolutePath()
{
    showFilenameIfVerbose();
    realLoadLibrary(m_suAbsolutePathFile);
}

void DynamicLibraryHelper::loadLibraryFromLocalPath()
{
    sal_Int32 nPos;
    rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("/"));
#if defined(WIN32)
    suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("\\"));
#endif
    rtl::OUString suSystemPathFile;
    osl::FileBase::getSystemPathFromFileURL(m_suAbsolutePathFile, suSystemPathFile);

    nPos = suSystemPathFile.lastIndexOf(suPathSeparator);
    rtl::OUString suCurrentDirPath;
    if (nPos != -1)
    {
        // the filename only, no '/' in the path
        rtl::OUString suNewPath = suSystemPathFile.copy(0, nPos );
        if (suNewPath.getLength() > 0)
        {
            rtl::OString sPath = rtl::OUStringToOString(suNewPath, RTL_TEXTENCODING_ASCII_US);
            osl_getProcessWorkingDir( &suCurrentDirPath.pData );

            fixes::changedir(sPath.getStr());

            // curNewDirPath should be suPath, small self test
            rtl::OUString curNewDirPath;
            osl_getProcessWorkingDir( &curNewDirPath.pData );
            if (! curNewDirPath.equals(m_suAbsolutePath))
            {
                fprintf(stderr, "There is a problem with path '%s'.\n", sPath.getStr());
            }
        }
    }

    showFilenameIfVerbose();
    realLoadLibrary(m_suFilename);

    // change back to old directory
    if (suCurrentDirPath.getLength() > 0)
    {
        rtl::OString sCurrentDirPath = rtl::OUStringToOString(suCurrentDirPath, RTL_TEXTENCODING_ASCII_US);
        fixes::changedir(sCurrentDirPath.getStr());
    }
}

DynamicLibraryHelper::~DynamicLibraryHelper()
{
    if (getOptions().hasOpt("-verbose"))
    {
        fprintf(stderr, "Dtor DynamicLibraryHelper.\n");
        fprintf(stderr, "Delete loaded module.");
    }
    delete m_pModule;
    if (getOptions().hasOpt("-verbose"))
    {
        fprintf(stderr, " [done].\n");
    }
}

<|endoftext|>