<commit_before>#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

#include <omp.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "alignment.h"
#include "data_array.h"
#include "features/count_source_target.h"
#include "features/feature.h"
#include "features/is_source_singleton.h"
#include "features/is_source_target_singleton.h"
#include "features/max_lex_source_given_target.h"
#include "features/max_lex_target_given_source.h"
#include "features/sample_source_count.h"
#include "features/target_given_source_coherent.h"
#include "grammar.h"
#include "grammar_extractor.h"
#include "precomputation.h"
#include "rule.h"
#include "scorer.h"
#include "suffix_array.h"
#include "time_util.h"
#include "translation_table.h"

namespace fs = boost::filesystem;
namespace po = boost::program_options;
using namespace std;
using namespace extractor;
using namespace features;

fs::path GetGrammarFilePath(const fs::path& grammar_path, int file_number) {
  string file_name = "grammar." + to_string(file_number);
  return grammar_path / file_name;
}

int main(int argc, char** argv) {
  int num_threads_default = 1;
  #pragma omp parallel
  num_threads_default = omp_get_num_threads();

  po::options_description desc("Command line options");
  desc.add_options()
    ("help,h", "Show available options")
    ("source,f", po::value<string>(), "Source language corpus")
    ("target,e", po::value<string>(), "Target language corpus")
    ("bitext,b", po::value<string>(), "Parallel text (source ||| target)")
    ("alignment,a", po::value<string>()->required(), "Bitext word alignment")
    ("grammars,g", po::value<string>()->required(), "Grammars output path")
    ("threads,t", po::value<int>()->default_value(num_threads_default),
        "Number of parallel extractors")
    ("frequent", po::value<int>()->default_value(100),
        "Number of precomputed frequent patterns")
    ("super_frequent", po::value<int>()->default_value(10),
        "Number of precomputed super frequent patterns")
    ("max_rule_span", po::value<int>()->default_value(15),
        "Maximum rule span")
    ("max_rule_symbols", po::value<int>()->default_value(5),
        "Maximum number of symbols (terminals + nontermals) in a rule")
    ("min_gap_size", po::value<int>()->default_value(1), "Minimum gap size")
    ("max_phrase_len", po::value<int>()->default_value(4),
        "Maximum frequent phrase length")
    ("max_nonterminals", po::value<int>()->default_value(2),
        "Maximum number of nonterminals in a rule")
    ("min_frequency", po::value<int>()->default_value(1000),
        "Minimum number of occurences for a pharse to be considered frequent")
    ("max_samples", po::value<int>()->default_value(300),
        "Maximum number of samples")
    ("tight_phrases", po::value<bool>()->default_value(true),
        "False if phrases may be loose (better, but slower)");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  // Check for help argument before notify, so we don't need to pass in the
  // required parameters.
  if (vm.count("help")) {
    cout << desc << endl;
    return 0;
  }

  po::notify(vm);

  if (!((vm.count("source") && vm.count("target")) || vm.count("bitext"))) {
    cerr << "A paralel corpus is required. "
         << "Use -f (source) with -e (target) or -b (bitext)."
         << endl;
    return 1;
  }

  Clock::time_point preprocess_start_time = Clock::now();
  cerr << "Reading source and target data..." << endl;
  Clock::time_point start_time = Clock::now();
  shared_ptr<DataArray> source_data_array, target_data_array;
  if (vm.count("bitext")) {
    source_data_array = make_shared<DataArray>(
        vm["bitext"].as<string>(), SOURCE);
    target_data_array = make_shared<DataArray>(
        vm["bitext"].as<string>(), TARGET);
  } else {
    source_data_array = make_shared<DataArray>(vm["source"].as<string>());
    target_data_array = make_shared<DataArray>(vm["target"].as<string>());
  }
  Clock::time_point stop_time = Clock::now();
  cerr << "Reading data took " << GetDuration(start_time, stop_time)
       << " seconds" << endl;

  cerr << "Creating source suffix array..." << endl;
  start_time = Clock::now();
  shared_ptr<SuffixArray> source_suffix_array =
      make_shared<SuffixArray>(source_data_array);
  stop_time = Clock::now();
  cerr << "Creating suffix array took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Reading alignment..." << endl;
  start_time = Clock::now();
  shared_ptr<Alignment> alignment =
      make_shared<Alignment>(vm["alignment"].as<string>());
  stop_time = Clock::now();
  cerr << "Reading alignment took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Precomputing collocations..." << endl;
  start_time = Clock::now();
  shared_ptr<Precomputation> precomputation = make_shared<Precomputation>(
      source_suffix_array,
      vm["frequent"].as<int>(),
      vm["super_frequent"].as<int>(),
      vm["max_rule_span"].as<int>(),
      vm["max_rule_symbols"].as<int>(),
      vm["min_gap_size"].as<int>(),
      vm["max_phrase_len"].as<int>(),
      vm["min_frequency"].as<int>());
  stop_time = Clock::now();
  cerr << "Precomputing collocations took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Precomputing conditional probabilities..." << endl;
  start_time = Clock::now();
  shared_ptr<TranslationTable> table = make_shared<TranslationTable>(
      source_data_array, target_data_array, alignment);
  stop_time = Clock::now();
  cerr << "Precomputing conditional probabilities took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  Clock::time_point preprocess_stop_time = Clock::now();
  cerr << "Overall preprocessing step took "
       << GetDuration(preprocess_start_time, preprocess_stop_time)
       << " seconds" << endl;

  Clock::time_point extraction_start_time = Clock::now();
  vector<shared_ptr<Feature> > features = {
      make_shared<TargetGivenSourceCoherent>(),
      make_shared<SampleSourceCount>(),
      make_shared<CountSourceTarget>(),
      make_shared<MaxLexSourceGivenTarget>(table),
      make_shared<MaxLexTargetGivenSource>(table),
      make_shared<IsSourceSingleton>(),
      make_shared<IsSourceTargetSingleton>()
  };
  shared_ptr<Scorer> scorer = make_shared<Scorer>(features);

  GrammarExtractor extractor(
      source_suffix_array,
      target_data_array,
      alignment,
      precomputation,
      scorer,
      vm["min_gap_size"].as<int>(),
      vm["max_rule_span"].as<int>(),
      vm["max_nonterminals"].as<int>(),
      vm["max_rule_symbols"].as<int>(),
      vm["max_samples"].as<int>(),
      vm["tight_phrases"].as<bool>());

  // Release extra memory used by the initial precomputation.
  precomputation.reset();

  fs::path grammar_path = vm["grammars"].as<string>();
  if (!fs::is_directory(grammar_path)) {
    fs::create_directory(grammar_path);
  }

  string sentence;
  vector<string> sentences, suffixes;
  while (getline(cin, sentence)) {
    sentences.push_back(sentence);
  }

  #pragma omp parallel for schedule(dynamic) \
      num_threads(vm["threads"].as<int>())
  for (size_t i = 0; i < sentences.size(); ++i) {
    string delimiter = "|||", suffix;
    int position = sentences[i].find(delimiter);
    if (position != sentences[i].npos) {
      suffix = sentences[i].substr(position);
      sentences[i] = sentences[i].substr(0, position);
    }
    suffixes.push_back(suffix);

    Grammar grammar = extractor.GetGrammar(sentences[i]);
    ofstream output(GetGrammarFilePath(grammar_path, i).c_str());
    output << grammar;
  }

  for (size_t i = 0; i < sentences.size(); ++i) {
    cout << "<seg grammar=\"" << GetGrammarFilePath(grammar_path, i) << "\" id=\""
         << i << "\"> " << sentences[i] << " </seg> " << suffixes[i] << endl;
  }

  Clock::time_point extraction_stop_time = Clock::now();
  cerr << "Overall extraction step took "
       << GetDuration(extraction_start_time, extraction_stop_time)
       << " seconds" << endl;

  return 0;
}
<commit_msg>Fix output order.<commit_after>#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

#include <omp.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "alignment.h"
#include "data_array.h"
#include "features/count_source_target.h"
#include "features/feature.h"
#include "features/is_source_singleton.h"
#include "features/is_source_target_singleton.h"
#include "features/max_lex_source_given_target.h"
#include "features/max_lex_target_given_source.h"
#include "features/sample_source_count.h"
#include "features/target_given_source_coherent.h"
#include "grammar.h"
#include "grammar_extractor.h"
#include "precomputation.h"
#include "rule.h"
#include "scorer.h"
#include "suffix_array.h"
#include "time_util.h"
#include "translation_table.h"

namespace fs = boost::filesystem;
namespace po = boost::program_options;
using namespace std;
using namespace extractor;
using namespace features;

fs::path GetGrammarFilePath(const fs::path& grammar_path, int file_number) {
  string file_name = "grammar." + to_string(file_number);
  return grammar_path / file_name;
}

int main(int argc, char** argv) {
  int num_threads_default = 1;
  #pragma omp parallel
  num_threads_default = omp_get_num_threads();

  po::options_description desc("Command line options");
  desc.add_options()
    ("help,h", "Show available options")
    ("source,f", po::value<string>(), "Source language corpus")
    ("target,e", po::value<string>(), "Target language corpus")
    ("bitext,b", po::value<string>(), "Parallel text (source ||| target)")
    ("alignment,a", po::value<string>()->required(), "Bitext word alignment")
    ("grammars,g", po::value<string>()->required(), "Grammars output path")
    ("threads,t", po::value<int>()->default_value(num_threads_default),
        "Number of parallel extractors")
    ("frequent", po::value<int>()->default_value(100),
        "Number of precomputed frequent patterns")
    ("super_frequent", po::value<int>()->default_value(10),
        "Number of precomputed super frequent patterns")
    ("max_rule_span", po::value<int>()->default_value(15),
        "Maximum rule span")
    ("max_rule_symbols", po::value<int>()->default_value(5),
        "Maximum number of symbols (terminals + nontermals) in a rule")
    ("min_gap_size", po::value<int>()->default_value(1), "Minimum gap size")
    ("max_phrase_len", po::value<int>()->default_value(4),
        "Maximum frequent phrase length")
    ("max_nonterminals", po::value<int>()->default_value(2),
        "Maximum number of nonterminals in a rule")
    ("min_frequency", po::value<int>()->default_value(1000),
        "Minimum number of occurences for a pharse to be considered frequent")
    ("max_samples", po::value<int>()->default_value(300),
        "Maximum number of samples")
    ("tight_phrases", po::value<bool>()->default_value(true),
        "False if phrases may be loose (better, but slower)");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  // Check for help argument before notify, so we don't need to pass in the
  // required parameters.
  if (vm.count("help")) {
    cout << desc << endl;
    return 0;
  }

  po::notify(vm);

  if (!((vm.count("source") && vm.count("target")) || vm.count("bitext"))) {
    cerr << "A paralel corpus is required. "
         << "Use -f (source) with -e (target) or -b (bitext)."
         << endl;
    return 1;
  }

  Clock::time_point preprocess_start_time = Clock::now();
  cerr << "Reading source and target data..." << endl;
  Clock::time_point start_time = Clock::now();
  shared_ptr<DataArray> source_data_array, target_data_array;
  if (vm.count("bitext")) {
    source_data_array = make_shared<DataArray>(
        vm["bitext"].as<string>(), SOURCE);
    target_data_array = make_shared<DataArray>(
        vm["bitext"].as<string>(), TARGET);
  } else {
    source_data_array = make_shared<DataArray>(vm["source"].as<string>());
    target_data_array = make_shared<DataArray>(vm["target"].as<string>());
  }
  Clock::time_point stop_time = Clock::now();
  cerr << "Reading data took " << GetDuration(start_time, stop_time)
       << " seconds" << endl;

  cerr << "Creating source suffix array..." << endl;
  start_time = Clock::now();
  shared_ptr<SuffixArray> source_suffix_array =
      make_shared<SuffixArray>(source_data_array);
  stop_time = Clock::now();
  cerr << "Creating suffix array took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Reading alignment..." << endl;
  start_time = Clock::now();
  shared_ptr<Alignment> alignment =
      make_shared<Alignment>(vm["alignment"].as<string>());
  stop_time = Clock::now();
  cerr << "Reading alignment took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Precomputing collocations..." << endl;
  start_time = Clock::now();
  shared_ptr<Precomputation> precomputation = make_shared<Precomputation>(
      source_suffix_array,
      vm["frequent"].as<int>(),
      vm["super_frequent"].as<int>(),
      vm["max_rule_span"].as<int>(),
      vm["max_rule_symbols"].as<int>(),
      vm["min_gap_size"].as<int>(),
      vm["max_phrase_len"].as<int>(),
      vm["min_frequency"].as<int>());
  stop_time = Clock::now();
  cerr << "Precomputing collocations took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  cerr << "Precomputing conditional probabilities..." << endl;
  start_time = Clock::now();
  shared_ptr<TranslationTable> table = make_shared<TranslationTable>(
      source_data_array, target_data_array, alignment);
  stop_time = Clock::now();
  cerr << "Precomputing conditional probabilities took "
       << GetDuration(start_time, stop_time) << " seconds" << endl;

  Clock::time_point preprocess_stop_time = Clock::now();
  cerr << "Overall preprocessing step took "
       << GetDuration(preprocess_start_time, preprocess_stop_time)
       << " seconds" << endl;

  Clock::time_point extraction_start_time = Clock::now();
  vector<shared_ptr<Feature> > features = {
      make_shared<TargetGivenSourceCoherent>(),
      make_shared<SampleSourceCount>(),
      make_shared<CountSourceTarget>(),
      make_shared<MaxLexSourceGivenTarget>(table),
      make_shared<MaxLexTargetGivenSource>(table),
      make_shared<IsSourceSingleton>(),
      make_shared<IsSourceTargetSingleton>()
  };
  shared_ptr<Scorer> scorer = make_shared<Scorer>(features);

  GrammarExtractor extractor(
      source_suffix_array,
      target_data_array,
      alignment,
      precomputation,
      scorer,
      vm["min_gap_size"].as<int>(),
      vm["max_rule_span"].as<int>(),
      vm["max_nonterminals"].as<int>(),
      vm["max_rule_symbols"].as<int>(),
      vm["max_samples"].as<int>(),
      vm["tight_phrases"].as<bool>());

  // Release extra memory used by the initial precomputation.
  precomputation.reset();

  fs::path grammar_path = vm["grammars"].as<string>();
  if (!fs::is_directory(grammar_path)) {
    fs::create_directory(grammar_path);
  }

  string sentence;
  vector<string> sentences;
  while (getline(cin, sentence)) {
    sentences.push_back(sentence);
  }

  vector<string> suffixes(sentences.size());
  #pragma omp parallel for schedule(dynamic) \
      num_threads(vm["threads"].as<int>())
  for (size_t i = 0; i < sentences.size(); ++i) {
    string delimiter = "|||", suffix;
    int position = sentences[i].find(delimiter);
    if (position != sentences[i].npos) {
      suffix = sentences[i].substr(position);
      sentences[i] = sentences[i].substr(0, position);
    }
    suffixes[i] = suffix;

    Grammar grammar = extractor.GetGrammar(sentences[i]);
    ofstream output(GetGrammarFilePath(grammar_path, i).c_str());
    output << grammar;
  }

  for (size_t i = 0; i < sentences.size(); ++i) {
    cout << "<seg grammar=\"" << GetGrammarFilePath(grammar_path, i) << "\" id=\""
         << i << "\"> " << sentences[i] << " </seg> " << suffixes[i] << endl;
  }

  Clock::time_point extraction_stop_time = Clock::now();
  cerr << "Overall extraction step took "
       << GetDuration(extraction_start_time, extraction_stop_time)
       << " seconds" << endl;

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <sys/wait.h>
#include<boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main()
{
    string username=getlogin();
    char hostname[999];
    gethostname(hostname, 999);
    string stringinput;
    char* input[999];
    char_separator<char> ands("&&");
    char_separator<char> ors("||");
    char_separator<char> semico(";");
    while(true)
    {
        //if the user name and hostname both exists, then the program displays it before the dollar sign.
        if(getlogin() != '\0' && gethostname(hostname,999) != -1)
            cout << username << "@" << hostname << "$ ";
        else
        {
            perror("your hostname or username couldn't be found!");
            cout << "$ ";
        }
        getline(cin,stringinput);
        //this checks for comments. Basically, everything after the hash symbol is useless
        if(stringinput.find("#") != string::npos)
        {
            stringinput=stringinput.substr(0,stringinput.find("#"));
        }
        if(stringinput.find("||")!=string::npos )
        {
            tokenizer<char_separator<char> > toke(stringinput,ors);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                else if(pid==0)
                {
                    int counter=0;
                    for(tokenizer<char_separator<char> >::iterator
                        it1=tok.begin(); it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;
                    int good=execvp(input[0],input);
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                    if(status<=0)
                        break;
                }
            }
            if(stringinput.find("exit")!=string::npos)
                continue;
        }
        else if(stringinput.find("&&")!=string::npos )
        {
            if(stringinput.find("exit")!=string::npos)
                exit(1);
            tokenizer<char_separator<char> > toke(stringinput,ands);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                else if(pid==0)
                {
                    int counter=0;
                    for(tokenizer<char_separator<char> >::iterator
                        it1=tok.begin(); it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;
                    int good=execvp(input[0],input);
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                    if(status>0)
                        break;
                }
            }
        }
        else
        {
            tokenizer<char_separator<char> > toke(stringinput,semico);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                else if(pid==0)
                {
                    int counter=0;
                    tokenizer<char_separator<char> >::iterator
                    it1=tok.begin();
                    for(; it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;

                    int good=execvp(input[0],input);
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                }
            }
        }
        if(stringinput.find("exit")!=string::npos)
        {
            exit(1);
        }
    }
    return 0;
}

<commit_msg>added some comments<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include <sys/wait.h>
#include<boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int main()
{
    string username=getlogin();
    char hostname[999];
    gethostname(hostname, 999);
    string stringinput;
    char* input[999];
    char_separator<char> ands("&&");
    char_separator<char> ors("||");
    char_separator<char> semico(";");
    while(true)
    {
        //if the user name and hostname both exists, then the program displays it before the dollar sign.
        if(getlogin() != '\0' && gethostname(hostname,999) != -1)
            cout << username << "@" << hostname << "$ ";
        else
        {
            perror("your hostname or username couldn't be found!");
            cout << "$ ";
        }
        getline(cin,stringinput);
        //this checks for comments. Basically, everything after the hash symbol is useless
        if(stringinput.find("#") != string::npos)
        {
            stringinput=stringinput.substr(0,stringinput.find("#"));
        }
        //this checks for ||
        if(stringinput.find("||")!=string::npos )
        {
            tokenizer<char_separator<char> > toke(stringinput,ors);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                else if(pid==0)
                {
                    int counter=0;
                    for(tokenizer<char_separator<char> >::iterator
                        it1=tok.begin(); it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;
                    int good=execvp(input[0],input);
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                    if(status<=0)
                        break;
                }
            }
            if(stringinput.find("exit")!=string::npos)
                continue;
        }
        //this checks for &&
        else if(stringinput.find("&&")!=string::npos )
        {
            if(stringinput.find("exit")!=string::npos)
                exit(1);
            tokenizer<char_separator<char> > toke(stringinput,ands);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                else if(pid==0)
                {
                    int counter=0;
                    for(tokenizer<char_separator<char> >::iterator
                        it1=tok.begin(); it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;
                    int good=execvp(input[0],input);
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                    if(status>0)
                        break;
                }
            }
        }
        //this checks for ; and other things
        else
        {
            tokenizer<char_separator<char> > toke(stringinput,semico);
            tokenizer<char_separator<char> >::iterator it=toke.begin();
            for(; it != toke.end(); it++)
            {
                char_separator<char> space(" ");
                tokenizer<char_separator<char> > tok(*it, space);
                int status=0;
                pid_t pid = fork();
                if(pid==-1)
                {
                    perror("this is an error with fork()");
                    exit(1);
                }
                //checks on the child
                else if(pid==0)
                {
                    //starts to parse and token
                    int counter=0;
                    tokenizer<char_separator<char> >::iterator
                    it1=tok.begin();
                    for(; it1 != tok.end();
                        it1++,counter++)
                    {
                        input[counter]=new char[(*it1).size()];
                        strcpy(input[counter],(*it1).c_str());
                    }
                    input[counter]=0;

                    int good=execvp(input[0],input);
                    //finds a invalid command
                    if(good==-1)
                    {
                        perror("Command is bad and not good!");
                        exit(1);
                    }
                    else
                    {
                        cout << "Good!" << execvp(input[0],input) << endl;
                    }
                }
                else if(pid>=1)
                {
                    waitpid(-1,&status,0);
                    //waits for the child to finish
                }
            }
        }
        if(stringinput.find("exit")!=string::npos)
        {
            exit(1);
        }
    }
    return 0;
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkDebugLeaks.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkDebugLeaks.h"
#include "vtkOutputWindow.h"
#include "vtkObjectFactory.h"

// A singleton that prints out the table, and deletes the table.
class vtkPrintLeaksAtExit
{
public:
  inline void Use()
    {
    }
  ~vtkPrintLeaksAtExit()
    {
      vtkDebugLeaks::PrintCurrentLeaks();
      vtkDebugLeaks::DeleteTable();
    }
};

#ifdef VTK_DEBUG_LEAKS
// the global varible that should be destroyed at exit
static vtkPrintLeaksAtExit vtkPrintLeaksAtExitGlobal;
#endif

// A hash function for converting a string to a long
inline size_t vtkHashString(const char* s)
{
  unsigned long h = 0;
  for ( ; *s; ++s)
    h = 5*h + *s;

  return size_t(h);
}

class vtkDebugLeaksHashNode
{
public:
  vtkDebugLeaksHashNode()
    {
      count =1; // if it goes in, then there is one of them
      key = 0;
      next =0;
    }
  void Print()
    {
      if(this->count)
	{
	vtkGenericWarningMacro("Class " << this->key << " has "
			       << this->count << " instances still around" );
	}
    }
  ~vtkDebugLeaksHashNode()
    {
      delete [] key;
    }
public:
  vtkDebugLeaksHashNode *next;
  char *key;
  int count;
};

class vtkDebugLeaksHashTable
{
public:
  vtkDebugLeaksHashTable();
  vtkDebugLeaksHashNode* GetNode(const char* name);
  void IncrementCount(const char *name);
  unsigned int GetCount(const char *name);
  int DecrementCount(const char* name);
  void PrintTable();
  int IsEmpty();
private:
  vtkDebugLeaksHashNode* nodes[64];
};

vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
  int i;
  for (i = 0; i < 64; i++)
    {
    this->nodes[i] = NULL;
    }
}

vtkDebugLeaks* vtkDebugLeaks::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDebugLeaks");
  if(ret)
    {
    return (vtkDebugLeaks*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkDebugLeaks;
}

void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
  vtkDebugLeaksHashNode *pos;
  vtkDebugLeaksHashNode *newpos;
  int loc;

  pos = this->GetNode(name);
  if(pos)
    {
    pos->count++;
    return;
    }

  newpos = new vtkDebugLeaksHashNode;
  newpos->key = strcpy(new char[strlen(name)+1], name);

  loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16;

  pos = this->nodes[loc];
  if (!pos)
    {
    this->nodes[loc] = newpos;
    return;
    }
  while (pos->next)
    {
    pos = pos->next;
    }
  pos->next = newpos;
}

vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;

  pos = this->nodes[loc];

  if (!pos)
    {
    return NULL;
    }
  while ((pos) && (strcmp(pos->key, key) != 0) )
    {
    pos = pos->next;
    }
  return pos;
}

unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;

  pos = this->nodes[loc];

  if (!pos)
    {
    return 0;
    }
  while ((pos)&&(pos->key != key))
    {
    pos = pos->next;
    }
  if (pos)
    {
    return pos->count;
    }
  return 0;
}

int vtkDebugLeaksHashTable::IsEmpty()
{
  int count = 0;
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->nodes[i];
    if(pos)
      {
      count += pos->count;
      while(pos->next)
	{
	pos = pos->next;
	count += pos->count;
	}
      }
    }
  return !count;
}

int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{

  vtkDebugLeaksHashNode *pos = this->GetNode(key);
  if(pos)
    {
    pos->count--;
    return 1;
    }
  else
    {
    return 0;
    }
}

void vtkDebugLeaksHashTable::PrintTable()
{
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->nodes[i];
    if(pos)
      {
      pos->Print();
      while(pos->next)
	{
	pos = pos->next;
	pos->Print();
	}
      }
    }
}

vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable = 0;

void vtkDebugLeaks::ConstructClass(const char* name)
{
#ifdef VTK_DEBUG_LEAKS
  // force the use of the global varible so it gets constructed
  // but only do this if VTK_DEBUG_LEAKS is on
  vtkPrintLeaksAtExitGlobal.Use();
#endif
  if(!vtkDebugLeaks::MemoryTable)
    vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;

  vtkDebugLeaks::MemoryTable->IncrementCount(name);
}

void vtkDebugLeaks::DestructClass(const char* p)
{
  // Due to globals being deleted, this table may already have
  // been deleted.
  if(vtkDebugLeaks::MemoryTable)
    {
    if(!vtkDebugLeaks::MemoryTable->DecrementCount(p))
      {
      vtkGenericWarningMacro("Deleting unknown object: " << p);
      }
    }
}

void vtkDebugLeaks::PrintCurrentLeaks()
{
  if(!vtkDebugLeaks::MemoryTable)
    {
    return;
    }
  if(vtkDebugLeaks::MemoryTable->IsEmpty())
    {
    return;
    }
  vtkGenericWarningMacro("vtkDebugLeaks has detected LEAKS!\n ");
  vtkObjectFactory::UnRegisterAllFactories();
  vtkDebugLeaks::MemoryTable->PrintTable();
}

void vtkDebugLeaks::DeleteTable()
{
  delete vtkDebugLeaks::MemoryTable;
  vtkDebugLeaks::MemoryTable = 0;
}
<commit_msg>ENH: fix so nothing is printed on exit for unix<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDebugLeaks.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkDebugLeaks.h"
#include "vtkOutputWindow.h"
#include "vtkObjectFactory.h"
#include "vtkOutputWindow.h"

// A singleton that prints out the table, and deletes the table.
class vtkPrintLeaksAtExit
{
public:
  inline void Use()
    {
    }
  ~vtkPrintLeaksAtExit()
    {
      vtkObjectFactory::UnRegisterAllFactories();
      vtkDebugLeaks::PrintCurrentLeaks();
      vtkDebugLeaks::DeleteTable();
    }
};

#ifdef VTK_DEBUG_LEAKS
// the global varible that should be destroyed at exit
static vtkPrintLeaksAtExit vtkPrintLeaksAtExitGlobal;
#endif

// A hash function for converting a string to a long
inline size_t vtkHashString(const char* s)
{
  unsigned long h = 0;
  for ( ; *s; ++s)
    h = 5*h + *s;

  return size_t(h);
}

class vtkDebugLeaksHashNode
{
public:
  vtkDebugLeaksHashNode()
    {
      count =1; // if it goes in, then there is one of them
      key = 0;
      next =0;
    }
  void Print()
    {
      if(this->count)
	{
	vtkGenericWarningMacro("Class " << this->key << " has "
			       << this->count << " instances still around" );
	}
    }
  ~vtkDebugLeaksHashNode()
    {
      delete [] key;
    }
public:
  vtkDebugLeaksHashNode *next;
  char *key;
  int count;
};

class vtkDebugLeaksHashTable
{
public:
  vtkDebugLeaksHashTable();
  vtkDebugLeaksHashNode* GetNode(const char* name);
  void IncrementCount(const char *name);
  unsigned int GetCount(const char *name);
  int DecrementCount(const char* name);
  void PrintTable();
  int IsEmpty();
private:
  vtkDebugLeaksHashNode* nodes[64];
};

vtkDebugLeaksHashTable::vtkDebugLeaksHashTable()
{
  int i;
  for (i = 0; i < 64; i++)
    {
    this->nodes[i] = NULL;
    }
}

vtkDebugLeaks* vtkDebugLeaks::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkDebugLeaks");
  if(ret)
    {
    return (vtkDebugLeaks*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkDebugLeaks;
}

void vtkDebugLeaksHashTable::IncrementCount(const char * name)
{
  vtkDebugLeaksHashNode *pos;
  vtkDebugLeaksHashNode *newpos;
  int loc;

  pos = this->GetNode(name);
  if(pos)
    {
    pos->count++;
    return;
    }

  newpos = new vtkDebugLeaksHashNode;
  newpos->key = strcpy(new char[strlen(name)+1], name);

  loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16;

  pos = this->nodes[loc];
  if (!pos)
    {
    this->nodes[loc] = newpos;
    return;
    }
  while (pos->next)
    {
    pos = pos->next;
    }
  pos->next = newpos;
}

vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;

  pos = this->nodes[loc];

  if (!pos)
    {
    return NULL;
    }
  while ((pos) && (strcmp(pos->key, key) != 0) )
    {
    pos = pos->next;
    }
  return pos;
}

unsigned int vtkDebugLeaksHashTable::GetCount(const char* key)
{
  vtkDebugLeaksHashNode *pos;
  int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16;

  pos = this->nodes[loc];

  if (!pos)
    {
    return 0;
    }
  while ((pos)&&(pos->key != key))
    {
    pos = pos->next;
    }
  if (pos)
    {
    return pos->count;
    }
  return 0;
}

int vtkDebugLeaksHashTable::IsEmpty()
{
  int count = 0;
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->nodes[i];
    if(pos)
      {
      count += pos->count;
      while(pos->next)
	{
	pos = pos->next;
	count += pos->count;
	}
      }
    }
  return !count;
}

int vtkDebugLeaksHashTable::DecrementCount(const char *key)
{

  vtkDebugLeaksHashNode *pos = this->GetNode(key);
  if(pos)
    {
    pos->count--;
    return 1;
    }
  else
    {
    return 0;
    }
}

void vtkDebugLeaksHashTable::PrintTable()
{
  for(int i =0; i < 64; i++)
    {
    vtkDebugLeaksHashNode *pos = this->nodes[i];
    if(pos)
      {
      pos->Print();
      while(pos->next)
	{
	pos = pos->next;
	pos->Print();
	}
      }
    }
}

vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable = 0;

void vtkDebugLeaks::ConstructClass(const char* name)
{
#ifdef VTK_DEBUG_LEAKS
  // force the use of the global varible so it gets constructed
  // but only do this if VTK_DEBUG_LEAKS is on
  vtkPrintLeaksAtExitGlobal.Use();
#endif
  if(!vtkDebugLeaks::MemoryTable)
    vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable;

  vtkDebugLeaks::MemoryTable->IncrementCount(name);
}

void vtkDebugLeaks::DestructClass(const char* p)
{
  // Due to globals being deleted, this table may already have
  // been deleted.
  if(vtkDebugLeaks::MemoryTable)
    {
    if(!vtkDebugLeaks::MemoryTable->DecrementCount(p))
      {
      vtkGenericWarningMacro("Deleting unknown object: " << p);
      }
    }
}

void vtkDebugLeaks::PrintCurrentLeaks()
{
  if(!vtkDebugLeaks::MemoryTable)
    {
    return;
    }
  if(vtkDebugLeaks::MemoryTable->IsEmpty())
    {
    return;
    }
  vtkOutputWindow::GetInstance()->PromptUserOn();
  vtkGenericWarningMacro("vtkDebugLeaks has detected LEAKS!\n ");
  vtkObjectFactory::UnRegisterAllFactories();
  vtkDebugLeaks::MemoryTable->PrintTable();
}

void vtkDebugLeaks::DeleteTable()
{
  delete vtkDebugLeaks::MemoryTable;
  vtkDebugLeaks::MemoryTable = 0;
}
<|endoftext|>


<commit_before>/**
 * @file gis.cpp
 * @brief WELL GIS storage
 * @author Oleg Borschuk
 * @version
 * @date 2011-07-26
 */

#include <memory.h>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <vector>

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

#include "bs_kernel.h"
#include "gis.h"
#include "bs_misc.h"
#include "bs_serialize.h"

using namespace boost;

#ifdef BSPY_EXPORTING_PLUGIN

#include <boost/python.hpp>
using namespace boost::python;

#endif //BSPY_EXPORTING_PLUGIN

namespace blue_sky
{
  gis::gis (bs_type_ctor_param)
    {
      sp_prop = BS_KERNEL.create_object ("prop");
      sp_table = BS_KERNEL.create_object ("table");
      if (!sp_prop || !sp_table)
        {
          bs_throw_exception ("Type (gis) isn't created");
        }
    }
  gis::gis (const gis& rhs)
        : bs_refcounter ()
    {
      *this = rhs;
    }

  void split_str (std::string &s,
                  std::string &name,
                  std::string &units,
                  std::string &data,
                  std::string &description)
    {
      size_t colon_pos;
      size_t dot_pos;
      size_t space_pos;

      colon_pos = s.find_last_of (':');
      description = s.substr (colon_pos + 1);
      s.erase (colon_pos);
      dot_pos = s.find ('.');
      if (dot_pos == s.npos) // dot not found
        {
          name = s;
          trim (name);
        }
      else
        {
          units = s.substr (dot_pos + 1);
          s.erase (dot_pos);
          name = s;
          trim (name);
          space_pos = units.find (' ');
          if (space_pos != units.npos)
            {
              data = units.substr (space_pos + 1);
              units.erase (space_pos);
              trim(data);
            }
          trim (units);
        }
    }
  template <class T>
  T str2T (std::string &s)
    {
      T f;
      trim (s);
      try
        {
          f = boost::lexical_cast<T>(s);
        }
      catch (boost::bad_lexical_cast &)
        {
          f = 0;
        }
      return f;
    }
  int
  gis::read_ver_info (sp_prop_iface prop, std::string &s)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC VER:" << s << std::endl;

      split_str (s, name, units, data, description);
      if (name == "VERS")
        {
          //prop->add_property_f (0, name, description);
          prop->set_f (str2wstr (name), str2T<double>(data));
        }
      else
        {
          prop->add_property_s (L"", str2wstr (name), str2wstr(description));
          prop->set_s (str2wstr (name), str2wstr (data));
        }
      return 0;
    }

  int
  gis::read_wel_info (sp_prop_iface prop, std::string &s, double ver)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC WELL:" << s << std::endl;

      split_str (s, name, units, data, description);
      if (name == "STRT"
          || name == "STOP"
          || name == "STEP"
          || name == "NULL")
        {
          prop->add_property_f (0, str2wstr (name), str2wstr(units));
          prop->set_f (str2wstr (name), str2T<double> (data));
        }
      else if (name == "LIC")
        {
          prop->add_property_i (0, str2wstr (name), str2wstr(description));
          prop->set_i (str2wstr (name), str2T<int> (data));
        }
      else
        {
          if (ver <= 1.2 && data == "")
            {
              prop->add_property_s (L"", str2wstr (name), L"");
              prop->set_s (str2wstr (name), str2wstr (description));
            }
          else if (data != "")
            {
              prop->add_property_s (L"", str2wstr (name), str2wstr(description));
              prop->set_s (str2wstr (name), str2wstr (data));
            }
        }
      return 0;
    }

  int
  gis::read_par_info (sp_prop_iface prop, std::string &s, double ver)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC PAR:" << s << std::endl;
      if (s[0]='-')
        {
          return 0;
        }

      split_str (s, name, units, data, description);
      if (ver <= 1.2 && data == "")
        {
          prop->add_property_s (L"", str2wstr (name), L"");
          prop->set_s (str2wstr (name), str2wstr (description));
        }
      else if (data != "")
        {
          prop->add_property_s (L"", str2wstr (name), str2wstr(description));
          prop->set_s (str2wstr (name), str2wstr (data));
        }
      return 0;
    }

  int
  gis::read_cur_info (sp_prop_iface prop, std::string &s, int n)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;
      std::cout << "SEC CUR:" << s << std::endl;

      std::string param = std::string ("param")
                         + boost::lexical_cast<std::string> (n);
      split_str (s, name, units, data, description);

      if (units != "")
        name = name + " (" + units + ")";
      prop->add_property_s (L"", str2wstr (param), str2wstr(description));
      prop->set_s (str2wstr (param), str2wstr (name));
      return 0;
    }
  int
  gis::read_asc_info (std::vector<t_double> &v, std::string &s,
                      int n, std::ifstream &file)
    {
      namespace qi = boost::spirit::qi;
      using boost::spirit::ascii::space;

      //std::cout << "SEC ASCII:" << s << std::endl;
      for (;!file.eof ();)
        {
          std::string::iterator begin = s.begin();
          std::string::iterator end = s.end();
          if (!qi::phrase_parse (begin, end, *qi::double_, space, v))
            {
              std::cout << "Error: Parsing failed double\n";
            }
          if ((int)v.size () < n)
            {
              if (sp_prop->get_s (L"WRAP") != L"YES")
                {
                  std::cerr << "Error: wrong number of parameters " << v.size ()
                            << " should be " << n << std::endl;
                  return -1;
                }
              std::getline (file, s);
            }
          else
            {
              break;
            }
        }
      //std::cout << v.size () << n << std::endl;
      return 0;
    }

  int
  gis::read_from_las_file (const std::string &fname)
    {
      std::ifstream file;
      std::string s;
      int state = 0;
      const std::string ver_sec = "~V";
      const std::string wel_sec = "~W";
      const std::string par_sec = "~P";
      const std::string cur_sec = "~C";
      const std::string oth_sec = "~O";
      const std::string asc_sec = "~A";
      int param_counter = 0;
      double ver = 0;
      std::vector <t_double> v;
      namespace fs = boost::filesystem;
      fs::path p(fname);
      std::cout << "Start:"  << '\n';
      sp_prop->add_property_f (2.0, L"VERS", L"Version information");
      try
        {
          if (!fs::exists (p) || !is_regular_file (p))
            {
# ifdef BOOST_POSIX_API
              std::cout  << "Error: can not open file " << p << std::endl;
# else  // BOOST_WINDOWS_API
              //std::cout << "Error: can not open file " << p.file_string() << std::endl;
# endif
              return -2;
            }
        }
      catch (const fs::filesystem_error& ex)
        {
          std::cout << "Error:" <<ex.what() << '\n';
          return -1;
        }

      try
        {
          std::string sss = p.string ();
          std::cout << "Read LAS from file: " << sss << std::endl;
          file.open (sss.c_str ());
        }
      catch (...)
        {
          //TODO error
          fprintf (stderr, "Error: cannot open file %s\n", p.string ().c_str ());
          return -2;
        }
      for (;!file.eof ();)
        {
          std::getline (file, s);
          trim (s);
          if (s.length() < 2 || s[0] == '#')
            continue;
          else if (s[0] == '~')
            {
              if (s[1] == 'V') // version info
                {
                  state = 1;
                }
              else if (s[1] == 'W') // well info
                {
                  ver = sp_prop->get_f (L"VERS");
                  state = 2;
                }
              else if (s[1] == 'P') // well info
                {
                  state = 3;
                }
              else if (s[1] == 'C') // well info
                {
                  state = 4;
                }
              else if (s[1] == 'O') // well info
                {
                  state = 5;
                }
              else if (s[1] == 'A') // well info
                {
                  state = 6;
                  sp_table->init (0, param_counter);
                  for (int i = 0; i < param_counter; ++i)
                    {
                      std::string name = std::string ("param")
                                         + boost::lexical_cast<std::string> (i);
                      sp_table->set_col_name (i, sp_prop->get_s (str2wstr (name)));
                    }
                }
              else
                {
                  //TODO unknown section
                std::cout << s << std::endl;
                }
              continue;
            }
          else
            {
              if (state == 1)
                read_ver_info (sp_prop, s);
              else if (state == 2)
                read_wel_info (sp_prop, s, ver);
              else if (state == 3)
                read_par_info (sp_prop, s, ver);
              else if (state == 4)
                {
                  read_cur_info (sp_prop, s, param_counter);
                  ++param_counter;
                }
              else if (state == 6)
                {
                  v.clear ();
                  int ret_code = read_asc_info (v, s, param_counter, file);
                  if (ret_code)
                    return -1;
                  sp_table->push_back (v);
                }

            }

        }
      return 0;
    }

  gis::sp_gis_t
  gis::check_serial () const
    {
      const std::string dump = to_str();
      return serialize_from_str_indirect< gis, gis_iface >(dump);
    }

  std::string
  gis::to_str () const
    {
      return serialize_to_str_indirect< gis, gis_iface >(this);
    }
  void
  gis::from_str (const std::string &s)
    {
      smart_ptr< gis > pv = serialize_from_str_indirect< gis, gis_iface >(s);
      sp_table = pv->sp_table;
      sp_prop = pv->sp_prop;
    }

#ifdef BSPY_EXPORTING_PLUGIN
  std::string
  gis::py_str () const
    {
      std::stringstream s;
      s << wstr2str(sp_prop->py_str ()) << "\n";
      s << sp_table->py_str () << std::endl;
      return s.str ();
    }
#endif //BSPY_EXPORTING_PLUGIN
/////////////////////////////////BS Register
/////////////////////////////////Stuff//////////////////////////

  BLUE_SKY_TYPE_STD_CREATE (gis);
  BLUE_SKY_TYPE_STD_COPY (gis);

  BLUE_SKY_TYPE_IMPL(gis,  gis_iface, "gis", "GIS storage", "realization of well GIS storage");

}  // blue_sky namespace
<commit_msg>common_types: fix typo - assignment instead of comaprison in if clause<commit_after>/**
 * @file gis.cpp
 * @brief WELL GIS storage
 * @author Oleg Borschuk
 * @version
 * @date 2011-07-26
 */

#include <memory.h>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <vector>

#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

#include "bs_kernel.h"
#include "gis.h"
#include "bs_misc.h"
#include "bs_serialize.h"

using namespace boost;

#ifdef BSPY_EXPORTING_PLUGIN

#include <boost/python.hpp>
using namespace boost::python;

#endif //BSPY_EXPORTING_PLUGIN

namespace blue_sky
{
  gis::gis (bs_type_ctor_param)
    {
      sp_prop = BS_KERNEL.create_object ("prop");
      sp_table = BS_KERNEL.create_object ("table");
      if (!sp_prop || !sp_table)
        {
          bs_throw_exception ("Type (gis) isn't created");
        }
    }
  gis::gis (const gis& rhs)
        : bs_refcounter ()
    {
      *this = rhs;
    }

  void split_str (std::string &s,
                  std::string &name,
                  std::string &units,
                  std::string &data,
                  std::string &description)
    {
      size_t colon_pos;
      size_t dot_pos;
      size_t space_pos;

      colon_pos = s.find_last_of (':');
      description = s.substr (colon_pos + 1);
      s.erase (colon_pos);
      dot_pos = s.find ('.');
      if (dot_pos == s.npos) // dot not found
        {
          name = s;
          trim (name);
        }
      else
        {
          units = s.substr (dot_pos + 1);
          s.erase (dot_pos);
          name = s;
          trim (name);
          space_pos = units.find (' ');
          if (space_pos != units.npos)
            {
              data = units.substr (space_pos + 1);
              units.erase (space_pos);
              trim(data);
            }
          trim (units);
        }
    }
  template <class T>
  T str2T (std::string &s)
    {
      T f;
      trim (s);
      try
        {
          f = boost::lexical_cast<T>(s);
        }
      catch (boost::bad_lexical_cast &)
        {
          f = 0;
        }
      return f;
    }
  int
  gis::read_ver_info (sp_prop_iface prop, std::string &s)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC VER:" << s << std::endl;

      split_str (s, name, units, data, description);
      if (name == "VERS")
        {
          //prop->add_property_f (0, name, description);
          prop->set_f (str2wstr (name), str2T<double>(data));
        }
      else
        {
          prop->add_property_s (L"", str2wstr (name), str2wstr(description));
          prop->set_s (str2wstr (name), str2wstr (data));
        }
      return 0;
    }

  int
  gis::read_wel_info (sp_prop_iface prop, std::string &s, double ver)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC WELL:" << s << std::endl;

      split_str (s, name, units, data, description);
      if (name == "STRT"
          || name == "STOP"
          || name == "STEP"
          || name == "NULL")
        {
          prop->add_property_f (0, str2wstr (name), str2wstr(units));
          prop->set_f (str2wstr (name), str2T<double> (data));
        }
      else if (name == "LIC")
        {
          prop->add_property_i (0, str2wstr (name), str2wstr(description));
          prop->set_i (str2wstr (name), str2T<int> (data));
        }
      else
        {
          if (ver <= 1.2 && data == "")
            {
              prop->add_property_s (L"", str2wstr (name), L"");
              prop->set_s (str2wstr (name), str2wstr (description));
            }
          else if (data != "")
            {
              prop->add_property_s (L"", str2wstr (name), str2wstr(description));
              prop->set_s (str2wstr (name), str2wstr (data));
            }
        }
      return 0;
    }

  int
  gis::read_par_info (sp_prop_iface prop, std::string &s, double ver)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;

      std::cout << "SEC PAR:" << s << std::endl;
      if (s[0] == '-')
        {
          return 0;
        }

      split_str (s, name, units, data, description);
      if (ver <= 1.2 && data == "")
        {
          prop->add_property_s (L"", str2wstr (name), L"");
          prop->set_s (str2wstr (name), str2wstr (description));
        }
      else if (data != "")
        {
          prop->add_property_s (L"", str2wstr (name), str2wstr(description));
          prop->set_s (str2wstr (name), str2wstr (data));
        }
      return 0;
    }

  int
  gis::read_cur_info (sp_prop_iface prop, std::string &s, int n)
    {
      std::string description;
      std::string name;
      std::string units;
      std::string data;
      std::cout << "SEC CUR:" << s << std::endl;

      std::string param = std::string ("param")
                         + boost::lexical_cast<std::string> (n);
      split_str (s, name, units, data, description);

      if (units != "")
        name = name + " (" + units + ")";
      prop->add_property_s (L"", str2wstr (param), str2wstr(description));
      prop->set_s (str2wstr (param), str2wstr (name));
      return 0;
    }
  int
  gis::read_asc_info (std::vector<t_double> &v, std::string &s,
                      int n, std::ifstream &file)
    {
      namespace qi = boost::spirit::qi;
      using boost::spirit::ascii::space;

      //std::cout << "SEC ASCII:" << s << std::endl;
      for (;!file.eof ();)
        {
          std::string::iterator begin = s.begin();
          std::string::iterator end = s.end();
          if (!qi::phrase_parse (begin, end, *qi::double_, space, v))
            {
              std::cout << "Error: Parsing failed double\n";
            }
          if ((int)v.size () < n)
            {
              if (sp_prop->get_s (L"WRAP") != L"YES")
                {
                  std::cerr << "Error: wrong number of parameters " << v.size ()
                            << " should be " << n << std::endl;
                  return -1;
                }
              std::getline (file, s);
            }
          else
            {
              break;
            }
        }
      //std::cout << v.size () << n << std::endl;
      return 0;
    }

  int
  gis::read_from_las_file (const std::string &fname)
    {
      std::ifstream file;
      std::string s;
      int state = 0;
      const std::string ver_sec = "~V";
      const std::string wel_sec = "~W";
      const std::string par_sec = "~P";
      const std::string cur_sec = "~C";
      const std::string oth_sec = "~O";
      const std::string asc_sec = "~A";
      int param_counter = 0;
      double ver = 0;
      std::vector <t_double> v;
      namespace fs = boost::filesystem;
      fs::path p(fname);
      std::cout << "Start:"  << '\n';
      sp_prop->add_property_f (2.0, L"VERS", L"Version information");
      try
        {
          if (!fs::exists (p) || !is_regular_file (p))
            {
# ifdef BOOST_POSIX_API
              std::cout  << "Error: can not open file " << p << std::endl;
# else  // BOOST_WINDOWS_API
              //std::cout << "Error: can not open file " << p.file_string() << std::endl;
# endif
              return -2;
            }
        }
      catch (const fs::filesystem_error& ex)
        {
          std::cout << "Error:" <<ex.what() << '\n';
          return -1;
        }

      try
        {
          std::string sss = p.string ();
          std::cout << "Read LAS from file: " << sss << std::endl;
          file.open (sss.c_str ());
        }
      catch (...)
        {
          //TODO error
          fprintf (stderr, "Error: cannot open file %s\n", p.string ().c_str ());
          return -2;
        }
      for (;!file.eof ();)
        {
          std::getline (file, s);
          trim (s);
          if (s.length() < 2 || s[0] == '#')
            continue;
          else if (s[0] == '~')
            {
              if (s[1] == 'V') // version info
                {
                  state = 1;
                }
              else if (s[1] == 'W') // well info
                {
                  ver = sp_prop->get_f (L"VERS");
                  state = 2;
                }
              else if (s[1] == 'P') // well info
                {
                  state = 3;
                }
              else if (s[1] == 'C') // well info
                {
                  state = 4;
                }
              else if (s[1] == 'O') // well info
                {
                  state = 5;
                }
              else if (s[1] == 'A') // well info
                {
                  state = 6;
                  sp_table->init (0, param_counter);
                  for (int i = 0; i < param_counter; ++i)
                    {
                      std::string name = std::string ("param")
                                         + boost::lexical_cast<std::string> (i);
                      sp_table->set_col_name (i, sp_prop->get_s (str2wstr (name)));
                    }
                }
              else
                {
                  //TODO unknown section
                std::cout << s << std::endl;
                }
              continue;
            }
          else
            {
              if (state == 1)
                read_ver_info (sp_prop, s);
              else if (state == 2)
                read_wel_info (sp_prop, s, ver);
              else if (state == 3)
                read_par_info (sp_prop, s, ver);
              else if (state == 4)
                {
                  read_cur_info (sp_prop, s, param_counter);
                  ++param_counter;
                }
              else if (state == 6)
                {
                  v.clear ();
                  int ret_code = read_asc_info (v, s, param_counter, file);
                  if (ret_code)
                    return -1;
                  sp_table->push_back (v);
                }

            }

        }
      return 0;
    }

  gis::sp_gis_t
  gis::check_serial () const
    {
      const std::string dump = to_str();
      return serialize_from_str_indirect< gis, gis_iface >(dump);
    }

  std::string
  gis::to_str () const
    {
      return serialize_to_str_indirect< gis, gis_iface >(this);
    }
  void
  gis::from_str (const std::string &s)
    {
      smart_ptr< gis > pv = serialize_from_str_indirect< gis, gis_iface >(s);
      sp_table = pv->sp_table;
      sp_prop = pv->sp_prop;
    }

#ifdef BSPY_EXPORTING_PLUGIN
  std::string
  gis::py_str () const
    {
      std::stringstream s;
      s << wstr2str(sp_prop->py_str ()) << "\n";
      s << sp_table->py_str () << std::endl;
      return s.str ();
    }
#endif //BSPY_EXPORTING_PLUGIN
/////////////////////////////////BS Register
/////////////////////////////////Stuff//////////////////////////

  BLUE_SKY_TYPE_STD_CREATE (gis);
  BLUE_SKY_TYPE_STD_COPY (gis);

  BLUE_SKY_TYPE_IMPL(gis,  gis_iface, "gis", "GIS storage", "realization of well GIS storage");

}  // blue_sky namespace
<|endoftext|>


<commit_before>#include <ncurses.h>

#include <string>

#include "game.h"
#include "InfoPanel.h"

using namespace std;

void menuShow(WINDOW *wnd, string title);
void startGame();

WINDOW *wmenu, *wmain;

InfoPanel *infoPanel = new InfoPanel();

int init() {

    initscr();

    /*
     * init main window
     */

    wmain = newwin(40, 80, 1, 1);
    box(wmain, 0, 0);

    /*
     * init menu window
     */

    wmenu = newwin(10, 12, 10, 10);
    wborder(wmenu,
            ACS_BULLET, ACS_BULLET, ACS_BULLET, ACS_BULLET,     /* ls, rs, ts, bs */
            '+', '+', '+', '+');                                /* tl, tr, bl, br */

    noecho();
    keypad(wmenu, true);
    curs_set(0);

    return 0;
}

void run() {
    char menuItems[2][10] = {
        "start",
        "quit"
    };
    char menuItem[7];
    int ch, i = 0, width = 7;

    /*
     * init title, menu
     */

    for (i = 0; i < 2; i++) {
        if (i == 0) wattron(wmenu, A_STANDOUT);
        else wattroff(wmenu, A_STANDOUT);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
    }

    wrefresh(wmain);
    wrefresh(wmenu);
    infoPanel->update();
    menuShow(wmain, "TERMINAL QUEST");
    i = 0;

    string infoPos, infoKey, infoMsg;
    bool exitRequested = false, gameRequested = false;
    while (( ch = wgetch(wmenu)) != 'q') {
        infoMsg = "";
        infoPos = to_string(ch);
        infoKey = to_string(i);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);

        switch (ch) {
            case KEY_UP:
            case 'k':
                i--;
                i = (i < 0) ? 1 : i;
                infoMsg = "up";
                break;
            case KEY_DOWN:
            case 'j':
                i++;
                i = (i > 1) ? 0: i;
                infoMsg = "down";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                if (i == 1) exitRequested = true;
                else if (i == 0) gameRequested = true;
                break;

        }

        infoPanel->push((infoPos + ' ' + infoKey + ' ' + infoMsg));

        wattron(wmenu, A_STANDOUT);
        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
        wattroff(wmenu, A_STANDOUT);

        if (exitRequested == true) {
            break;
        } else if (gameRequested) {
            delwin(wmenu);
            delwin(wmain);

            startGame();
            break;
        }
    }

    /*
     * exit
     */

    endwin();

}

void close() {
    endwin();
}

void menuShow(WINDOW *wnd, string title) {

    wmove(wnd, 5, 5);

    for (size_t i = 0; i < title.size(); i++) {
        waddch(wnd, title[i]);
        waddch(wnd, ' ');
    }

    wrefresh(wnd);
}

void startGame() {
    endwin();

    WINDOW *wgame = newwin(40, 80, 1, 1);
    box(wgame, '-', '.');
    wrefresh(wgame);

    keypad(wgame, true);

    wmove(wgame, 1, 1);
    int ch, i;
    while (( ch = wgetch(wgame)) != 'q') {
        waddstr(wgame, to_string(ch).c_str());
        wmove(wgame, 1, 1);

        infoPanel->push(to_string(ch));
    }
    delwin(wgame);
}

<commit_msg>Add movable character to game area<commit_after>#include <ncurses.h>

#include <string>

#include "game.h"
#include "InfoPanel.h"

using namespace std;

void menuShow(WINDOW *wnd, string title);
void startGame();

WINDOW *wmenu, *wmain;

InfoPanel *infoPanel = new InfoPanel();

struct {
    vec2i pos;
    rect bounds;
    char disp_char;
} player;

rect game_area;

int init() {

    initscr();

    /*
     * init main window
     */

    wmain = newwin(40, 80, 1, 1);
    box(wmain, 0, 0);

    /*
     * init menu window
     */

    wmenu = newwin(10, 12, 10, 10);
    wborder(wmenu,
            ACS_BULLET, ACS_BULLET, ACS_BULLET, ACS_BULLET,     /* ls, rs, ts, bs */
            '+', '+', '+', '+');                                /* tl, tr, bl, br */

    noecho();
    keypad(wmenu, true);
    curs_set(0);

    return 0;
}

void run() {
    char menuItems[2][10] = {
        "start",
        "quit"
    };
    char menuItem[7];
    int ch, i = 0, width = 7;

    /*
     * init title, menu
     */

    for (i = 0; i < 2; i++) {
        if (i == 0) wattron(wmenu, A_STANDOUT);
        else wattroff(wmenu, A_STANDOUT);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
    }

    wrefresh(wmain);
    wrefresh(wmenu);
    infoPanel->update();
    menuShow(wmain, "TERMINAL QUEST");
    i = 0;

    string infoPos, infoKey, infoMsg;
    bool exitRequested = false, gameRequested = false;
    while (( ch = wgetch(wmenu)) != 'q') {
        infoMsg = "";
        infoPos = to_string(ch);
        infoKey = to_string(i);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);

        switch (ch) {
            case KEY_UP:
            case 'k':
                i--;
                i = (i < 0) ? 1 : i;
                infoMsg = "up";
                break;
            case KEY_DOWN:
            case 'j':
                i++;
                i = (i > 1) ? 0: i;
                infoMsg = "down";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                if (i == 1) exitRequested = true;
                else if (i == 0) gameRequested = true;
                break;

        }

        infoPanel->push((infoPos + ' ' + infoKey + ' ' + infoMsg));

        wattron(wmenu, A_STANDOUT);
        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
        wattroff(wmenu, A_STANDOUT);

        if (exitRequested == true) {
            break;
        } else if (gameRequested) {
            delwin(wmenu);
            delwin(wmain);

            startGame();
            break;
        }
    }

    /*
     * exit
     */

    endwin();

}

void close() {
    endwin();
}

void menuShow(WINDOW *wnd, string title) {

    wmove(wnd, 5, 5);

    for (size_t i = 0; i < title.size(); i++) {
        waddch(wnd, title[i]);
        waddch(wnd, ' ');
    }

    wrefresh(wnd);
}

void startGame() {

    player.pos = {1, 1};
    player.disp_char = '@';

    //endwin();
    game_area = {
        {1, 1},
        {40, 37} /* {40, 80} minus borders */
    };

    WINDOW *wgame = newwin(40, 80, 1, 1);
    box(wgame, '-', '.');
    keypad(wgame, true);
    wmove(wgame, 1, 1);

    int ch, i;
    string infoKey, infoMsg;
    vec2i infoPos;
    while (( ch = wgetch(wgame)) != 'q') {

        infoMsg = "";
        infoKey = to_string(ch);

        werase(wgame);
        box(wgame, '-', '.');

        switch (ch) {
            case KEY_UP:
            case 'k':
                /* TODO check for area bounds */
                if (player.pos.y > game_area.top()) player.pos.y--;
                break;
            case KEY_DOWN:
            case 'j':
                /* TODO check for area bounds */
                if (player.pos.y < game_area.bot()) player.pos.y++;
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                break;

        }

        wmove(wgame, player.pos.y, 1);
        waddch(wgame, player.disp_char);

        infoPanel->push('{'
            + std::to_string(player.pos.x) + ','
            + std::to_string(player.pos.y) + '}'
            + '{'
            + std::to_string(game_area.top()) + ','
            + std::to_string(game_area.bot()) + '}'
        );

        wrefresh(wgame);

    }

    delwin(wgame);
}

<|endoftext|>


<commit_before>#include <game.h>
#include <log.h>
#include <text.h>
#include <fpscounter.h>
#include <camera.h>
#include <noise.h>
#include <graphics.h>

Game* currentGame;
void error_callback(int error, const char* description){loge.log("GLFW Error: %s",description);}
void glDebugMessageCallbackFunction( GLenum source, GLenum type, GLuint id,
                   GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam)
{
  loge.log("OpenGL: %s",message);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
  if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
    glfwSetWindowShouldClose(window, GL_TRUE);
  else
    currentGame->key(key,scancode,action,mods);
}

/// The constructor for the game class
///
/// This function is called on the creation of a new game.  It loads
/// all the data, initialises the screen and keyboard functions.
/// @param doGraphics Should this game initialise graphics?
Game::Game()
{
  logi.log("New game");
  logi.log("Initialising Graphics");
  initGraphics();
  initNoise();
  terrain = new Terrain(glm::vec3(0),this);
  mouseCameraControl = false;
  currentGame = this;
  for (int i = 0;i<256;i++)keys[i] =false;
}
glm::vec2 oldMousePos;
void Game::initGraphics()
{
  // Initialise GLFW
  if (!glfwInit())
    DIE("glfwInit failed");
  glfwSetErrorCallback(error_callback);
  mainWindow = new Window(this);
  mainWindow->setKeyCallBack(&key_callback);
  // Initialise glew.  If there is an error, report it
  glewExperimental=GL_TRUE;
  GLenum res = glewInit();
  if (res != GLEW_OK)
  {
    DIE2("Could not start GLEW:", glewGetErrorString(res));
  }
  glDebugMessageCallbackARB((GLDEBUGPROCARB) glDebugMessageCallbackFunction, NULL);
  glEnable(GL_DEPTH_TEST);
  glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

  initTextEngine();
  shaderManager = new ShaderManager();
  camera = new Camera(&shaderManager->frameData.cameraMatrix,&shaderManager->frameData.cameraPosition);
  camera->setPosition(glm::vec3(4000,100,4000));
  oldMousePos = mainWindow->getSize()/2.f;
}

/// Run the game
void Game::run()
{
  logi.log("Running game...");
  while ((!mainWindow->shouldClose()))
  {
    float ms = getFrameDiff();
    logFrame();
    float fps = getFrameRate();
    char buffer[80]; sprintf(buffer,"Project Magrathea III (%.2f FPS : %.0fms)",fps,ms*1000);
    mainWindow->setTitle(buffer);

    if (mouseCameraControl)
      camera->getInputFromWindow(mainWindow);
    if (keys['W'])
      camera->MoveForward(ms*50.f);
    if (keys['S'])
      camera->MoveForward(-ms*50.f);

    glfwPollEvents();
    mainWindow->setContext();
    renderMainWindow();
    mainWindow->swapBuffers();
  }
  glfwTerminate();
}

void Game::renderMainWindow()
{
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  camera->Render();
  shaderManager->setFrameData();
  terrain->Render();
}

void Game::key(int key, int scancode, int action, int mods)
{
  if (action==GLFW_PRESS)
  {
    if (key=='Q')
    {
      mouseCameraControl = !mouseCameraControl;
      if (mouseCameraControl)
        mainWindow->setMouseCentre();
    }
    keys[key] = true;
  }
  if (action==GLFW_RELEASE)
    keys[key] = false;
}
<commit_msg>Alpha and sky colour<commit_after>#include <game.h>
#include <log.h>
#include <text.h>
#include <fpscounter.h>
#include <camera.h>
#include <noise.h>
#include <graphics.h>

Game* currentGame;
void error_callback(int error, const char* description){loge.log("GLFW Error: %s",description);}
void glDebugMessageCallbackFunction( GLenum source, GLenum type, GLuint id,
                   GLenum severity, GLsizei length, const GLchar* message, GLvoid* userParam)
{
  loge.log("OpenGL: %s",message);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
  if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
    glfwSetWindowShouldClose(window, GL_TRUE);
  else
    currentGame->key(key,scancode,action,mods);
}

/// The constructor for the game class
///
/// This function is called on the creation of a new game.  It loads
/// all the data, initialises the screen and keyboard functions.
/// @param doGraphics Should this game initialise graphics?
Game::Game()
{
  logi.log("New game");
  logi.log("Initialising Graphics");
  initGraphics();
  initNoise();
  terrain = new Terrain(glm::vec3(0),this);
  mouseCameraControl = false;
  currentGame = this;
  for (int i = 0;i<256;i++)keys[i] =false;
}
glm::vec2 oldMousePos;
void Game::initGraphics()
{
  // Initialise GLFW
  if (!glfwInit())
    DIE("glfwInit failed");
  glfwSetErrorCallback(error_callback);
  mainWindow = new Window(this);
  mainWindow->setKeyCallBack(&key_callback);
  // Initialise glew.  If there is an error, report it
  glewExperimental=GL_TRUE;
  GLenum res = glewInit();
  if (res != GLEW_OK)
  {
    DIE2("Could not start GLEW:", glewGetErrorString(res));
  }
  glDebugMessageCallbackARB((GLDEBUGPROCARB) glDebugMessageCallbackFunction, NULL);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
  glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

  initTextEngine();
  shaderManager = new ShaderManager();
  camera = new Camera(&shaderManager->frameData.cameraMatrix,&shaderManager->frameData.cameraPosition);
  camera->setPosition(glm::vec3(4000,100,4000));
  oldMousePos = mainWindow->getSize()/2.f;
}

/// Run the game
void Game::run()
{
  logi.log("Running game...");
  while ((!mainWindow->shouldClose()))
  {
    float ms = getFrameDiff();
    logFrame();
    float fps = getFrameRate();
    char buffer[80]; sprintf(buffer,"Project Magrathea III (%.2f FPS : %.0fms)",fps,ms*1000);
    mainWindow->setTitle(buffer);

    if (mouseCameraControl)
      camera->getInputFromWindow(mainWindow);
    if (keys['W'])
      camera->MoveForward(ms*50.f);
    if (keys['S'])
      camera->MoveForward(-ms*50.f);

    glfwPollEvents();
    mainWindow->setContext();
    renderMainWindow();
    mainWindow->swapBuffers();
  }
  glfwTerminate();
}

void Game::renderMainWindow()
{
  glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
  glClearColor(0.54,0.93,0.93,1.0);
  camera->Render();
  shaderManager->setFrameData();
  terrain->Render();
}

void Game::key(int key, int scancode, int action, int mods)
{
  if (action==GLFW_PRESS)
  {
    if (key=='Q')
    {
      mouseCameraControl = !mouseCameraControl;
      if (mouseCameraControl)
        mainWindow->setMouseCentre();
    }
    keys[key] = true;
  }
  if (action==GLFW_RELEASE)
    keys[key] = false;
}
<|endoftext|>


<commit_before>/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 "game.hpp"

#include <cmath> // For abs
#include <stdexcept>

#include "config.hpp"
#include "direction.hpp"
#include "i18n.hpp"
#ifdef __MINGW32__
#include "to_string_replacement.hpp"
#endif

Game::Game()
: window_{{800, 600}, "Pong v" PONG_VERSION},
  font_{},
  text_{{}, font_, 50},
  startMessage_{},
  paddle1_{10.f, getHeight() / 2.f - 50.f},
  paddle2_{getWidth() - 30.f, getHeight() / 2.f - 50.f},
  balls_{10, {getWidth() / 2.f, getHeight() / 2.f}},
  player1_cpu_{false},
  player2_cpu_{false}
{
  std::random_device rd;
  generator_ = std::make_shared<std::mt19937>(rd());

  for (Ball& ball : balls_) {
    ball.setGenerator(generator_);
    ball.setRandomDirection();
  }

  window_.setFramerateLimit(60);

  if (!font_.loadFromFile("font.ttf"))
    throw std::runtime_error{_("Failed to load font.")};

  const char* startMessageMb = _("Press SPACE to start");
  std::size_t len = std::mbstowcs(nullptr, startMessageMb, 0) + 1;
  std::vector<wchar_t> wstr(len);
  std::mbstowcs(wstr.data(), startMessageMb, wstr.size());
  startMessage_ = wstr.data();
}

void Game::run(bool singleplayer)
{
  if (singleplayer)
    player2_cpu_ = true;

  sf::Event event;

  while (window_.isOpen()) {

    while (window_.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window_.close();
      }
      else if (event.type == sf::Event::KeyPressed) {
        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window_.close();
            break;
          case sf::Keyboard::Space:
            for (Ball& ball : balls_)
              ball.start();
            break;
          default:
            break;
        }
      }
    }

    update();
    render();
  }
}

void Game::update()
{
  if (!player1_cpu_)
    updatePaddleControls(paddle1_, sf::Keyboard::W,  sf::Keyboard::S);
  else
    updatePaddleAuto(paddle1_);

  if (!player2_cpu_)
    updatePaddleControls(paddle2_, sf::Keyboard::Up, sf::Keyboard::Down);
  else
    updatePaddleAuto(paddle2_);

  for (Ball& ball : balls_) {
    ball.updatePosition();

    if (ball.getTop() < 0.f || ball.getBottom() > getHeight()) {
      ball.bounceY();
    }
    else if (paddle1_.getGlobalBounds().intersects(ball.getGlobalBounds())) {
      ball.setLeft(paddle1_.getRight());
      ball.bounceX();
    }
    else if (paddle2_.getGlobalBounds().intersects(ball.getGlobalBounds())) {
      ball.setRight(paddle2_.getLeft());
      ball.bounceX();
    }
    else if (ball.getRight() < 0.f) {
      paddle2_.addPoints(1);
      ball.setPosition(getWidth() / 2.f, getHeight() / 2.f);
      ball.setRandomDirection();
      ball.stop();
    }
    else if (ball.getLeft() > getWidth()) {
      paddle1_.addPoints(1);
      ball.setPosition(getWidth() / 2.f, getHeight() / 2.f);
      ball.setRandomDirection();
      ball.stop();
    }
  }
}

void Game::updatePaddleControls(Paddle& paddle,
                                sf::Keyboard::Key upKey,
                                sf::Keyboard::Key downKey)
{
  if (sf::Keyboard::isKeyPressed(upKey) && paddle.getTop() > 0.f) {
    paddle.move(Direction::Up);
  }

  if (sf::Keyboard::isKeyPressed(downKey) && paddle.getBottom() < getHeight()) {
    paddle.move(Direction::Down);
  }
}

/*
 * This is the CPU player logic.
 * The paddle will only move if it is a certain distance away from the ball.
 */
void Game::updatePaddleAuto(Paddle& paddle)
{
  for (Ball& ball : balls_) {
    if (std::abs(ball.getLeft() - paddle.getLeft()) < 200.f) {
      if (paddle.getTop() > ball.getBottom() && paddle.getTop() > 0.f) {
        paddle.move(Direction::Up, Paddle::slow_velocity);
      }
      else if (paddle.getBottom() < ball.getTop() &&
               paddle.getBottom() < getHeight()) {
        paddle.move(Direction::Down, Paddle::slow_velocity);
      }
    }
  }
}

void Game::render()
{
  window_.clear(sf::Color::Black);

  window_.draw(paddle1_);
  window_.draw(paddle2_);
  for (Ball& ball : balls_)
    window_.draw(ball);

  text_.setString(std::to_string(paddle1_.getPoints()));
  text_.setPosition(getWidth() * 0.25f - text_.getGlobalBounds().width, 10.f);
  window_.draw(text_);

  text_.setString(std::to_string(paddle2_.getPoints()));
  text_.setPosition(getWidth() * 0.75f, 10.f);
  window_.draw(text_);

  for (Ball& ball : balls_) {
    if (ball.isStopped()) {
      text_.setString(startMessage_);
      text_.setCharacterSize(15);
      text_.setPosition(10.f, getHeight() - 25.f);
      window_.draw(text_);
      text_.setCharacterSize(50);
    }
  }

  window_.display();
}

float Game::getWidth() const
{
  return window_.getSize().x;
}

float Game::getHeight() const
{
  return window_.getSize().y;
}
<commit_msg>Don't draw start text multiple times<commit_after>/* Copyright 2014-2015 Juhani Numminen
 *
 * 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 "game.hpp"

#include <cmath> // For abs
#include <stdexcept>

#include "config.hpp"
#include "direction.hpp"
#include "i18n.hpp"
#ifdef __MINGW32__
#include "to_string_replacement.hpp"
#endif

Game::Game()
: window_{{800, 600}, "Pong v" PONG_VERSION},
  font_{},
  text_{{}, font_, 50},
  startMessage_{},
  paddle1_{10.f, getHeight() / 2.f - 50.f},
  paddle2_{getWidth() - 30.f, getHeight() / 2.f - 50.f},
  balls_{10, {getWidth() / 2.f, getHeight() / 2.f}},
  player1_cpu_{false},
  player2_cpu_{false}
{
  std::random_device rd;
  generator_ = std::make_shared<std::mt19937>(rd());

  for (Ball& ball : balls_) {
    ball.setGenerator(generator_);
    ball.setRandomDirection();
  }

  window_.setFramerateLimit(60);

  if (!font_.loadFromFile("font.ttf"))
    throw std::runtime_error{_("Failed to load font.")};

  const char* startMessageMb = _("Press SPACE to start");
  std::size_t len = std::mbstowcs(nullptr, startMessageMb, 0) + 1;
  std::vector<wchar_t> wstr(len);
  std::mbstowcs(wstr.data(), startMessageMb, wstr.size());
  startMessage_ = wstr.data();
}

void Game::run(bool singleplayer)
{
  if (singleplayer)
    player2_cpu_ = true;

  sf::Event event;

  while (window_.isOpen()) {

    while (window_.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window_.close();
      }
      else if (event.type == sf::Event::KeyPressed) {
        switch (event.key.code) {
          case sf::Keyboard::Escape:
            window_.close();
            break;
          case sf::Keyboard::Space:
            for (Ball& ball : balls_)
              ball.start();
            break;
          default:
            break;
        }
      }
    }

    update();
    render();
  }
}

void Game::update()
{
  if (!player1_cpu_)
    updatePaddleControls(paddle1_, sf::Keyboard::W,  sf::Keyboard::S);
  else
    updatePaddleAuto(paddle1_);

  if (!player2_cpu_)
    updatePaddleControls(paddle2_, sf::Keyboard::Up, sf::Keyboard::Down);
  else
    updatePaddleAuto(paddle2_);

  for (Ball& ball : balls_) {
    ball.updatePosition();

    if (ball.getTop() < 0.f || ball.getBottom() > getHeight()) {
      ball.bounceY();
    }
    else if (paddle1_.getGlobalBounds().intersects(ball.getGlobalBounds())) {
      ball.setLeft(paddle1_.getRight());
      ball.bounceX();
    }
    else if (paddle2_.getGlobalBounds().intersects(ball.getGlobalBounds())) {
      ball.setRight(paddle2_.getLeft());
      ball.bounceX();
    }
    else if (ball.getRight() < 0.f) {
      paddle2_.addPoints(1);
      ball.setPosition(getWidth() / 2.f, getHeight() / 2.f);
      ball.setRandomDirection();
      ball.stop();
    }
    else if (ball.getLeft() > getWidth()) {
      paddle1_.addPoints(1);
      ball.setPosition(getWidth() / 2.f, getHeight() / 2.f);
      ball.setRandomDirection();
      ball.stop();
    }
  }
}

void Game::updatePaddleControls(Paddle& paddle,
                                sf::Keyboard::Key upKey,
                                sf::Keyboard::Key downKey)
{
  if (sf::Keyboard::isKeyPressed(upKey) && paddle.getTop() > 0.f) {
    paddle.move(Direction::Up);
  }

  if (sf::Keyboard::isKeyPressed(downKey) && paddle.getBottom() < getHeight()) {
    paddle.move(Direction::Down);
  }
}

/*
 * This is the CPU player logic.
 * The paddle will only move if it is a certain distance away from the ball.
 */
void Game::updatePaddleAuto(Paddle& paddle)
{
  for (Ball& ball : balls_) {
    if (std::abs(ball.getLeft() - paddle.getLeft()) < 200.f) {
      if (paddle.getTop() > ball.getBottom() && paddle.getTop() > 0.f) {
        paddle.move(Direction::Up, Paddle::slow_velocity);
      }
      else if (paddle.getBottom() < ball.getTop() &&
               paddle.getBottom() < getHeight()) {
        paddle.move(Direction::Down, Paddle::slow_velocity);
      }
    }
  }
}

void Game::render()
{
  window_.clear(sf::Color::Black);

  window_.draw(paddle1_);
  window_.draw(paddle2_);
  for (Ball& ball : balls_)
    window_.draw(ball);

  text_.setString(std::to_string(paddle1_.getPoints()));
  text_.setPosition(getWidth() * 0.25f - text_.getGlobalBounds().width, 10.f);
  window_.draw(text_);

  text_.setString(std::to_string(paddle2_.getPoints()));
  text_.setPosition(getWidth() * 0.75f, 10.f);
  window_.draw(text_);

  for (Ball& ball : balls_) {
    if (ball.isStopped()) {
      text_.setString(startMessage_);
      text_.setCharacterSize(15);
      text_.setPosition(10.f, getHeight() - 25.f);
      window_.draw(text_);
      text_.setCharacterSize(50);
      break;
    }
  }

  window_.display();
}

float Game::getWidth() const
{
  return window_.getSize().x;
}

float Game::getHeight() const
{
  return window_.getSize().y;
}
<|endoftext|>


<commit_before>#include "config.h"

#include "system_configuration.hpp"

#include "network_manager.hpp"
#include "routing_table.hpp"

#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/Common/error.hpp>

namespace phosphor
{
namespace network
{

// systemd service to kick start a target.
constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1";
constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1";
constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1";
constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties";
constexpr auto METHOD_GET = "Get";
constexpr auto METHOD_SET = "SetStaticHostname";

using namespace phosphor::logging;
using namespace sdbusplus::xyz::openbmc_project::Common::Error;
using InvalidArgumentMetadata = xyz::openbmc_project::Common::InvalidArgument;

using SystemConfigIntf =
    sdbusplus::xyz::openbmc_project::Network::server::SystemConfiguration;

SystemConfiguration::SystemConfiguration(sdbusplus::bus::bus& bus,
                                         const std::string& objPath,
                                         Manager& parent) :
    Iface(bus, objPath.c_str(), true),
    bus(bus), manager(parent)
{
    auto name = getHostNameFromSystem();
    route::Table routingTable;

    SystemConfigIntf::hostName(name);
    SystemConfigIntf::defaultGateway(routingTable.getDefaultGateway());
    SystemConfigIntf::defaultGateway6(routingTable.getDefaultGateway6());

    this->emit_object_added();
}

std::string SystemConfiguration::hostName(std::string name)
{
    if (SystemConfigIntf::hostName() == name)
    {
        return name;
    }
    auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
                                      HOSTNAMED_INTERFACE, METHOD_SET);

    method.append(name, true);

    if (!bus.call(method))
    {
        log<level::ERR>("Failed to set the hostname");
        report<InternalFailure>();
        return SystemConfigIntf::hostName();
    }

    return SystemConfigIntf::hostName(name);
}

std::string SystemConfiguration::getHostNameFromSystem() const
{
    sdbusplus::message::variant<std::string> name;
    auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
                                      PROPERTY_INTERFACE, METHOD_GET);

    method.append(HOSTNAMED_INTERFACE, "Hostname");

    auto reply = bus.call(method);

    if (reply)
    {
        reply.read(name);
    }
    else
    {
        log<level::ERR>("Failed to get hostname");
        report<InternalFailure>();
        return "";
    }
    return std::get<std::string>(name);
}

std::string SystemConfiguration::defaultGateway(std::string gateway)
{
    auto gw = SystemConfigIntf::defaultGateway();
    if (gw == gateway)
    {
        return gw;
    }

    if (!isValidIP(AF_INET, gateway))
    {
        log<level::ERR>("Not a valid v4 Gateway",
                        entry("GATEWAY=%s", gateway.c_str()));
        elog<InvalidArgument>(
            InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"),
            InvalidArgumentMetadata::ARGUMENT_VALUE(gateway.c_str()));
    }
    gw = SystemConfigIntf::defaultGateway(gateway);
    manager.writeToConfigurationFile();
    return gw;
}

std::string SystemConfiguration::defaultGateway6(std::string gateway)
{
    auto gw = SystemConfigIntf::defaultGateway6();
    if (gw == gateway)
    {
        return gw;
    }

    if (!isValidIP(AF_INET6, gateway))
    {
        log<level::ERR>("Not a valid v6 Gateway",
                        entry("GATEWAY=%s", gateway.c_str()));
        elog<InvalidArgument>(
            InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"),
            InvalidArgumentMetadata::ARGUMENT_VALUE(gateway.c_str()));
    }
    gw = SystemConfigIntf::defaultGateway6(gateway);
    manager.writeToConfigurationFile();
    return gw;
}

} // namespace network
} // namespace phosphor
<commit_msg>sdbusplus: replace message::variant with std::variant<commit_after>#include "config.h"

#include "system_configuration.hpp"

#include "network_manager.hpp"
#include "routing_table.hpp"

#include <phosphor-logging/elog-errors.hpp>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/Common/error.hpp>

namespace phosphor
{
namespace network
{

// systemd service to kick start a target.
constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1";
constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1";
constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1";
constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties";
constexpr auto METHOD_GET = "Get";
constexpr auto METHOD_SET = "SetStaticHostname";

using namespace phosphor::logging;
using namespace sdbusplus::xyz::openbmc_project::Common::Error;
using InvalidArgumentMetadata = xyz::openbmc_project::Common::InvalidArgument;

using SystemConfigIntf =
    sdbusplus::xyz::openbmc_project::Network::server::SystemConfiguration;

SystemConfiguration::SystemConfiguration(sdbusplus::bus::bus& bus,
                                         const std::string& objPath,
                                         Manager& parent) :
    Iface(bus, objPath.c_str(), true),
    bus(bus), manager(parent)
{
    auto name = getHostNameFromSystem();
    route::Table routingTable;

    SystemConfigIntf::hostName(name);
    SystemConfigIntf::defaultGateway(routingTable.getDefaultGateway());
    SystemConfigIntf::defaultGateway6(routingTable.getDefaultGateway6());

    this->emit_object_added();
}

std::string SystemConfiguration::hostName(std::string name)
{
    if (SystemConfigIntf::hostName() == name)
    {
        return name;
    }
    auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
                                      HOSTNAMED_INTERFACE, METHOD_SET);

    method.append(name, true);

    if (!bus.call(method))
    {
        log<level::ERR>("Failed to set the hostname");
        report<InternalFailure>();
        return SystemConfigIntf::hostName();
    }

    return SystemConfigIntf::hostName(name);
}

std::string SystemConfiguration::getHostNameFromSystem() const
{
    std::variant<std::string> name;
    auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH,
                                      PROPERTY_INTERFACE, METHOD_GET);

    method.append(HOSTNAMED_INTERFACE, "Hostname");

    auto reply = bus.call(method);

    if (reply)
    {
        reply.read(name);
    }
    else
    {
        log<level::ERR>("Failed to get hostname");
        report<InternalFailure>();
        return "";
    }
    return std::get<std::string>(name);
}

std::string SystemConfiguration::defaultGateway(std::string gateway)
{
    auto gw = SystemConfigIntf::defaultGateway();
    if (gw == gateway)
    {
        return gw;
    }

    if (!isValidIP(AF_INET, gateway))
    {
        log<level::ERR>("Not a valid v4 Gateway",
                        entry("GATEWAY=%s", gateway.c_str()));
        elog<InvalidArgument>(
            InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"),
            InvalidArgumentMetadata::ARGUMENT_VALUE(gateway.c_str()));
    }
    gw = SystemConfigIntf::defaultGateway(gateway);
    manager.writeToConfigurationFile();
    return gw;
}

std::string SystemConfiguration::defaultGateway6(std::string gateway)
{
    auto gw = SystemConfigIntf::defaultGateway6();
    if (gw == gateway)
    {
        return gw;
    }

    if (!isValidIP(AF_INET6, gateway))
    {
        log<level::ERR>("Not a valid v6 Gateway",
                        entry("GATEWAY=%s", gateway.c_str()));
        elog<InvalidArgument>(
            InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"),
            InvalidArgumentMetadata::ARGUMENT_VALUE(gateway.c_str()));
    }
    gw = SystemConfigIntf::defaultGateway6(gateway);
    manager.writeToConfigurationFile();
    return gw;
}

} // namespace network
} // namespace phosphor
<|endoftext|>