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

#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "src/wsiToDcm.h"
namespace {
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 1;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;

}  // namespace
int main(int argc, char *argv[]) {
  std::string inputFile;
  std::string jsonFile;
  std::string outputFolder;
  std::string compression;
  std::string seriesDescription;
  std::string seriesId;
  std::string studyId;
  int tileHeight;
  int tileWidth;
  int levels;
  int start;
  int stop;
  int batch;
  int threads;
  bool debug;
  bool dropFirstRowAndColumn;
  std::vector<double> downsamples;
  downsamples.resize(1);
  bool sparse;
  try {
    namespace programOptions = boost::program_options;
    programOptions::options_description desc("Options", 90, 20);
    desc.add_options()("help", "Print help messages")(
        "input", programOptions::value<std::string>(&inputFile)->required(),
        "input file")("outFolder",
                      programOptions::value<std::string>(&outputFolder)
                          ->required()
                          ->default_value("./"),
                      "folder to store dcm files")(
        "tileHeight",
        programOptions::value<int>(&tileHeight)->required()->default_value(500),
        "tile height px")(
        "tileWidth",
        programOptions::value<int>(&tileWidth)->required()->default_value(500),
        "tile width px")("levels",
                         programOptions::value<int>(&levels)->default_value(0),
                         "number of levels, levels == 0 means number of levels "
                         "will be readed from wsi file")(
        "downsamples",
        programOptions::value<std::vector<double> >(&downsamples)->multitoken(),
        "downsample for each level, downsample is size factor for each level")(
        "startOn", programOptions::value<int>(&start)->default_value(0),
        "level to start")("stopOn",
                          programOptions::value<int>(&stop)->default_value(-1),
                          "level to stop")(
        "sparse", programOptions::bool_switch(&sparse)->default_value(false),
        "use TILED_SPARSE frame organization, by default it's TILED_FULL")(
        "compression",
        programOptions::value<std::string>(&compression)->default_value("jpeg"),
        "compression, supported compressions: jpeg, jpeg2000, raw")(
        "seriesDescription",
        programOptions::value<std::string>(&seriesDescription)->required(),
        "series description in SeriesDescription tag")(
        "studyId",
        programOptions::value<std::string>(&studyId)->required()->default_value(
            ""),
        "StudyID")("seriesId",
                   programOptions::value<std::string>(&seriesId)
                       ->required()
                       ->default_value(""),
                   "SeriesID")("jsonFile",
                               programOptions::value<std::string>(&jsonFile),
                               "dicom json file with additional tags "
        "\nhttps://www.dicomstandard.org/dicomweb/dicom-json-format/")(
        "batch", programOptions::value<int>(&batch)->default_value(0),
        "maximum frames in one file")(
        "threads",
        programOptions::value<int>(&threads)->required()->default_value(-1),
        "number of threads")(
        "debug", programOptions::bool_switch(&debug)->default_value(false),
        "debug messages")(
        "dropFirstRowAndColumn",
        programOptions::bool_switch(
        &dropFirstRowAndColumn)->default_value(false),
        "drop first row and column of the source image in order to "
        "workaround bug\nhttps://github.com/openslide/openslide/issues/268");
    programOptions::positional_options_description positionalOptions;
    positionalOptions.add("input", 1);
    positionalOptions.add("outFolder", 1);
    programOptions::variables_map vm;
    try {
      programOptions::store(programOptions::command_line_parser(argc, argv)
                                .options(desc)
                                .positional(positionalOptions)
                                .run(),
                            vm);

      if (vm.count("help")) {
        std::cout << "Wsi2dcm" << std::endl << desc << std::endl;
        return SUCCESS;
      }
      programOptions::notify(vm);
    } catch (programOptions::error &e) {
      std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
      std::cerr << desc << std::endl;
      return ERROR_IN_COMMAND_LINE;
    }
  } catch (std::exception &exception) {
    std::cerr << "Unhandled Exception reached the top of main: "
              << exception.what() << ", application will now exit" << std::endl;
    return ERROR_UNHANDLED_EXCEPTION;
  }
  wsiToDicomConverter::WsiRequest request;
  request.inputFile = inputFile;
  request.outputFileMask = outputFolder;
  request.frameSizeX = tileWidth;
  request.frameSizeY = tileHeight;
  request.compression = dcmCompressionFromString(compression);
  request.quality = 80;
  request.startOnLevel = start;
  request.stopOnLevel = stop;
  request.imageName = seriesDescription;
  request.studyId = studyId;
  request.seriesId = seriesId;
  request.jsonFile = jsonFile;
  request.retileLevels = levels;
  request.downsamples = &downsamples[0];
  request.tiled = !sparse;
  request.batchLimit = batch;
  request.threads = threads;
  request.dropFirstRowAndColumn = dropFirstRowAndColumn;
  request.debug = debug;
  wsiToDicomConverter::WsiToDcm::wsi2dcm(request);

  return SUCCESS;
}
<commit_msg>Update main.cpp<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <vector>
#include "src/wsiToDcm.h"
namespace {
const size_t ERROR_IN_COMMAND_LINE = 1;
const size_t SUCCESS = 0;
const size_t ERROR_UNHANDLED_EXCEPTION = 2;

}  // namespace
int main(int argc, char *argv[]) {
  std::string inputFile;
  std::string jsonFile;
  std::string outputFolder;
  std::string compression;
  std::string seriesDescription;
  std::string seriesId;
  std::string studyId;
  int tileHeight;
  int tileWidth;
  int levels;
  int start;
  int stop;
  int batch;
  int threads;
  bool debug;
  bool dropFirstRowAndColumn;
  std::vector<double> downsamples;
  downsamples.resize(1);
  bool sparse;
  try {
    namespace programOptions = boost::program_options;
    programOptions::options_description desc("Options", 90, 20);
    desc.add_options()("help", "Print help messages")(
        "input", programOptions::value<std::string>(&inputFile)->required(),
        "input file")("outFolder",
                      programOptions::value<std::string>(&outputFolder)
                          ->required()
                          ->default_value("./"),
                      "folder to store dcm files")(
        "tileHeight",
        programOptions::value<int>(&tileHeight)->required()->default_value(500),
        "tile height px")(
        "tileWidth",
        programOptions::value<int>(&tileWidth)->required()->default_value(500),
        "tile width px")("levels",
                         programOptions::value<int>(&levels)->default_value(0),
                         "number of levels, levels == 0 means number of levels "
                         "will be readed from wsi file")(
        "downsamples",
        programOptions::value<std::vector<double> >(&downsamples)->multitoken(),
        "downsample for each level, downsample is size factor for each level")(
        "startOn", programOptions::value<int>(&start)->default_value(0),
        "level to start")("stopOn",
                          programOptions::value<int>(&stop)->default_value(-1),
                          "level to stop")(
        "sparse", programOptions::bool_switch(&sparse)->default_value(false),
        "use TILED_SPARSE frame organization, by default it's TILED_FULL")(
        "compression",
        programOptions::value<std::string>(&compression)->default_value("jpeg"),
        "compression, supported compressions: jpeg, jpeg2000, raw")(
        "seriesDescription",
        programOptions::value<std::string>(&seriesDescription)->required(),
        "series description in SeriesDescription tag")(
        "studyId",
        programOptions::value<std::string>(&studyId)->required()->default_value(
            ""),
        "StudyID")("seriesId",
                   programOptions::value<std::string>(&seriesId)
                       ->required()
                       ->default_value(""),
                   "SeriesID")("jsonFile",
                               programOptions::value<std::string>(&jsonFile),
                               "dicom json file with additional tags "
        "\nhttps://www.dicomstandard.org/dicomweb/dicom-json-format/")(
        "batch", programOptions::value<int>(&batch)->default_value(0),
        "maximum frames in one file")(
        "threads",
        programOptions::value<int>(&threads)->required()->default_value(-1),
        "number of threads")(
        "debug", programOptions::bool_switch(&debug)->default_value(false),
        "debug messages")(
        "dropFirstRowAndColumn",
        programOptions::bool_switch(
        &dropFirstRowAndColumn)->default_value(false),
        "drop first row and column of the source image in order to "
        "workaround bug\nhttps://github.com/openslide/openslide/issues/268");
    programOptions::positional_options_description positionalOptions;
    positionalOptions.add("input", 1);
    positionalOptions.add("outFolder", 1);
    programOptions::variables_map vm;
    try {
      programOptions::store(programOptions::command_line_parser(argc, argv)
                                .options(desc)
                                .positional(positionalOptions)
                                .run(),
                            vm);

      if (vm.count("help")) {
        std::cout << "Wsi2dcm" << std::endl << desc << std::endl;
        return SUCCESS;
      }
      programOptions::notify(vm);
    } catch (programOptions::error &e) {
      std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
      std::cerr << desc << std::endl;
      return ERROR_IN_COMMAND_LINE;
    }
  } catch (std::exception &exception) {
    std::cerr << "Unhandled Exception reached the top of main: "
              << exception.what() << ", application will now exit" << std::endl;
    return ERROR_UNHANDLED_EXCEPTION;
  }
  wsiToDicomConverter::WsiRequest request;
  request.inputFile = inputFile;
  request.outputFileMask = outputFolder;
  request.frameSizeX = tileWidth;
  request.frameSizeY = tileHeight;
  request.compression = dcmCompressionFromString(compression);
  request.quality = 80;
  request.startOnLevel = start;
  request.stopOnLevel = stop;
  request.imageName = seriesDescription;
  request.studyId = studyId;
  request.seriesId = seriesId;
  request.jsonFile = jsonFile;
  request.retileLevels = levels;
  request.downsamples = &downsamples[0];
  request.tiled = !sparse;
  request.batchLimit = batch;
  request.threads = threads;
  request.dropFirstRowAndColumn = dropFirstRowAndColumn;
  request.debug = debug;
  wsiToDicomConverter::WsiToDcm::wsi2dcm(request);

  return SUCCESS;
}
<|endoftext|>


<commit_before>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#include <iostream>
#include <list>
#define _CRT_SECURE_NO_WARNINGS
#include <chaiscript/chaiscript.hpp>

#ifdef READLINE_AVAILABLE
#include <readline/readline.h>
#include <readline/history.h>
#else
char* readline(const char* p)
{
  std::string retval;
  std::cout << p ;
  std::getline(std::cin, retval);
#ifdef BOOST_MSVC
  return std::cin.eof() ? NULL : _strdup(retval.c_str());
#else
  return std::cin.eof() ? NULL : strdup(retval.c_str());
#endif
}
void add_history(const char*){}
void using_history(){}
#endif

void help(int n) {
  if ( n >= 0 ) {
    std::cout << "ChaiScript evaluator.  To evaluate an expression, type it and press <enter>." << std::endl;
    std::cout << "Additionally, you can inspect the runtime system using:" << std::endl;
    std::cout << "  dump_system() - outputs all functions registered to the system" << std::endl;
    std::cout << "  dump_object(x) - dumps information about the given symbol" << std::endl;
  } else {
    std::cout << "usage : chai [option]+" << std::endl;
    std::cout << "option:"                << std::endl;
    std::cout << "   -h | --help"         << std::endl;
    std::cout << "   -i | --interactive"  << std::endl;
    std::cout << "   -c | --command cmd"  << std::endl;
    std::cout << "   -v | --version"      << std::endl;
    std::cout << "   -    --stdin"        << std::endl;
    std::cout << "   filepath"            << std::endl;
  }
}

void version(int){
  std::cout << "chai: compiled " << __TIME__ << " " << __DATE__ << std::endl;
}

bool throws_exception(const chaiscript::Proxy_Function &f)
{
  try {
    chaiscript::functor<void ()>(f)();
  } catch (...) {
    return true;
  }

  return false;
}

std::string trim(std::string source,const std::string& t)
{
  std::string result = source ;
  result.erase(result.find_last_not_of(t)+1);
  result.erase(0, result.find_first_not_of(t));
  return result ;
}

std::string get_next_command() {
  std::string retval("quit");
  if ( ! std::cin.eof() ) {
    char *input_raw = readline("eval> ");
    if ( input_raw ) {
      add_history(input_raw);
      retval = trim(std::string(input_raw),std::string(" \t"));
      ::free(input_raw);
    }
  }
  if(   retval == "quit"
     || retval == "exit"
     || retval == "help"
     || retval == "version")
  {
    retval += "(0)";
  }
  return retval;
}

// We have to wrap exit with our own because Clang has a hard time with
// function pointers to functions with special attributes (system exit being marked NORETURN)
void myexit(int return_val) {
  exit(return_val);
}

void interactive(chaiscript::ChaiScript& chai)
{
  using_history();

  for (;;) {
    std::string input = get_next_command();
    try {
      // evaluate input
      chaiscript::Boxed_Value val = chai.eval(input);

      //Then, we try to print the result of the evaluation to the user
      if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) {
        try {
          chaiscript::dispatch(chai.get_eval_engine().get_function("print"), chaiscript::Param_List_Builder() << val);
        }
        catch (...) {} //If we can't, do nothing
      }
    }
    catch (chaiscript::Eval_Error &ee) {
      std::cout << ee.what();
      if (ee.call_stack.size() > 0) {
        std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
      }
      std::cout << std::endl;
    }
    catch (std::exception &e) {
      std::cout << e.what();
      std::cout << std::endl;
    }
  }
}

int main(int argc, char *argv[])
{
  std::vector<std::string> usepaths;
  std::vector<std::string> modulepaths;

  // Disable deprecation warning for getenv call.
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

  const char *usepath = getenv("CHAI_USE_PATH");
  const char *modulepath = getenv("CHAI_MODULE_PATH");

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

  usepaths.push_back("");
  if (usepath)
  {
    usepaths.push_back(usepath);
  }

  modulepaths.push_back("");
  if (modulepath)
  {
    modulepaths.push_back(modulepath);
  }

  chaiscript::ChaiScript chai(modulepaths,usepaths);

  chai.add(chaiscript::fun(&myexit), "exit");
  chai.add(chaiscript::fun(&myexit), "quit");
  chai.add(chaiscript::fun(&help), "help");
  chai.add(chaiscript::fun(&version), "version");
  chai.add(chaiscript::fun(&throws_exception), "throws_exception");

  for (int i = 0; i < argc; ++i) {
    if ( i == 0 && argc > 1 ) {
      ++i;
    }

    std::string arg( i ? argv[i] : "--interactive" );

    enum { eInteractive
         , eCommand
         , eFile
    } mode = eCommand ;

    if  ( arg == "-c" || arg == "--command" ) {
      if ( (i+1) >= argc ) {
        std::cout << "insufficient input following " << arg << std::endl;
        return EXIT_FAILURE;
      } else {
        arg = argv[++i];
      }
    } else if ( arg == "-" || arg == "--stdin" ) {
      arg = "" ;
      std::string line;
      while ( std::getline(std::cin, line) ) {
        arg += line + '\n' ;
      }
    } else if ( arg == "-v" || arg == "--version" ) {
      arg = "version(0)" ;
    } else if ( arg == "-h" || arg == "--help" ) {
      arg = "help(-1)";
    } else if ( arg == "-i" || arg == "--interactive" ) {
      mode = eInteractive ;
    } else if ( arg.find('-') == 0 ) {
      std::cout << "unrecognised argument " << arg << std::endl;
      return EXIT_FAILURE;
    } else {
      mode = eFile;
    }

    chaiscript::Boxed_Value val ;
    try {
      switch ( mode ) {
        case eInteractive : interactive(chai); break;
        case eCommand     : val = chai.eval(arg); break;
        case eFile        : val = chai.eval_file(arg); break;
      }
    }
    catch (chaiscript::Eval_Error &ee) {
      std::cout << ee.what();
      if (ee.call_stack.size() > 0) {
        std::cout << "during evaluation at (" << *(ee.call_stack[0]->filename) << " " << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
        for (unsigned int j = 1; j < ee.call_stack.size(); ++j) {
          std::cout << std::endl;
          std::cout << "  from " << *(ee.call_stack[j]->filename) << " (" << ee.call_stack[j]->start.line << ", " << ee.call_stack[j]->start.column << ")";
        }
      }
      std::cout << std::endl;
      return EXIT_FAILURE;
    }
    catch (std::exception &e) {
      std::cout << e.what() << std::endl;
      return EXIT_FAILURE;
    }
  }

  return EXIT_SUCCESS;
}
<commit_msg>Move from hand rolled trim function to boost::trim function<commit_after>// This file is distributed under the BSD License.
// See "license.txt" for details.
// Copyright 2009-2010, Jonathan Turner (jonathan@emptycrate.com)
// and Jason Turner (jason@emptycrate.com)
// http://www.chaiscript.com

#include <iostream>
#include <list>
#include <boost/algorithm/string/trim.hpp>

#define _CRT_SECURE_NO_WARNINGS
#include <chaiscript/chaiscript.hpp>

#ifdef READLINE_AVAILABLE
#include <readline/readline.h>
#include <readline/history.h>
#else
char* readline(const char* p)
{
  std::string retval;
  std::cout << p ;
  std::getline(std::cin, retval);
#ifdef BOOST_MSVC
  return std::cin.eof() ? NULL : _strdup(retval.c_str());
#else
  return std::cin.eof() ? NULL : strdup(retval.c_str());
#endif
}
void add_history(const char*){}
void using_history(){}
#endif

void help(int n) {
  if ( n >= 0 ) {
    std::cout << "ChaiScript evaluator.  To evaluate an expression, type it and press <enter>." << std::endl;
    std::cout << "Additionally, you can inspect the runtime system using:" << std::endl;
    std::cout << "  dump_system() - outputs all functions registered to the system" << std::endl;
    std::cout << "  dump_object(x) - dumps information about the given symbol" << std::endl;
  } else {
    std::cout << "usage : chai [option]+" << std::endl;
    std::cout << "option:"                << std::endl;
    std::cout << "   -h | --help"         << std::endl;
    std::cout << "   -i | --interactive"  << std::endl;
    std::cout << "   -c | --command cmd"  << std::endl;
    std::cout << "   -v | --version"      << std::endl;
    std::cout << "   -    --stdin"        << std::endl;
    std::cout << "   filepath"            << std::endl;
  }
}

void version(int){
  std::cout << "chai: compiled " << __TIME__ << " " << __DATE__ << std::endl;
}

bool throws_exception(const chaiscript::Proxy_Function &f)
{
  try {
    chaiscript::functor<void ()>(f)();
  } catch (...) {
    return true;
  }

  return false;
}

std::string get_next_command() {
  std::string retval("quit");
  if ( ! std::cin.eof() ) {
    char *input_raw = readline("eval> ");
    if ( input_raw ) {
      add_history(input_raw);
      retval = boost::trim_copy_if(std::string(input_raw),boost::is_any_of(" \t"));
      ::free(input_raw);
    }
  }
  if(   retval == "quit"
     || retval == "exit"
     || retval == "help"
     || retval == "version")
  {
    retval += "(0)";
  }
  return retval;
}

// We have to wrap exit with our own because Clang has a hard time with
// function pointers to functions with special attributes (system exit being marked NORETURN)
void myexit(int return_val) {
  exit(return_val);
}

void interactive(chaiscript::ChaiScript& chai)
{
  using_history();

  for (;;) {
    std::string input = get_next_command();
    try {
      // evaluate input
      chaiscript::Boxed_Value val = chai.eval(input);

      //Then, we try to print the result of the evaluation to the user
      if (!val.get_type_info().bare_equal(chaiscript::user_type<void>())) {
        try {
          chaiscript::dispatch(chai.get_eval_engine().get_function("print"), chaiscript::Param_List_Builder() << val);
        }
        catch (...) {} //If we can't, do nothing
      }
    }
    catch (chaiscript::Eval_Error &ee) {
      std::cout << ee.what();
      if (ee.call_stack.size() > 0) {
        std::cout << "during evaluation at (" << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
      }
      std::cout << std::endl;
    }
    catch (std::exception &e) {
      std::cout << e.what();
      std::cout << std::endl;
    }
  }
}

int main(int argc, char *argv[])
{
  std::vector<std::string> usepaths;
  std::vector<std::string> modulepaths;

  // Disable deprecation warning for getenv call.
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4996)
#endif

  const char *usepath = getenv("CHAI_USE_PATH");
  const char *modulepath = getenv("CHAI_MODULE_PATH");

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

  usepaths.push_back("");
  if (usepath)
  {
    usepaths.push_back(usepath);
  }

  modulepaths.push_back("");
  if (modulepath)
  {
    modulepaths.push_back(modulepath);
  }

  chaiscript::ChaiScript chai(modulepaths,usepaths);

  chai.add(chaiscript::fun(&myexit), "exit");
  chai.add(chaiscript::fun(&myexit), "quit");
  chai.add(chaiscript::fun(&help), "help");
  chai.add(chaiscript::fun(&version), "version");
  chai.add(chaiscript::fun(&throws_exception), "throws_exception");

  for (int i = 0; i < argc; ++i) {
    if ( i == 0 && argc > 1 ) {
      ++i;
    }

    std::string arg( i ? argv[i] : "--interactive" );

    enum { eInteractive
         , eCommand
         , eFile
    } mode = eCommand ;

    if  ( arg == "-c" || arg == "--command" ) {
      if ( (i+1) >= argc ) {
        std::cout << "insufficient input following " << arg << std::endl;
        return EXIT_FAILURE;
      } else {
        arg = argv[++i];
      }
    } else if ( arg == "-" || arg == "--stdin" ) {
      arg = "" ;
      std::string line;
      while ( std::getline(std::cin, line) ) {
        arg += line + '\n' ;
      }
    } else if ( arg == "-v" || arg == "--version" ) {
      arg = "version(0)" ;
    } else if ( arg == "-h" || arg == "--help" ) {
      arg = "help(-1)";
    } else if ( arg == "-i" || arg == "--interactive" ) {
      mode = eInteractive ;
    } else if ( arg.find('-') == 0 ) {
      std::cout << "unrecognised argument " << arg << std::endl;
      return EXIT_FAILURE;
    } else {
      mode = eFile;
    }

    chaiscript::Boxed_Value val ;
    try {
      switch ( mode ) {
        case eInteractive : interactive(chai); break;
        case eCommand     : val = chai.eval(arg); break;
        case eFile        : val = chai.eval_file(arg); break;
      }
    }
    catch (chaiscript::Eval_Error &ee) {
      std::cout << ee.what();
      if (ee.call_stack.size() > 0) {
        std::cout << "during evaluation at (" << *(ee.call_stack[0]->filename) << " " << ee.call_stack[0]->start.line << ", " << ee.call_stack[0]->start.column << ")";
        for (unsigned int j = 1; j < ee.call_stack.size(); ++j) {
          std::cout << std::endl;
          std::cout << "  from " << *(ee.call_stack[j]->filename) << " (" << ee.call_stack[j]->start.line << ", " << ee.call_stack[j]->start.column << ")";
        }
      }
      std::cout << std::endl;
      return EXIT_FAILURE;
    }
    catch (std::exception &e) {
      std::cout << e.what() << std::endl;
      return EXIT_FAILURE;
    }
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>

using namespace std;
bool global_continue = true;
void fixing_spacing_command(char *org_prompt)
{
    char *finished_prompt = (char*)malloc(50000);
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == '#')
        {
            org_prompt[x] = '\0';
            finished_prompt[i] = '\0';
        }
        else if(org_prompt[x] == ';')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = ';';
            finished_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == '&' && org_prompt[x] == '&')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == '|' && org_prompt[x] == '|')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            finished_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') finished_prompt[i + 1] = '\0';
    }
    strcpy(org_prompt, finished_prompt);

}

void execute(char* command, char* command_list[], int conect_type)
{
    int exec_status;
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0)            //child process
    {

        exec_status = (execvp(command, command_list));
        if(exec_status == -1)
        {
            perror("error with passed in argument list");
            exit(1);
        }
    }
    else if(process_ID > 0)
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    if(exec_status == -1  && conect_type == 1)
    {
        cout << "execstatus: " << exec_status << endl;
        global_continue = true;
    }
    if(exec_status == -1  && conect_type == 2)
    {
        cout << "second one fucked up" << endl;
        global_continue = false;
    }
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return  0;
    else if(!strcmp(check, "||")) return  1;
    else if(!strcmp(check, "&&")) return  2;
    else return -1;
}

int main(int argc, char **argv)
{
    int sequence = 0;           //sequence of which is executable and flags
    int status;
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token;            //will be bit of code strtok cuts off

    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }

    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }
    //outputs the userinfo with login and host
    while(prompter)
    {
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;

        string converter;                           //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] =  to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder);
        int connect_check;

        token = strtok(prompt_holder, "\t ");
        connect_check = check_connections(token);
        while(token != NULL  &&  prompter)
        {
            if(connect_check == -1 && sequence < 1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++;                     //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;

            }
            else if(connect_check != -1 && global_continue == true)
            {
                cout << "outputting token: " << token << endl;
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                execute(comd_arr[0], comd_arr, connect_check);
            }
            token = strtok(NULL, "\t ");
            cout << "outputlast token: " << token << endl;
            if(connect_check == -1 && token == NULL && global_continue == true)
            {
                cout << "did this execute" << endl;
                comd_arr[comd_arr_cnt] = '\0';
                execute(comd_arr[0], comd_arr, connect_check);
            }
        }
    }

}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<commit_msg>reset back to before deletion<commit_after>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>

using namespace std;
bool global_continue = true;
void fixing_spacing_command(char *org_prompt)
{
    char *finished_prompt = (char*)malloc(50000);
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == '#')
        {
            org_prompt[x] = '\0';
            finished_prompt[i] = '\0';
        }
        else if(org_prompt[x] == ';')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = ';';
            finished_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == '&' && org_prompt[x] == '&')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == '|' && org_prompt[x] == '|')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            finished_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') finished_prompt[i + 1] = '\0';
    }
    strcpy(org_prompt, finished_prompt);

}

bool execute(char* command, char* command_list[], int conect_type)
{
    int exec_status;
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0)            //child process
    {

        exec_status = (execvp(command, command_list));
        if(exec_status == -1)
        {
            perror("error with passed in argument list");
            exit(1);
        }
    }
    else if(process_ID > 0)
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2));
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return  0;
    else if(!strcmp(check, "||")) return  1;
    else if(!strcmp(check, "&&")) return  2;
    else return -1;
}

int main(int argc, char **argv)
{
    int sequence = 0;           //sequence of which is executable and flags
    int status;
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token;            //will be bit of code strtok cuts off

    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }

    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }
    //outputs the userinfo with login and host
    while(prompter)
    {
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;

        string converter;                           //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] =  to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder);
        int connect_check;                          //indicates which connection is in token
        int exec_result;
        token = strtok(prompt_holder, "\t ");
        while(token != NULL  &&  prompter)
        {
            connect_check = check_connections(token);
            cout << "connect_check: " << connect_check << endl;
            cout << "first token: " << token << endl;
            if(connect_check == -1 && sequence < 1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++;                     //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;

            }
            else if(connect_check != -1 && global_continue == true)
            {
                cout << "outputting token: " << token << endl;
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                exec_result = execute(comd_arr[0], comd_arr, connect_check);
                cout << "exex_result: " << exec_result << endl;
            }
            token = strtok(NULL, " ");
            if(connect_check == -1 && token == NULL && global_continue == true)
            {
                cout << "did this execute" << endl;
                comd_arr[comd_arr_cnt] = '\0';
                execute(comd_arr[0], comd_arr, connect_check);
            }
        }
    }
}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<|endoftext|>


<commit_before>/*
   Filename: main.hpp
   Purpose:  Main applicaiton entry point

   Part of Engine2D

   Copyright (C) 2014 Vbitz

   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.
*/

#pragma once<commit_msg>Removed src/main.hpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_processes_api.h"

#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"

#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"

namespace keys = extension_processes_api_constants;

DictionaryValue* CreateProcessValue(int process_id,
                                    const std::string& type,
                                    double cpu,
                                    int64 net,
                                    int64 pr_mem,
                                    int64 sh_mem) {
  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(keys::kIdKey, process_id);
  result->SetString(keys::kTypeKey, type);
  result->SetDouble(keys::kCpuKey, cpu);
  result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
  result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
  result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
  return result;
}

ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
  return Singleton<ExtensionProcessesEventRouter>::get();
}

ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
  model_ = TaskManager::GetInstance()->model();
  model_->AddObserver(this);
}

ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
  model_->RemoveObserver(this);
}

void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
  profiles_.insert(profile);
}

void ExtensionProcessesEventRouter::ListenerAdded() {
  model_->StartUpdating();
}

void ExtensionProcessesEventRouter::ListenerRemoved() {
  model_->StopUpdating();
}

void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
  if (model_) {
    ListValue args;
    DictionaryValue* processes = new DictionaryValue();
    for (int i = start; i < start + length; i++) {
      if (model_->IsResourceFirstInGroup(i)) {
        int id = model_->GetProcessId(i);

        // Determine process type
        std::string type = keys::kProcessTypeOther;
        TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
        switch (resource_type) {
          case TaskManager::Resource::BROWSER:
            type = keys::kProcessTypeBrowser;
            break;
          case TaskManager::Resource::RENDERER:
            type = keys::kProcessTypeRenderer;
            break;
          case TaskManager::Resource::EXTENSION:
            type = keys::kProcessTypeExtension;
            break;
          case TaskManager::Resource::NOTIFICATION:
            type = keys::kProcessTypeNotification;
            break;
          case TaskManager::Resource::PLUGIN:
            type = keys::kProcessTypePlugin;
            break;
          case TaskManager::Resource::WORKER:
            type = keys::kProcessTypeWorker;
            break;
          case TaskManager::Resource::NACL:
            type = keys::kProcessTypeNacl;
            break;
          case TaskManager::Resource::UTILITY:
            type = keys::kProcessTypeUtility;
            break;
          case TaskManager::Resource::GPU:
            type = keys::kProcessTypeGPU;
            break;
          case TaskManager::Resource::PROFILE_IMPORT:
          case TaskManager::Resource::ZYGOTE:
          case TaskManager::Resource::SANDBOX_HELPER:
          case TaskManager::Resource::UNKNOWN:
            type = keys::kProcessTypeOther;
            break;
          default:
            NOTREACHED() << "Unknown resource type.";
        }

        // Get process metrics as numbers
        double cpu = model_->GetCPUUsage(i);

        // TODO(creis): Network is actually reported per-resource (tab),
        // not per-process.  We should aggregate it here.
        int64 net = model_->GetNetworkUsage(i);
        size_t mem;
        int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;
        int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;

        // Store each process indexed by the string version of its id
        processes->Set(base::IntToString(id),
                       CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
      }
    }
    args.Append(processes);

    std::string json_args;
    base::JSONWriter::Write(&args, &json_args);

    // Notify each profile that is interested.
    for (ProfileSet::iterator it = profiles_.begin();
         it != profiles_.end(); it++) {
      Profile* profile = *it;
      DispatchEvent(profile, keys::kOnUpdated, json_args);
    }
  }
}

void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
    const char* event_name,
    const std::string& json_args) {
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, NULL, GURL());
  }
}

bool GetProcessIdForTabFunction::RunImpl() {
  int tab_id;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));

  TabContentsWrapper* contents = NULL;
  int tab_index = -1;
  if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
                                    NULL, NULL, &contents, &tab_index)) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        extension_tabs_module_constants::kTabNotFoundError,
        base::IntToString(tab_id));
    return false;
  }

  // Return the process ID of the tab as an integer.
  int id = base::GetProcId(contents->web_contents()->
      GetRenderProcessHost()->GetHandle());
  result_.reset(Value::CreateIntegerValue(id));
  return true;
}
<commit_msg>ifdef'd out more references to TaskManager<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_processes_api.h"

#include "base/callback.h"
#include "base/json/json_writer.h"
#include "base/message_loop.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"

#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_processes_api_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/extension_tabs_module_constants.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"

namespace keys = extension_processes_api_constants;

DictionaryValue* CreateProcessValue(int process_id,
                                    const std::string& type,
                                    double cpu,
                                    int64 net,
                                    int64 pr_mem,
                                    int64 sh_mem) {
  DictionaryValue* result = new DictionaryValue();
  result->SetInteger(keys::kIdKey, process_id);
  result->SetString(keys::kTypeKey, type);
  result->SetDouble(keys::kCpuKey, cpu);
  result->SetDouble(keys::kNetworkKey, static_cast<double>(net));
  result->SetDouble(keys::kPrivateMemoryKey, static_cast<double>(pr_mem));
  result->SetDouble(keys::kSharedMemoryKey, static_cast<double>(sh_mem));
  return result;
}

ExtensionProcessesEventRouter* ExtensionProcessesEventRouter::GetInstance() {
  return Singleton<ExtensionProcessesEventRouter>::get();
}

ExtensionProcessesEventRouter::ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
  model_ = TaskManager::GetInstance()->model();
  model_->AddObserver(this);
#endif  // defined(ENABLE_TASK_MANAGER)
}

ExtensionProcessesEventRouter::~ExtensionProcessesEventRouter() {
#if defined(ENABLE_TASK_MANAGER)
  model_->RemoveObserver(this);
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::ObserveProfile(Profile* profile) {
  profiles_.insert(profile);
}

void ExtensionProcessesEventRouter::ListenerAdded() {
#if defined(ENABLE_TASK_MANAGER)
  model_->StartUpdating();
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::ListenerRemoved() {
#if defined(ENABLE_TASK_MANAGER)
  model_->StopUpdating();
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::OnItemsChanged(int start, int length) {
#if defined(ENABLE_TASK_MANAGER)
  if (model_) {
    ListValue args;
    DictionaryValue* processes = new DictionaryValue();
    for (int i = start; i < start + length; i++) {
      if (model_->IsResourceFirstInGroup(i)) {
        int id = model_->GetProcessId(i);

        // Determine process type
        std::string type = keys::kProcessTypeOther;
        TaskManager::Resource::Type resource_type = model_->GetResourceType(i);
        switch (resource_type) {
          case TaskManager::Resource::BROWSER:
            type = keys::kProcessTypeBrowser;
            break;
          case TaskManager::Resource::RENDERER:
            type = keys::kProcessTypeRenderer;
            break;
          case TaskManager::Resource::EXTENSION:
            type = keys::kProcessTypeExtension;
            break;
          case TaskManager::Resource::NOTIFICATION:
            type = keys::kProcessTypeNotification;
            break;
          case TaskManager::Resource::PLUGIN:
            type = keys::kProcessTypePlugin;
            break;
          case TaskManager::Resource::WORKER:
            type = keys::kProcessTypeWorker;
            break;
          case TaskManager::Resource::NACL:
            type = keys::kProcessTypeNacl;
            break;
          case TaskManager::Resource::UTILITY:
            type = keys::kProcessTypeUtility;
            break;
          case TaskManager::Resource::GPU:
            type = keys::kProcessTypeGPU;
            break;
          case TaskManager::Resource::PROFILE_IMPORT:
          case TaskManager::Resource::ZYGOTE:
          case TaskManager::Resource::SANDBOX_HELPER:
          case TaskManager::Resource::UNKNOWN:
            type = keys::kProcessTypeOther;
            break;
          default:
            NOTREACHED() << "Unknown resource type.";
        }

        // Get process metrics as numbers
        double cpu = model_->GetCPUUsage(i);

        // TODO(creis): Network is actually reported per-resource (tab),
        // not per-process.  We should aggregate it here.
        int64 net = model_->GetNetworkUsage(i);
        size_t mem;
        int64 pr_mem = model_->GetPrivateMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;
        int64 sh_mem = model_->GetSharedMemory(i, &mem) ?
            static_cast<int64>(mem) : -1;

        // Store each process indexed by the string version of its id
        processes->Set(base::IntToString(id),
                       CreateProcessValue(id, type, cpu, net, pr_mem, sh_mem));
      }
    }
    args.Append(processes);

    std::string json_args;
    base::JSONWriter::Write(&args, &json_args);

    // Notify each profile that is interested.
    for (ProfileSet::iterator it = profiles_.begin();
         it != profiles_.end(); it++) {
      Profile* profile = *it;
      DispatchEvent(profile, keys::kOnUpdated, json_args);
    }
  }
#endif  // defined(ENABLE_TASK_MANAGER)
}

void ExtensionProcessesEventRouter::DispatchEvent(Profile* profile,
    const char* event_name,
    const std::string& json_args) {
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, NULL, GURL());
  }
}

bool GetProcessIdForTabFunction::RunImpl() {
  int tab_id;
  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &tab_id));

  TabContentsWrapper* contents = NULL;
  int tab_index = -1;
  if (!ExtensionTabUtil::GetTabById(tab_id, profile(), include_incognito(),
                                    NULL, NULL, &contents, &tab_index)) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        extension_tabs_module_constants::kTabNotFoundError,
        base::IntToString(tab_id));
    return false;
  }

  // Return the process ID of the tab as an integer.
  int id = base::GetProcId(contents->web_contents()->
      GetRenderProcessHost()->GetHandle());
  result_.reset(Value::CreateIntegerValue(id));
  return true;
}
<|endoftext|>


<commit_before>#include "../include/IntegerEncodingInitializer.hpp"

namespace clusterer
{
namespace backend
{

IntegerEncodingInitializer::IntegerEncodingInitializer(
        const Graph* g, unsigned maxClusters) : graph(g)
{
    if (maxClusters == 0 || maxClusters >= graph->getNoVertices())
    { maxClusters = graph->getNoVertices() - 1; }

    std::random_device rd;
    rng.seed(rd());
    uni_dist = new std::uniform_int_distribution<unsigned>(0, maxClusters);
}

IntegerVectorEncoding IntegerEncodingInitializer::getRandomSolution()
{
    IntegerVectorEncoding result(graph);
    for (int vert = 0; vert < graph->getNoVertices(); vert++)
    { result.addToCluster(vert, (*uni_dist)(rng)); }
    result.normalize();
    return result;
}

std::vector<IntegerVectorEncoding> IntegerEncodingInitializer::getInitialPopulation(int count)
{
    std::vector<IntegerVectorEncoding> result;
    for (int i = 0; i < count; i++)
    { result.push_back(getRandomSolution()); }
    return result;
}

}  // namespace backend
}  // namespace clusterer

<commit_msg>Fixed random range error<commit_after>#include "../include/IntegerEncodingInitializer.hpp"

namespace clusterer
{
namespace backend
{

IntegerEncodingInitializer::IntegerEncodingInitializer(
        const Graph* g, unsigned maxClusters) : graph(g)
{
    if (maxClusters == 0 || maxClusters >= graph->getNoVertices())
    { maxClusters = graph->getNoVertices() - 1; }

    std::random_device rd;
    rng.seed(rd());
    uni_dist = new std::uniform_int_distribution<unsigned>(0, maxClusters - 1);
}

IntegerVectorEncoding IntegerEncodingInitializer::getRandomSolution()
{
    IntegerVectorEncoding result(graph);
    for (int vert = 0; vert < graph->getNoVertices(); vert++)
    { result.addToCluster(vert, (*uni_dist)(rng)); }
    result.normalize();
    return result;
}

std::vector<IntegerVectorEncoding> IntegerEncodingInitializer::getInitialPopulation(int count)
{
    std::vector<IntegerVectorEncoding> result;
    for (int i = 0; i < count; i++)
    { result.push_back(getRandomSolution()); }
    return result;
}

}  // namespace backend
}  // namespace clusterer

<|endoftext|>


<commit_before>#include <bitcoin/address.hpp>
#include <bitcoin/constants.hpp>
#include <bitcoin/messages.hpp>
#include <bitcoin/kernel.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/network/network.hpp>
#include <bitcoin/util/elliptic_curve_key.hpp>
#include <bitcoin/util/logger.hpp>
#include <bitcoin/util/ripemd.hpp>

#include <functional>
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

using namespace libbitcoin;
using namespace libbitcoin::message;
using std::placeholders::_1;
using std::placeholders::_2;

void display_help()
{
    puts("Usage: mktx [HOST[:PORT]] [OUTPUT] [ADDRESS] [AMOUNT]");
    puts("");
    puts("OUTPUT consists of a transaction hash and output index");
    puts("  125d49f6b826c564ea99345c56286de4b5126e3da38691caa4ccc68c8c8118d5:1");
    puts("AMOUNT uses internal bitcoin values");
    puts("  0.1 BTC = 0.1 * 10^8 = 1000000");
}

void error_exit(const std::string& message, int status=1)
{
    log_error() << "balance: " << message;
    exit(status);
}

std::mutex mutex;
std::condition_variable condition;
bool finished = false;

void close_application()
{
    std::unique_lock<std::mutex> lock(mutex);
    finished = true;
    condition.notify_one();
}

void handle_tx_sent(const std::error_code& ec)
{
    if (ec)
        error_exit(ec.message());
    close_application();
}

void handle_connected(const std::error_code& ec, channel_handle chandle,
    network_ptr net, const message::transaction& tx)
{
    if (ec)
        error_exit(ec.message());
    log_info() << "Connected";
    net->send(chandle, tx, handle_tx_sent);
}

script build_output_script(const short_hash& public_key_hash)
{
    script result;
    result.push_operation({opcode::dup, data_chunk()});
    result.push_operation({opcode::hash160, data_chunk()});
    result.push_operation({opcode::special,
        data_chunk(public_key_hash.begin(), public_key_hash.end())});
    result.push_operation({opcode::equalverify, data_chunk()});
    result.push_operation({opcode::checksig, data_chunk()});
    return result;
}

int main(int argc, char** argv)
{
    if (argc != 5)
    {
        display_help();
        return 0;
    }
    std::vector<std::string> output_parts;
    boost::split(output_parts, argv[2], boost::is_any_of(":"));
    if (output_parts.size() != 2)
        error_exit("output requires transaction hash and index");

    std::string raw_private_key;
    std::getline(std::cin, raw_private_key);
    elliptic_curve_key key;
    if (!key.set_private_key(
            private_data(raw_private_key.begin(), raw_private_key.end())))
        error_exit("bad private key");

    transaction_input input;
    input.previous_output.hash = hash_from_pretty(output_parts[0]);
    if (input.previous_output.hash == null_hash)
        error_exit("malformed previous output transaction hash");
    input.previous_output.index =
        boost::lexical_cast<uint32_t>(output_parts[1]);
    input.sequence = 4294967295;
    data_chunk public_key = key.get_public_key();
    input.input_script.push_operation({opcode::special, public_key});

    transaction_output output;
    output.value = boost::lexical_cast<uint64_t>(argv[4]);
    short_hash dest_pubkey_hash = address_to_short_hash(argv[3]);
    output.output_script = build_output_script(dest_pubkey_hash);

    transaction tx;
    tx.inputs.push_back(input);
    tx.outputs.push_back(output);
    tx.version = 1;
    tx.locktime = 0;

    // Rebuild previous output script
    script script_code =
        build_output_script(generate_ripemd_hash(public_key));

    hash_digest tx_hash =
        script::generate_signature_hash(tx, 0, script_code, 1);
    if (tx_hash == null_hash)
        error_exit("error generating signature hash");
    data_chunk signature = key.sign(tx_hash);
    signature.push_back(0x01);

    script& input_script = tx.inputs[0].input_script;
    input_script = script();
    input_script.push_operation({opcode::special, signature});
    input_script.push_operation({opcode::special, public_key});

    std::vector<std::string> args;
    boost::split(args, argv[1], boost::is_any_of(":"));
    std::string hostname = args[0];
    unsigned short port = 8333;
    if (args.size() > 1)
        port = boost::lexical_cast<unsigned short>(args[1]);

    network_ptr net(new network_impl);
    handshake_connect(net, hostname, port,
        std::bind(&handle_connected, _1, _2, net, tx));

    std::unique_lock<std::mutex> lock(mutex);
    condition.wait(lock, []{ return finished; });
    // Display hash of sent transaction
    log_info() << pretty_hex(hash_transaction(tx));
    sleep(1);
    return 0;
}

<commit_msg>Intermediate step for mktx:<commit_after>#include <bitcoin/address.hpp>
#include <bitcoin/constants.hpp>
#include <bitcoin/dialect.hpp>
#include <bitcoin/messages.hpp>
#include <bitcoin/kernel.hpp>
#include <bitcoin/types.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/network/network.hpp>
#include <bitcoin/util/assert.hpp>
#include <bitcoin/util/elliptic_curve_key.hpp>
#include <bitcoin/util/logger.hpp>
#include <bitcoin/util/ripemd.hpp>

#include <getopt.h>
#include <functional>
#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

using namespace libbitcoin;
using namespace libbitcoin::message;
using std::placeholders::_1;
using std::placeholders::_2;

const option long_opts[] = {
    {"previous-output", required_argument, NULL, 'p'},
    {"recipient", required_argument, NULL, 'r'},
    {"host", required_argument, NULL, 'H'},
    {"port", required_argument, NULL, 'P'},
    {"help", required_argument, NULL, 'h'},
    {NULL, no_argument, NULL, 0}
};

const char* opt_string = "p:r:H:P:h";

void display_help()
{
    puts("Usage: mktx COMMAND [ARGS]...");
    puts("");
    puts("Commands:");
    puts("");
    puts("  create\tCreate a new transaction and output the binary data");
    puts("  send\t\tSend a transaction to the network, reading from STDIN");
    puts("");
    puts("Options:");
    puts("");
    puts(" -p, --previous-output\tPrevious output in the form OUT:INDEX");
    puts(" -r, --recipient\tSpecify a destination ADDRESS:AMOUNT");
    puts("\t\t\tAMOUNT uses internal bitcoin values");
    puts("\t\t\t  0.1 BTC = 0.1 * 10^8 = 1000000");
    puts(" -H, --host\t\tHost of bitcoin node");
    puts(" -P, --port\t\tPort for bitcoin node");
    puts(" -h, --help\t\tThis help text");
    puts("");
    puts("Please email suggestions and questions to <genjix@riseup.net>.");
}

void error_exit(const std::string& message, int status=1)
{
    log_error() << "mktx: " << message;
    exit(status);
}

std::mutex mutex;
std::condition_variable condition;
bool finished = false;

void close_application()
{
    std::unique_lock<std::mutex> lock(mutex);
    finished = true;
    condition.notify_one();
}

void handle_tx_sent(const std::error_code& ec)
{
    if (ec)
        error_exit(ec.message());
    close_application();
}

void handle_connected(const std::error_code& ec, channel_handle chandle,
    network_ptr net, const message::transaction& tx)
{
    if (ec)
        error_exit(ec.message());
    log_info() << "Connected";
    net->send(chandle, tx, handle_tx_sent);
}

script build_output_script(const short_hash& public_key_hash)
{
    script result;
    result.push_operation({opcode::dup, data_chunk()});
    result.push_operation({opcode::hash160, data_chunk()});
    result.push_operation({opcode::special,
        data_chunk(public_key_hash.begin(), public_key_hash.end())});
    result.push_operation({opcode::equalverify, data_chunk()});
    result.push_operation({opcode::checksig, data_chunk()});
    return result;
}

struct destination
{
    std::string address;
    uint64_t amount;
};

void create(std::vector<output_point> previous_outputs,
    std::vector<destination> endpoints, const elliptic_curve_key& key)
{
    if (previous_outputs.size() != 1)
        error_exit("more than 1 previous output not supported yet");

    transaction tx;
    tx.version = 1;
    tx.locktime = 0;

    transaction_input input;
    input.previous_output = previous_outputs[0];
    input.sequence = 4294967295;
    data_chunk public_key = key.get_public_key();
    input.input_script.push_operation({opcode::special, public_key});
    tx.inputs.push_back(input);

    for (const destination& dest: endpoints)
    {
        transaction_output output;
        output.value = dest.amount;
        short_hash dest_pubkey_hash = address_to_short_hash(dest.address);
        output.output_script = build_output_script(dest_pubkey_hash);
        tx.outputs.push_back(output);
    }

    // Rebuild previous output script
    script script_code =
        build_output_script(generate_ripemd_hash(public_key));

    hash_digest tx_hash =
        script::generate_signature_hash(tx, 0, script_code, 1);
    if (tx_hash == null_hash)
        error_exit("error generating signature hash");
    data_chunk signature = key.sign(tx_hash);
    signature.push_back(0x01);

    script& input_script = tx.inputs[0].input_script;
    input_script = script();
    input_script.push_operation({opcode::special, signature});
    input_script.push_operation({opcode::special, public_key});

    original_dialect convert_tx;
    data_chunk raw_tx = convert_tx.to_network(tx);
    BITCOIN_ASSERT(raw_tx ==
        convert_tx.to_network(convert_tx.transaction_from_network(raw_tx)));
    log_info() << std::string(raw_tx.begin(), raw_tx.end());
}

int send(const message::transaction& tx,
    const std::string& hostname, unsigned short port)
{
    network_ptr net(new network_impl);
    handshake_connect(net, hostname, port,
        std::bind(&handle_connected, _1, _2, net, tx));

    std::unique_lock<std::mutex> lock(mutex);
    condition.wait(lock, []{ return finished; });
    // Display hash of sent transaction
    log_info() << pretty_hex(hash_transaction(tx));
    sleep(1);
    return 0;
}

std::string read_stdin()
{
    std::istreambuf_iterator<char> it(std::cin);
    std::istreambuf_iterator<char> end;
    return std::string(it, end);
}

private_data read_private_key()
{
    std::string raw_private_key = read_stdin();
    return private_data(raw_private_key.begin(), raw_private_key.end());
}

message::transaction read_transaction()
{
    std::string raw_tx_string = read_stdin();
    data_chunk raw_tx(raw_tx_string.begin(), raw_tx_string.end());
    original_dialect convert_tx;
    return convert_tx.transaction_from_network(raw_tx);
}

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        display_help();
        return 0;
    }
    std::string command = argv[1];
    argc--;
    argv++;

    std::vector<output_point> previous_outputs;
    std::vector<destination> endpoints;

    std::string hostname = "localhost";
    unsigned short port = 8333;

    int long_index = 0;
    int opt = getopt_long(argc, argv, opt_string, long_opts, &long_index);
    while (opt != -1)
    {
        switch (opt)
        {
            case 'p':
            {
                std::vector<std::string> output_parts;
                boost::split(output_parts, optarg, boost::is_any_of(":"));
                if (output_parts.size() != 2)
                    error_exit("output requires transaction hash and index");
                output_point prevout;
                prevout.hash = hash_from_pretty(output_parts[0]);
                if (prevout.hash == null_hash)
                    error_exit("malformed previous output transaction hash");
                prevout.index = boost::lexical_cast<uint32_t>(output_parts[1]);
                previous_outputs.push_back(prevout);
                break;
            }

            case 'r':
            {
                std::vector<std::string> dest_parts;
                boost::split(dest_parts, optarg, boost::is_any_of(":"));
                if (dest_parts.size() != 2)
                    error_exit("recipient requires address and amount");
                destination dest;
                dest.address = dest_parts[0];
                dest.amount = boost::lexical_cast<uint64_t>(dest_parts[1]);
                endpoints.push_back(dest);
                break;
            }

            case 'H':
                hostname = optarg;
                break;

            case 'P':
                port = boost::lexical_cast<unsigned short>(optarg);
                break;

            case 'h':
                display_help();
                return 0;

            case 0:
            default:
                return -1;
        }
        opt = getopt_long(argc, argv, opt_string, long_opts, &long_index);
    }

    size_t number_args = argc - 2, arg_index = 2;
    if (command == "create")
    {
        if (previous_outputs.empty())
            error_exit("need at least one previous output");
        if (endpoints.empty())
            error_exit("need at least one recipient");
        elliptic_curve_key key;
        if (!key.set_private_key(read_private_key()))
            error_exit("bad private key");
        create(previous_outputs, endpoints, key);
    }
    else if (command == "send")
    {
        message::transaction tx;
        try
        {
            tx = read_transaction();
        }
        catch (end_of_stream)
        {
            error_exit("bad transaction");
        }
        return send(tx, hostname, port);
    }
    else if (command == "help")
    {
        display_help();
        return 0;
    }
    else
        error_exit("not a valid command. See mktx help text.");
    // Should never happen!
    return 1;
}

<|endoftext|>


<commit_before>// Source : https://leetcode.com/problems/bulls-and-cows/
// Author : Calinescu Valentin, Hao Chen
// Date   : 2015-11-04

/***************************************************************************************
 *
 * You are playing the following Bulls and Cows game with your friend: You write a
 * 4-digit secret number and ask your friend to guess it. Each time your friend guesses
 * a number, you give a hint. The hint tells your friend how many digits are in the
 * correct positions (called "bulls") and how many digits are in the wrong positions
 * (called "cows"). Your friend will use those hints to find out the secret number.
 *
 * For example:
 *
 * Secret number:  "1807"
 * Friend's guess: "7810"
 * Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
 * Write a function to return a hint according to the secret number and friend's guess,
 * use A to indicate the bulls and B to indicate the cows. In the above example, your
 * function should return "1A3B".
 *
 * Please note that both secret number and friend's guess may contain duplicate digits,
 * for example:
 *
 * Secret number:  "1123"
 * Friend's guess: "0111"
 * In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and
 * your function should return "1A1B".
 * You may assume that the secret number and your friend's guess only contain digits,
 * and their lengths are always equal.
 *
 * Credits:
 * Special thanks to @jeantimex for adding this problem and creating all test cases.
 *
 ***************************************************************************************/

class Solution {
public:
    string getHint(string secret, string guess) {
        return getHint02(secret, guess);
        return getHint01(secret, guess);
    }

    string getHint01(string secret, string guess) {
        int appears_in_secret[10], appears_in_guess[10], bulls[10];
        int total_bulls, total_cows;
        for(int i = 0; i < secret.size(); i++)
            appears_in_secret[secret[i] - '0']++;
        for(int i = 0; i < guess.size(); i++)
        {
             if(secret[i] == guess[i])
                 bulls[secret[i] - '0']++;
             appears_in_guess[guess[i] - '0']++;
        }
        for(int i = 0; i <= 9; i++)
        {
            total_bulls += bulls[i];
            total_cows += min(appears_in_secret[i], appears_in_guess[i]) - bulls[i];
        }
        return to_string(total_bulls) + "A" + to_string(total_cows) + "B";
    }

    // Another implemntation - to save more space
    string getHint02(string secret, string guess) {

        const int digital_num = 10;
        int secret_stat[digital_num]={0};

        int bull = 0;
        for(int i=0; i<secret.size(); i++) {
            //both number & location are matched, count bull
            if ( secret[i] == guess[i] ) {
                bull++;
                continue;
            }
            //otherwise, count the unmatched digits.
            secret_stat[secret[i]-'0']++;
        }

        int cow = 0;
        for(int i=0; i<guess.size(); i++) {
            //deal with duplication - decrease the digits count if cow is found.
            if ( secret[i] != guess[i] && secret_stat[guess[i]-'0']-- > 0 ) {
                cow++;
            }
        }

        return to_string(bull) + "A" + to_string(cow) + "B";
    }
};
<commit_msg>Update bullsAndCows.cpp<commit_after>// Source : https://leetcode.com/problems/bulls-and-cows/
// Author : Calinescu Valentin, Hao Chen
// Date   : 2015-11-04

/***************************************************************************************
 *
 * You are playing the following Bulls and Cows game with your friend: You write a
 * 4-digit secret number and ask your friend to guess it. Each time your friend guesses
 * a number, you give a hint. The hint tells your friend how many digits are in the
 * correct positions (called "bulls") and how many digits are in the wrong positions
 * (called "cows"). Your friend will use those hints to find out the secret number.
 *
 * For example:
 *
 * Secret number:  "1807"
 * Friend's guess: "7810"
 * Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
 * Write a function to return a hint according to the secret number and friend's guess,
 * use A to indicate the bulls and B to indicate the cows. In the above example, your
 * function should return "1A3B".
 *
 * Please note that both secret number and friend's guess may contain duplicate digits,
 * for example:
 *
 * Secret number:  "1123"
 * Friend's guess: "0111"
 * In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and
 * your function should return "1A1B".
 * You may assume that the secret number and your friend's guess only contain digits,
 * and their lengths are always equal.
 *
 * Credits:
 * Special thanks to @jeantimex for adding this problem and creating all test cases.
 *
 ***************************************************************************************/

class Solution {
public:
    string getHint(string secret, string guess) {
        return getHint02(secret, guess);
        return getHint01(secret, guess);
    }

    string getHint01(string secret, string guess) {
        int appears_in_secret[10] = {0}, appears_in_guess[10] = {0}, bulls[10] = {0};
        int total_bulls = 0, total_cows = 0;
        for(int i = 0; i < secret.size(); i++)
            appears_in_secret[secret[i] - '0']++;
        for(int i = 0; i < guess.size(); i++)
        {
             if(secret[i] == guess[i])
                 bulls[secret[i] - '0']++;
             appears_in_guess[guess[i] - '0']++;
        }
        for(int i = 0; i <= 9; i++)
        {
            total_bulls += bulls[i];
            total_cows += min(appears_in_secret[i], appears_in_guess[i]) - bulls[i];
        }
        return to_string(total_bulls) + "A" + to_string(total_cows) + "B";
    }

    // Another implemntation - to save more space
    string getHint02(string secret, string guess) {

        const int digital_num = 10;
        int secret_stat[digital_num]={0};

        int bull = 0;
        for(int i=0; i<secret.size(); i++) {
            //both number & location are matched, count bull
            if ( secret[i] == guess[i] ) {
                bull++;
                continue;
            }
            //otherwise, count the unmatched digits.
            secret_stat[secret[i]-'0']++;
        }

        int cow = 0;
        for(int i=0; i<guess.size(); i++) {
            //deal with duplication - decrease the digits count if cow is found.
            if ( secret[i] != guess[i] && secret_stat[guess[i]-'0']-- > 0 ) {
                cow++;
            }
        }

        return to_string(bull) + "A" + to_string(cow) + "B";
    }
};
<|endoftext|>


<commit_before>#include "SerializationService.hpp"

#include <algorithm>

using namespace Serialization;
using namespace Core;

#define TYPE_FIELD "_type"

SerializationService::SerializationService(const IContextFactory& contextFactory) :
  contextFactory(contextFactory) {
}

std::tuple<Core::Status, std::string>
SerializationService::serialize(const IEntity& entity) const {
  Core::Status result;
  std::unique_ptr<ISerializationContext> context;
  std::tie(result, context) = contextFactory.createSerializationContext(*this);
  if (!result.isOk())
    return std::make_tuple(result, "");

  result = serialize(*context, entity);
  if (!result.isOk())
    return std::make_tuple(result, "");

  return std::make_tuple(Status::OK, context->toString());
}

Core::Status
SerializationService::serialize(ISerializationContext& context, const IEntity& entity) const {
  std::string typeId = entity.getTypeId();
  auto result = context.setString(TYPE_FIELD, typeId);
  if (!result.isOk())
    return result;

  auto serializer = getSerialzier(typeId);
  if (!serializer) {
    return Status(StatusCode::BadRequest,
      "Unable to find a serializer for type """ + typeId + """.");
  }
  return serializer->serialize(context, entity);
}

std::tuple<Core::Status, std::unique_ptr<IEntity>>
SerializationService::deserialize(const std::string& json) const {
  Core::Status result;
  std::unique_ptr<IDeserializationContext> context;
  std::tie(result, context) = contextFactory.createDeserializationContext(*this, json);
  if (!result.isOk())
    return result;

  return deserialize(*context);
}

std::tuple<Core::Status, std::unique_ptr<IEntity>>
SerializationService::deserialize(const IDeserializationContext& context) const {
  Core::Status result;
  std::string typeId;
  std::tie(result, typeId) = context.getString(TYPE_FIELD);
  if (!result.isOk())
    return std::make_tuple(result, nullptr);

  auto serializer = getSerialzier(typeId);
  if (!serializer) {
    return std::make_tuple(Status(StatusCode::BadRequest,
      "Unable to find serializer for type """ + typeId + """."), nullptr);
  }
  return serializer->deserialize(context);
}

void
SerializationService::addSerializer(std::unique_ptr<ISerializer> serializer) {
  serializers.push_back(std::move(serializer));
}

const ISerializer*
SerializationService::getSerialzier(std::string typeId) const {
  auto findIter = std::find_if(serializers.begin(), serializers.end(),
    [&](const std::unique_ptr<ISerializer>& serializer){
      return serializer->getTypeId() == typeId;
    });

  if (findIter == serializers.end())
    return nullptr;

  return findIter->get();
}
<commit_msg>Build fix<commit_after>#include "SerializationService.hpp"

#include <algorithm>

using namespace Serialization;
using namespace Core;

#define TYPE_FIELD "_type"

SerializationService::SerializationService(const IContextFactory& contextFactory) :
  contextFactory(contextFactory) {
}

std::tuple<Core::Status, std::string>
SerializationService::serialize(const IEntity& entity) const {
  Core::Status result;
  std::unique_ptr<ISerializationContext> context;
  std::tie(result, context) = contextFactory.createSerializationContext(*this);
  if (!result.isOk())
    return std::make_tuple(result, "");

  result = serialize(*context, entity);
  if (!result.isOk())
    return std::make_tuple(result, "");

  return std::make_tuple(Status::OK, context->toString());
}

Core::Status
SerializationService::serialize(ISerializationContext& context, const IEntity& entity) const {
  std::string typeId = entity.getTypeId();
  auto result = context.setString(TYPE_FIELD, typeId);
  if (!result.isOk())
    return result;

  auto serializer = getSerialzier(typeId);
  if (!serializer) {
    return Status(StatusCode::BadRequest,
      "Unable to find a serializer for type """ + typeId + """.");
  }
  return serializer->serialize(context, entity);
}

std::tuple<Core::Status, std::unique_ptr<IEntity>>
SerializationService::deserialize(const std::string& json) const {
  Core::Status result;
  std::unique_ptr<IDeserializationContext> context;
  std::tie(result, context) = contextFactory.createDeserializationContext(*this, json);
  if (!result.isOk())
    return std::make_tuple(result, nullptr);

  return deserialize(*context);
}

std::tuple<Core::Status, std::unique_ptr<IEntity>>
SerializationService::deserialize(const IDeserializationContext& context) const {
  Core::Status result;
  std::string typeId;
  std::tie(result, typeId) = context.getString(TYPE_FIELD);
  if (!result.isOk())
    return std::make_tuple(result, nullptr);

  auto serializer = getSerialzier(typeId);
  if (!serializer) {
    return std::make_tuple(Status(StatusCode::BadRequest,
      "Unable to find serializer for type """ + typeId + """."), nullptr);
  }
  return serializer->deserialize(context);
}

void
SerializationService::addSerializer(std::unique_ptr<ISerializer> serializer) {
  serializers.push_back(std::move(serializer));
}

const ISerializer*
SerializationService::getSerialzier(std::string typeId) const {
  auto findIter = std::find_if(serializers.begin(), serializers.end(),
    [&](const std::unique_ptr<ISerializer>& serializer){
      return serializer->getTypeId() == typeId;
    });

  if (findIter == serializers.end())
    return nullptr;

  return findIter->get();
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "hip_event.hpp"
#include "thread/monitor.hpp"

static amd::Monitor streamSetLock("Guards global stream set");
static std::unordered_set<amd::HostQueue*> streamSet;

// Internal structure for stream callback handler
class StreamCallback {
   public:
    StreamCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData,
                  amd::Command* command)
        : stream_(stream), callBack_(callback),
          userData_(userData), command_(command) {
        };
    hipStream_t stream_;
    hipStreamCallback_t callBack_;
    void* userData_;
    amd::Command* command_;
};

namespace hip {

void syncStreams() {
  amd::ScopedLock lock(streamSetLock);

  for (const auto& it : streamSet) {
    it->finish();
  }
}

};

void ihipStreamCallback(cl_event event, cl_int command_exec_status, void* user_data) {

  hipError_t status = hipSuccess;
  StreamCallback* cbo = reinterpret_cast<StreamCallback*>(user_data);
  cbo->callBack_(cbo->stream_, status, cbo->userData_);
  cbo->command_->release();
  delete cbo;
}

static hipError_t ihipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) {
  amd::Device* device = hip::getCurrentContext()->devices()[0];

  cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE;
  amd::HostQueue* queue = new amd::HostQueue(*hip::getCurrentContext(), *device, properties,
                                             amd::CommandQueue::RealTimeDisabled,
                                             amd::CommandQueue::Priority::Normal);

  if (queue == nullptr || !queue->create()) {
    return hipErrorOutOfMemory;
  }

  if (!(flags & hipStreamNonBlocking)) {
    hip::syncStreams();

    {
      amd::ScopedLock lock(streamSetLock);
      streamSet.insert(queue);
    }
  }

  *stream = reinterpret_cast<hipStream_t>(as_cl(queue));

  return hipSuccess;
}

hipError_t hipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) {
  HIP_INIT_API(stream, flags);

  HIP_RETURN(ihipStreamCreateWithFlags(stream, flags));
}

hipError_t hipStreamCreate(hipStream_t *stream) {
  HIP_INIT_API(stream);

  HIP_RETURN(ihipStreamCreateWithFlags(stream, hipStreamDefault));
}

hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int *flags) {
  HIP_INIT_API(stream, flags);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  auto it = streamSet.find(hostQueue);

  if(flags != nullptr) {
    *flags = (it == streamSet.end()) ? hipStreamNonBlocking : hipStreamDefault;
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamSynchronize(hipStream_t stream) {
  HIP_INIT_API(stream);

  amd::HostQueue* hostQueue;

  if (stream == nullptr) {
    hip::syncStreams();

    hostQueue = hip::getNullStream();
  } else {
    hip::getNullStream()->finish();

    hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  }

  if (hostQueue == nullptr) {
    HIP_RETURN(hipErrorUnknown);
  }

  hostQueue->finish();

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamDestroy(hipStream_t stream) {
  HIP_INIT_API(stream);

  if (stream == nullptr) {
    HIP_RETURN(hipErrorInvalidResourceHandle);
  }

  amd::ScopedLock lock(streamSetLock);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();

  // Release last tracked command
  hostQueue->setLastQueuedCommand(nullptr);

  hostQueue->release();
  streamSet.erase(hostQueue);

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags) {
  HIP_INIT_API(stream, event, flags);

  if (stream == nullptr || event == nullptr) {
    HIP_RETURN(hipErrorInvalidResourceHandle);
  }

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  hip::Event* e = reinterpret_cast<hip::Event*>(event);
  cl_event clEvent = as_cl(e->event_);

  amd::Command::EventWaitList eventWaitList;
  cl_int err = amd::clSetEventWaitList(eventWaitList, *hostQueue, 1, &clEvent);
  if (err != CL_SUCCESS) {
    HIP_RETURN(hipErrorUnknown);
  }

  amd::Command* command = new amd::Marker(*hostQueue, true, eventWaitList);
  if (command == NULL) {
    HIP_RETURN(hipErrorOutOfMemory);
  }
  command->enqueue();
  command->release();

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamQuery(hipStream_t stream) {
  HIP_INIT_API(stream);

  amd::HostQueue* hostQueue;
  if (stream == nullptr) {
    hostQueue = hip::getNullStream();
  } else {
    hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  }
  HIP_RETURN(hostQueue->isEmpty() ? hipSuccess : hipErrorNotReady);
}

hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData,
                                unsigned int flags) {
  HIP_INIT_API(stream, callback, userData, flags);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>
                              (stream))->asHostQueue();
  amd::Command* command = hostQueue->getLastQueuedCommand(true);
  amd::Event& event = command->event();
  StreamCallback* cbo = new StreamCallback(stream, callback, userData, command);

  if(!event.setCallback(CL_COMPLETE, ihipStreamCallback, reinterpret_cast<void*>(cbo))) {
    command->release();
    return hipErrorInvalidResourceHandle;
  }

  event.notifyCmdQueue();

  HIP_RETURN(hipSuccess);
}

<commit_msg>P4 to Git Change 1758971 by yaxunl@yaxunl-lc10 on 2019/03/20 12:00:49<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <hip/hip_runtime.h>
#include "hip_internal.hpp"
#include "hip_event.hpp"
#include "thread/monitor.hpp"

static amd::Monitor streamSetLock("Guards global stream set");
static std::unordered_set<amd::HostQueue*> streamSet;

// Internal structure for stream callback handler
class StreamCallback {
   public:
    StreamCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData,
                  amd::Command* command)
        : stream_(stream), callBack_(callback),
          userData_(userData), command_(command) {
        };
    hipStream_t stream_;
    hipStreamCallback_t callBack_;
    void* userData_;
    amd::Command* command_;
};

namespace hip {

void syncStreams() {
  amd::ScopedLock lock(streamSetLock);

  for (const auto& it : streamSet) {
    it->finish();
  }
}

};

void CL_CALLBACK ihipStreamCallback(cl_event event, cl_int command_exec_status, void* user_data) {

  hipError_t status = hipSuccess;
  StreamCallback* cbo = reinterpret_cast<StreamCallback*>(user_data);
  cbo->callBack_(cbo->stream_, status, cbo->userData_);
  cbo->command_->release();
  delete cbo;
}

static hipError_t ihipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) {
  amd::Device* device = hip::getCurrentContext()->devices()[0];

  cl_command_queue_properties properties = CL_QUEUE_PROFILING_ENABLE;
  amd::HostQueue* queue = new amd::HostQueue(*hip::getCurrentContext(), *device, properties,
                                             amd::CommandQueue::RealTimeDisabled,
                                             amd::CommandQueue::Priority::Normal);

  if (queue == nullptr || !queue->create()) {
    return hipErrorOutOfMemory;
  }

  if (!(flags & hipStreamNonBlocking)) {
    hip::syncStreams();

    {
      amd::ScopedLock lock(streamSetLock);
      streamSet.insert(queue);
    }
  }

  *stream = reinterpret_cast<hipStream_t>(as_cl(queue));

  return hipSuccess;
}

hipError_t hipStreamCreateWithFlags(hipStream_t *stream, unsigned int flags) {
  HIP_INIT_API(stream, flags);

  HIP_RETURN(ihipStreamCreateWithFlags(stream, flags));
}

hipError_t hipStreamCreate(hipStream_t *stream) {
  HIP_INIT_API(stream);

  HIP_RETURN(ihipStreamCreateWithFlags(stream, hipStreamDefault));
}

hipError_t hipStreamGetFlags(hipStream_t stream, unsigned int *flags) {
  HIP_INIT_API(stream, flags);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  auto it = streamSet.find(hostQueue);

  if(flags != nullptr) {
    *flags = (it == streamSet.end()) ? hipStreamNonBlocking : hipStreamDefault;
  } else {
    HIP_RETURN(hipErrorInvalidValue);
  }

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamSynchronize(hipStream_t stream) {
  HIP_INIT_API(stream);

  amd::HostQueue* hostQueue;

  if (stream == nullptr) {
    hip::syncStreams();

    hostQueue = hip::getNullStream();
  } else {
    hip::getNullStream()->finish();

    hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  }

  if (hostQueue == nullptr) {
    HIP_RETURN(hipErrorUnknown);
  }

  hostQueue->finish();

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamDestroy(hipStream_t stream) {
  HIP_INIT_API(stream);

  if (stream == nullptr) {
    HIP_RETURN(hipErrorInvalidResourceHandle);
  }

  amd::ScopedLock lock(streamSetLock);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();

  // Release last tracked command
  hostQueue->setLastQueuedCommand(nullptr);

  hostQueue->release();
  streamSet.erase(hostQueue);

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamWaitEvent(hipStream_t stream, hipEvent_t event, unsigned int flags) {
  HIP_INIT_API(stream, event, flags);

  if (stream == nullptr || event == nullptr) {
    HIP_RETURN(hipErrorInvalidResourceHandle);
  }

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  hip::Event* e = reinterpret_cast<hip::Event*>(event);
  cl_event clEvent = as_cl(e->event_);

  amd::Command::EventWaitList eventWaitList;
  cl_int err = amd::clSetEventWaitList(eventWaitList, *hostQueue, 1, &clEvent);
  if (err != CL_SUCCESS) {
    HIP_RETURN(hipErrorUnknown);
  }

  amd::Command* command = new amd::Marker(*hostQueue, true, eventWaitList);
  if (command == NULL) {
    HIP_RETURN(hipErrorOutOfMemory);
  }
  command->enqueue();
  command->release();

  HIP_RETURN(hipSuccess);
}

hipError_t hipStreamQuery(hipStream_t stream) {
  HIP_INIT_API(stream);

  amd::HostQueue* hostQueue;
  if (stream == nullptr) {
    hostQueue = hip::getNullStream();
  } else {
    hostQueue = as_amd(reinterpret_cast<cl_command_queue>(stream))->asHostQueue();
  }
  HIP_RETURN(hostQueue->isEmpty() ? hipSuccess : hipErrorNotReady);
}

hipError_t hipStreamAddCallback(hipStream_t stream, hipStreamCallback_t callback, void* userData,
                                unsigned int flags) {
  HIP_INIT_API(stream, callback, userData, flags);

  amd::HostQueue* hostQueue = as_amd(reinterpret_cast<cl_command_queue>
                              (stream))->asHostQueue();
  amd::Command* command = hostQueue->getLastQueuedCommand(true);
  amd::Event& event = command->event();
  StreamCallback* cbo = new StreamCallback(stream, callback, userData, command);

  if(!event.setCallback(CL_COMPLETE, ihipStreamCallback, reinterpret_cast<void*>(cbo))) {
    command->release();
    return hipErrorInvalidResourceHandle;
  }

  event.notifyCmdQueue();

  HIP_RETURN(hipSuccess);
}

<|endoftext|>