<commit_before>#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>

int g_world_size;
int g_mpi_rank;
int start_id;
int end_id;
int g_max_id = 125000000;
int count = 0;
MPI_Offset file_start;
MPI_Offset file_end;
std::map<int, std::vector<int>> g_adj_list;

void parse_file_one_rank();
void parse_file();
int add_to_adjlist(std::string line);
int id_to_rank(int id);
MPI_Offset compute_offset(MPI_File infile, MPI_Offset filesize);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  MPI_Init(&argc, &argv);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_mpi_rank);

  start_id = g_mpi_rank*(g_max_id / g_world_size);
  end_id = (g_mpi_rank+1)*(g_max_id / g_world_size);
  if (g_mpi_rank == g_world_size-1){
    end_id = g_max_id;
  }

  printf("Rank %d: start_id: %d end_id: %d\n", g_mpi_rank, start_id, end_id);

  // Print off a hello world message
  parse_file();
  // if(g_mpi_rank==0){
  //   parse_file_one_rank();
  // }

  MPI_Barrier(MPI_COMM_WORLD);
  printf("Rank: %d    g_adj_list.size(): %lu    elements in list: %d\n", g_mpi_rank, g_adj_list.size(), count);
  //if (g_mpi_rank == 0){
   // parse_file();
    //printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  // }

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

//only use this once to optimize file parsing
void parse_file_one_rank(){
  std::string line;
  int count = 0;
  std::ifstream infile("com-friendster.ungraph.txt");
  for(int i =0; i<4; i++){
    std::getline(infile, line);
  }
  std::vector<std::ofstream*> streams;
  for(int i=0;i<125;i++) {
    std::stringstream sstm;
    sstm<<"./Friendster/users_"<<i<<".txt";
    std::string fileName = sstm.str();
    streams.push_back(new std::ofstream(fileName.c_str(), std::ofstream::out));
  }
  while(std::getline(infile,line)){
    count++;
    int tab_pos = line.find("\t");
    int one = atoi(line.substr(0, tab_pos).c_str());
    int two = atoi(line.substr(tab_pos+1).c_str());
    int oneFile = floor((double)one/1000000);
    int twoFile = floor((double)two/1000000);
    std::stringstream sstm;
    sstm<<one<<"\t"<<two<<"\n";
    std::string lineOne = sstm.str();
    sstm.str(std::string());
    sstm.clear();
    sstm<<two<<"\t"<<one<<"\n";
    std::string lineTwo = sstm.str();

    *streams[oneFile]<<lineOne;
    *streams[twoFile]<<lineTwo;
    if(count%500000==0){
      double percent = one/(double)g_max_id*100;
      std::cout<<percent<<"%"<<std::endl;
    }
  }
}

MPI_Offset compute_offset(MPI_File infile, MPI_Offset filesize){
  MPI_Offset offset = 0;
  int num_sections = 16;
  for (int i=1; i<num_sections; i++){
    // set the temp offset
    int tmp_offset = (filesize / num_sections) * i;

    // allocate some space to read in at the offset
    char * buffer = (char *)malloc( (1001)*sizeof(char));
    // read in there
    MPI_File_read_at(infile, tmp_offset, buffer, 1000, MPI_CHAR, MPI_STATUS_IGNORE);
    buffer[1000] = '\0';
    // cast as a string
    std::string chunk(buffer);
    free(buffer);

    // read up to the first newline and throw that away
    chunk = chunk.substr(chunk.find('\n'));
    // get everything from there to the next newline
    std::string line = chunk.substr(0, chunk.find('\n'));

    // split it up over the tab and pull out the first id
    int tab_pos = line.find("\t");
    int first_id = atoi(line.substr(0, tab_pos).c_str());
    // if this id is greater than the starting id, the offset is too big, go to the last one
    if (first_id > start_id){
      offset = (filesize / num_sections) * (i-1);
      break;
    }
  }
  return offset;
}

void parse_file(){
  int lowFile = floor((double)start_id/1000000);
  int highFile = floor((double)end_id/1000000);
  // loop through all of the files that will hold information about our set of ids
  for (int i=0; i<highFile-lowFile+1; i++){
    // create the filename as a c_str
    char filename[100];
    sprintf(filename, "/gpfs/u/home/PCP5/PCP5bhgw/scratch/users_%d.txt", lowFile);

    // open the file and get the filesize
    MPI_File infile;
    MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
    MPI_Offset filesize = 0;
    MPI_File_get_size(infile, &filesize);

    // start the offset at 0, for now
    MPI_Offset offset = compute_offset(infile, filesize);
    char * buffer;
    std::string chunk = "";
    // set the buffer size, ie. how much to read in at a time
    unsigned int buffer_size = 10000;

    // keep track of the latest id that we read in so that we can stop reading if we've found the last id that we need
    int latest_id_found = 0;

    // loop while we haven't read the whole file and we haven't found the latest id yet
    while (offset < fliesize && latest_id_found < end_id){
      // printf("Rank: %d offset: %lld, file_end: %lld, remaining: %lld  size of adj_list: %lu\n", g_mpi_rank, offset, file_end, file_end-offset, g_adj_list.size());
      // read in a chukn to the buffer
      buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
      MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
      offset += buffer_size;
      // end the string
      buffer[buffer_size] = '\0';
      // make the c_string a std::string for convenience
      std::string new_string(buffer);
      free(buffer);
      // add the new string to the existing one
      chunk += new_string;

      /*if (skip){
        // skip up to the first newline to remove any broken lines from starting in the middle of the file
        chunk = chunk.substr(chunk.find('\n')+1);
      }else{
        skip = true;
      }*/

      // find the first newline in the file
      int found_nl = chunk.find('\n');
      // loop while there are still newlines and we havne't found the last id yet
      while (found_nl < chunk.size() && latest_id_found < end_id){
        // get the part of the string before the newline
        std::string line = chunk.substr(0, found_nl);
        // parse that part of it
        latest_id_found = add_to_adjlist(line);

        // reset the string so it is past that first part
        chunk = chunk.substr(found_nl+1);
        // search for another newline
        found_nl = chunk.find('\n');
      }
   }
   // go to the next file
   lowFile++;
  }
  printf("Rank %d: finished read in of own portion of file    %lu\n", g_mpi_rank, g_adj_list.size());
    //sprintf(filename, "com-friendster.ungraph.txt");
}

int id_to_rank(int id){
  int max_id=0;
  for (int i=0; i<g_world_size; i++){
    max_id += g_max_id / g_world_size;
    if (id < max_id){
      return i;
    }
  }
  return g_world_size-1;
}

int add_to_adjlist(std::string line){
  int tab_pos = line.find("\t");
  int one = atoi(line.substr(0, tab_pos).c_str());
  int two = atoi(line.substr(tab_pos+1).c_str());
  //std::cout<<start_id<<" "<<end_id<<std::endl;
  if (one >= start_id && one < end_id){
    g_adj_list[one].push_back(two);
    count++;
    if(count%1000000==0){
      std::cout<<g_mpi_rank<<" "<<count<<std::endl;
    }
  }
  return one;
}
<commit_msg>fixed the offset stuff<commit_after>#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>

int g_world_size;
int g_mpi_rank;
int start_id;
int end_id;
int g_max_id = 125000000;
int count = 0;
MPI_Offset file_start;
MPI_Offset file_end;
std::map<int, std::vector<int>> g_adj_list;

void parse_file_one_rank();
void parse_file();
int add_to_adjlist(std::string line);
int id_to_rank(int id);
MPI_Offset compute_offset(char * filename);

int main(int argc, char** argv) {
  // Initialize the MPI environment
  int test;
  MPI_Init(&argc, &argv);

  // Get the number of processes
  MPI_Comm_size(MPI_COMM_WORLD, &g_world_size);

  // Get the rank of the process
  MPI_Comm_rank(MPI_COMM_WORLD, &g_mpi_rank);

  start_id = g_mpi_rank*(g_max_id / g_world_size);
  end_id = (g_mpi_rank+1)*(g_max_id / g_world_size);
  if (g_mpi_rank == g_world_size-1){
    end_id = g_max_id;
  }

  printf("Rank %d: start_id: %d end_id: %d\n", g_mpi_rank, start_id, end_id);

  // Print off a hello world message
  parse_file();
  // if(g_mpi_rank==0){
  //   parse_file_one_rank();
  // }

  MPI_Barrier(MPI_COMM_WORLD);
  printf("Rank: %d    g_adj_list.size(): %lu    elements in list: %d\n", g_mpi_rank, g_adj_list.size(), count);
  //if (g_mpi_rank == 0){
   // parse_file();
    //printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  // }

  // Finalize the MPI environment.
  MPI_Finalize();

  return 0;
}

//only use this once to optimize file parsing
void parse_file_one_rank(){
  std::string line;
  int count = 0;
  std::ifstream infile("com-friendster.ungraph.txt");
  for(int i =0; i<4; i++){
    std::getline(infile, line);
  }
  std::vector<std::ofstream*> streams;
  for(int i=0;i<125;i++) {
    std::stringstream sstm;
    sstm<<"./Friendster/users_"<<i<<".txt";
    std::string fileName = sstm.str();
    streams.push_back(new std::ofstream(fileName.c_str(), std::ofstream::out));
  }
  while(std::getline(infile,line)){
    count++;
    int tab_pos = line.find("\t");
    int one = atoi(line.substr(0, tab_pos).c_str());
    int two = atoi(line.substr(tab_pos+1).c_str());
    int oneFile = floor((double)one/1000000);
    int twoFile = floor((double)two/1000000);
    std::stringstream sstm;
    sstm<<one<<"\t"<<two<<"\n";
    std::string lineOne = sstm.str();
    sstm.str(std::string());
    sstm.clear();
    sstm<<two<<"\t"<<one<<"\n";
    std::string lineTwo = sstm.str();

    *streams[oneFile]<<lineOne;
    *streams[twoFile]<<lineTwo;
    if(count%500000==0){
      double percent = one/(double)g_max_id*100;
      std::cout<<percent<<"%"<<std::endl;
    }
  }
}

MPI_Offset compute_offset(char * filename){
  MPI_File infile;
  MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
  MPI_Offset filesize = 0;
  MPI_File_get_size(infile, &filesize);

  MPI_Offset offset = 0;
  int num_sections = 100;
  for (int i=1; i<num_sections; i++){
    // set the temp offset
    int tmp_offset = (filesize / num_sections) * i;

    // allocate some space to read in at the offset
    char * buffer = (char *)malloc( (1001)*sizeof(char));
    // read in there
    MPI_File_read_at(infile, tmp_offset, buffer, 1000, MPI_CHAR, MPI_STATUS_IGNORE);
    buffer[1000] = '\0';
    // cast as a string
    std::string chunk(buffer);
    free(buffer);
    //std::cout << chunk << std::endl;

    // read up to the first newline and throw that away
    chunk = chunk.substr(chunk.find('\n')+1);
    // get everything from there to the next newline
    std::string line = chunk.substr(0, chunk.find('\n'));

    // split it up over the tab and pull out the first id
    int tab_pos = line.find("\t");
    int first_id = atoi(line.substr(0, tab_pos).c_str());
    // if this id is greater than the starting id, the offset is too big, go to the last one
    if (first_id > start_id){
      offset = (filesize / num_sections) * (i-1);
      break;
    }
  }
  return offset;
}

void parse_file(){
  int lowFile = floor((double)start_id/1000000);
  int highFile = floor((double)end_id/1000000);
  // loop through all of the files that will hold information about our set of ids
  for (int i=0; i<highFile-lowFile+1; i++){
    // create the filename as a c_str
    char filename[100];
    sprintf(filename, "/gpfs/u/home/PCP5/PCP5stns/scratch/users_%d.txt", lowFile);

    // open the file and get the filesize
    MPI_File infile;
    MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
    MPI_Offset filesize = 0;
    MPI_File_get_size(infile, &filesize);

    //printf("%s: %lu", filename, filesize);

    // start the offset at 0, for now
    MPI_Offset offset = compute_offset(filename);
    char * buffer;
    std::string chunk = "";
    // set the buffer size, ie. how much to read in at a time
    unsigned int buffer_size = 10000;

    // keep track of the latest id that we read in so that we can stop reading if we've found the last id that we need
    int latest_id_found = 0;

    // loop while we haven't read the whole file and we haven't found the latest id yet
    while (offset < filesize && latest_id_found < end_id){
      // printf("Rank: %d offset: %lld, file_end: %lld, remaining: %lld  size of adj_list: %lu\n", g_mpi_rank, offset, file_end, file_end-offset, g_adj_list.size());
      // read in a chukn to the buffer
      buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
      MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
      offset += buffer_size;
      // end the string
      buffer[buffer_size] = '\0';
      // make the c_string a std::string for convenience
      std::string new_string(buffer);
      free(buffer);
      // add the new string to the existing one
      chunk += new_string;

      /*if (skip){
        // skip up to the first newline to remove any broken lines from starting in the middle of the file
        chunk = chunk.substr(chunk.find('\n')+1);
      }else{
        skip = true;
      }*/

      // find the first newline in the file
      int found_nl = chunk.find('\n');
      // loop while there are still newlines and we havne't found the last id yet
      while (found_nl < chunk.size() && latest_id_found < end_id){
        // get the part of the string before the newline
        std::string line = chunk.substr(0, found_nl);
        // parse that part of it
        latest_id_found = add_to_adjlist(line);

        // reset the string so it is past that first part
        chunk = chunk.substr(found_nl+1);
        // search for another newline
        found_nl = chunk.find('\n');
      }
   }
   // go to the next file
   lowFile++;
  }
  printf("Rank %d: finished read in of own portion of file    %lu\n", g_mpi_rank, g_adj_list.size());
    //sprintf(filename, "com-friendster.ungraph.txt");
}

int id_to_rank(int id){
  int max_id=0;
  for (int i=0; i<g_world_size; i++){
    max_id += g_max_id / g_world_size;
    if (id < max_id){
      return i;
    }
  }
  return g_world_size-1;
}

int add_to_adjlist(std::string line){
  int tab_pos = line.find("\t");
  int one = atoi(line.substr(0, tab_pos).c_str());
  int two = atoi(line.substr(tab_pos+1).c_str());
  //std::cout<<start_id<<" "<<end_id<<std::endl;
  if (one >= start_id && one < end_id){
    g_adj_list[one].push_back(two);
    count++;
    if(count%1000000==0){
      std::cout<<g_mpi_rank<<" "<<count<<std::endl;
    }
  }
  return one;
}
<|endoftext|>


<commit_before>#define RAPIDJSON_HAS_STDSTRING 1
#define RAPIDJSON_PARSE_DEFAULT_FLAGS (kParseTrailingCommasFlag|kParseStopWhenDoneFlag|kParseCommentsFlag)

#include <ctime>

#include <rapidjson/filereadstream.h>
#include <rapidjson/filewritestream.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/getter.h>

#include "Renju.hpp"

rapidjson::Pointer pointer_type("/head/type");
rapidjson::Pointer pointer_white_name("/body/player_white/name");
rapidjson::Pointer pointer_black_name("/body/player_black/name");
rapidjson::Pointer pointer_steps("/body/steps");
rapidjson::Pointer pointer_size("/body/size");
rapidjson::Pointer pointer_forbin("/body/has_hand_cut");
rapidjson::Pointer pointer_side("/side");
rapidjson::Pointer pointer_x("/x");
rapidjson::Pointer pointer_y("/y");
rapidjson::Pointer pointer_result("/head/result");
rapidjson::Pointer pointer_msg("/head/msg");

void SetName(rapidjson::Document &json)
{
    auto white = pointer_white_name.Get(json);
    if (white != nullptr)
    {
        white->SetString("okhowang_white");
        return;
    }

    auto black = pointer_black_name.Get(json);
    if (black != nullptr)
    {
        black->SetString("okhowang_black");
        return;
    }
    throw "bad get name";
}

void Process(rapidjson::Document &json)
{
    int size = rapidjson::GetIntByPointer(json, pointer_size);
    int forbid = rapidjson::GetIntByPointer(json, pointer_forbin);
    rapidjson::Value v;
    auto steps = pointer_steps.Get(json);
    if (steps == nullptr || !steps->IsArray())
    {
        v.SetArray();
        steps = &v;
    }
    Renju renju(size, forbid);
    Renju::Role cur_role = Renju::Role::kWhite;
    for (auto &step : steps->GetArray())
    {
        int x = rapidjson::GetIntByPointer(step, pointer_x) - 1;
        int y = rapidjson::GetIntByPointer(step, pointer_y) - 1;
        auto v_side = pointer_side.Get(step);
        if (v_side == nullptr || !v_side->IsString() || v_side->GetStringLength() == 0)
        {
            throw "bad side";
        }
        if (v_side->GetString()[0] == 'w')
        {
            renju.SetPos(x, y, Renju::Pos::kWhite, false);
            cur_role = Renju::Role::kWhite;
        }
        else
        {

            renju.SetPos(x, y, Renju::Pos::kBlack, false);
            cur_role = Renju::Role::kBlack;
        }
    }
    renju.Init();
    if (cur_role == Renju::Role::kWhite)
        cur_role = Renju::Role::kBlack;
    else cur_role = Renju::Role::kWhite;

    auto pos = renju.GetNext(cur_role, 2);
    rapidjson::Value step;
    step.SetObject();
	if (cur_role == Renju::Role::kBlack)
		step.AddMember("side", "b", json.GetAllocator());
	else step.AddMember("side", "w", json.GetAllocator());

    step.AddMember("x", std::to_string(pos.first + 1), json.GetAllocator());
    step.AddMember("y", std::to_string(pos.second + 1), json.GetAllocator());
    time_t t;
    time(&t);
    tm *tm = localtime(&t);
    char timebuf[128];
    strftime(timebuf, sizeof (timebuf), "%Y%m%d%H%M%S", tm);
    step.AddMember("time", rapidjson::Value(timebuf, json.GetAllocator()).Move(), json.GetAllocator());
    steps->PushBack(step.Move(), json.GetAllocator());
    pointer_steps.Set(json, *steps, json.GetAllocator());
}

int main(int argc, char** argv)
{
    printf("Content-Type: text/json\r\n\r\n");
    char buffer[65535];
    rapidjson::Document json;
    if (getenv("QUERY_STRING"))
    {
        rapidjson::FileReadStream input(stdin, buffer, sizeof (buffer));
        json.ParseStream(input);
    }
    else
        json.Parse(R"(
{"head":{"type":1,"result":0,"err_msg":"sucess"},"body":{"player_white":{"type":"Human","name":"123","url":"123","side":"w","team":"Human"},"player_black":{"type":"\u54d4\u4e86\u72d7","name":"okhowang_black","url":"http:\/\/133.130.100.186:81\/cgi-bin\/renju","side":"b","team":"\u54d4\u4e86\u72d7"},"start_time":"20161028_225545","size":15,"steps":null,"id":"d0535a68aff1cf36f67bcfcfb691c470","has_hand_cut":1,"invalid":null,"winner":null,"reason":null,"timeout":10}}
)");
    if (json.HasParseError())
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, "json parse error");
        return 0;
    }
    try
    {
        int type = rapidjson::GetIntByPointer(json, pointer_type);
        switch (type)
        {
        case 0:
            SetName(json);
            break;
        case 1:
            Process(json);
            break;
        }
    }
    catch (const rapidjson::ValueError &e)
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, e.what());
    }
    catch (const char *e)
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, e);
    }
    rapidjson::FileWriteStream output(stdout, buffer, sizeof (buffer));
    rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(output);
    json.Accept(writer);
    return 0;
}

<commit_msg>修复steps问题<commit_after>#define RAPIDJSON_HAS_STDSTRING 1
#define RAPIDJSON_PARSE_DEFAULT_FLAGS (kParseTrailingCommasFlag|kParseStopWhenDoneFlag|kParseCommentsFlag)

#include <ctime>

#include <rapidjson/filereadstream.h>
#include <rapidjson/filewritestream.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/writer.h>
#include <rapidjson/getter.h>

#include "Renju.hpp"

rapidjson::Pointer pointer_type("/head/type");
rapidjson::Pointer pointer_white_name("/body/player_white/name");
rapidjson::Pointer pointer_black_name("/body/player_black/name");
rapidjson::Pointer pointer_steps("/body/steps");
rapidjson::Pointer pointer_size("/body/size");
rapidjson::Pointer pointer_forbin("/body/has_hand_cut");
rapidjson::Pointer pointer_side("/side");
rapidjson::Pointer pointer_x("/x");
rapidjson::Pointer pointer_y("/y");
rapidjson::Pointer pointer_result("/head/result");
rapidjson::Pointer pointer_msg("/head/msg");

void SetName(rapidjson::Document &json)
{
    auto white = pointer_white_name.Get(json);
    if (white != nullptr)
    {
        white->SetString("okhowang_white");
        return;
    }

    auto black = pointer_black_name.Get(json);
    if (black != nullptr)
    {
        black->SetString("okhowang_black");
        return;
    }
    throw "bad get name";
}

void Process(rapidjson::Document &json)
{
    int size = rapidjson::GetIntByPointer(json, pointer_size);
    int forbid = rapidjson::GetIntByPointer(json, pointer_forbin);
    auto steps = pointer_steps.Get(json);
    if (steps == nullptr || !steps->IsArray())
    {
        pointer_steps.Set(json, 1);
        steps = pointer_steps.Get(json);
        steps->SetArray();
    }
    Renju renju(size, forbid);
    Renju::Role cur_role = Renju::Role::kWhite;
    for (auto &step : steps->GetArray())
    {
        int x = rapidjson::GetIntByPointer(step, pointer_x) - 1;
        int y = rapidjson::GetIntByPointer(step, pointer_y) - 1;
        auto v_side = pointer_side.Get(step);
        if (v_side == nullptr || !v_side->IsString() || v_side->GetStringLength() == 0)
        {
            throw "bad side";
        }
        if (v_side->GetString()[0] == 'w')
        {
            renju.SetPos(x, y, Renju::Pos::kWhite, false);
            cur_role = Renju::Role::kWhite;
        }
        else
        {

            renju.SetPos(x, y, Renju::Pos::kBlack, false);
            cur_role = Renju::Role::kBlack;
        }
    }
    renju.Init();
    if (cur_role == Renju::Role::kWhite)
        cur_role = Renju::Role::kBlack;
    else cur_role = Renju::Role::kWhite;

    auto pos = renju.GetNext(cur_role, 2);
    rapidjson::Value step;
    step.SetObject();
	if (cur_role == Renju::Role::kBlack)
		step.AddMember("side", "b", json.GetAllocator());
	else step.AddMember("side", "w", json.GetAllocator());

    step.AddMember("x", std::to_string(pos.first + 1), json.GetAllocator());
    step.AddMember("y", std::to_string(pos.second + 1), json.GetAllocator());
    time_t t;
    time(&t);
    tm *tm = localtime(&t);
    char timebuf[128];
    strftime(timebuf, sizeof (timebuf), "%Y%m%d%H%M%S", tm);
    step.AddMember("time", rapidjson::Value(timebuf, json.GetAllocator()).Move(), json.GetAllocator());
    steps->PushBack(step.Move(), json.GetAllocator());
}

int main(int argc, char** argv)
{
    printf("Content-Type: text/json\r\n\r\n");
    char buffer[65535];
    rapidjson::Document json;
    if (getenv("QUERY_STRING"))
    {
        rapidjson::FileReadStream input(stdin, buffer, sizeof (buffer));
        json.ParseStream(input);
    }
    else
        json.Parse(R"(
// {"head":{"type":1,"result":0,"err_msg":"sucess"},"body":{"player_white":{"type":"Human","name":"rt","url":"rt","side":"w","team":"Human"},"player_black":{"type":"\u54d4\u4e86\u72d7","name":"okhowang_black","url":"http:\/\/133.130.100.186:81\/cgi-bin\/renju","side":"b","team":"\u54d4\u4e86\u72d7"},"start_time":"20161028_231503","size":15,"steps":[{"side":"b","x":8,"y":8,"time":"20160729071005","seq":0},{"side":"w","x":8,"y":7,"time":"20160729071007","seq":1}],"id":"8cb29cfae3e6e5bcb05a9110c45f2399","has_hand_cut":1,"invalid":null,"winner":null,"reason":null,"timeout":10}}
{"head":{"type":1,"result":0,"err_msg":"sucess"},"body":{"player_white":{"type":"Human","name":"rt","url":"rt","side":"w","team":"Human"},"player_black":{"type":"\u54d4\u4e86\u72d7","name":"okhowang_black","url":"http:\/\/133.130.100.186:81\/cgi-bin\/renju","side":"b","team":"\u54d4\u4e86\u72d7"},"start_time":"20161028_231503","size":15,"steps":null,"id":"8cb29cfae3e6e5bcb05a9110c45f2399","has_hand_cut":1,"invalid":null,"winner":null,"reason":null,"timeout":10}}
)");
    if (json.HasParseError())
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, "json parse error");
        return 0;
    }
    try
    {
        int type = rapidjson::GetIntByPointer(json, pointer_type);
        switch (type)
        {
        case 0:
            SetName(json);
            break;
        case 1:
            Process(json);
            break;
        }
    }
    catch (const rapidjson::ValueError &e)
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, e.what());
    }
    catch (const char *e)
    {
        pointer_result.Set(json, 1);
        pointer_msg.Set(json, e);
    }
    rapidjson::FileWriteStream output(stdout, buffer, sizeof (buffer));
    rapidjson::Writer<rapidjson::FileWriteStream> writer(output);
    json.Accept(writer);
    return 0;
}

<|endoftext|>


<commit_before>/*
 *  Copyright 2011 Wolfgang Koller - http://www.gofg.at/
 *
 *  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 <QApplication>

#include "src/cordova.h"

#if QT_VERSION < 0x050000
# include <QDeclarativeView>
#else
# include <QQuickView>
#endif

#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <qplatformdefs.h>

#ifdef MEEGO_EDITION_HARMATTAN
# include <MDeclarativeCache>
#endif

#ifdef MEEGO_EDITION_HARMATTAN
Q_DECL_EXPORT int main(int argc, char *argv[])
#else
int main(int argc, char *argv[])
#endif
{

#ifdef MEEGO_EDITION_HARMATTAN
    QScopedPointer<QApplication> app(MDeclarativeCache::qApplication(argc, argv));
#else
    QScopedPointer<QApplication> app(new QApplication(argc, argv));
#endif

#if QT_VERSION < 0x050000
# ifdef MEEGO_EDITION_HARMATTAN
    QScopedPointer<QDeclarativeView> view(MDeclarativeCache::qDeclarativeView());
# else
    QScopedPointer<QDeclarativeView> view(new QDeclarativeView());
# endif
    Cordova::instance()->setTopLevelEventsReceiver(view->data());
    view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
    view->rootContext()->setContextProperty("cordova", Cordova::instance());
# ifdef MEEGO_EDITION_HARMATTAN
    view->setSource(QUrl(QString("%1/qml/main_harmattan.qml").arg(Cordova::instance()->workingDir())));
    view->showFullScreen();
# else
    view->setSource(QUrl(QString("%1/qml/main.qml").arg(Cordova::instance()->workingDir())));
    view->show();
# endif
#else // QT_VERSION >= 0x050000
    QQuickView view;
    Cordova::instance()->setTopLevelEventsReceiver(&view);
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.rootContext()->setContextProperty("cordova", Cordova::instance());
    view.setSource(QUrl(QString("%1/qml/main_qt5.qml").arg(Cordova::instance()->workingDir())));
    view.show();
#endif

    return app->exec();
}
<commit_msg>Small fix after resolving conflicts<commit_after>/*
 *  Copyright 2011 Wolfgang Koller - http://www.gofg.at/
 *
 *  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 <QApplication>

#include "src/cordova.h"

#if QT_VERSION < 0x050000
# include <QDeclarativeView>
#else
# include <QQuickView>
#endif

#include <QDeclarativeContext>
#include <QDeclarativeEngine>
#include <qplatformdefs.h>

#ifdef MEEGO_EDITION_HARMATTAN
# include <MDeclarativeCache>
#endif

#ifdef MEEGO_EDITION_HARMATTAN
Q_DECL_EXPORT int main(int argc, char *argv[])
#else
int main(int argc, char *argv[])
#endif
{

#ifdef MEEGO_EDITION_HARMATTAN
    QScopedPointer<QApplication> app(MDeclarativeCache::qApplication(argc, argv));
#else
    QScopedPointer<QApplication> app(new QApplication(argc, argv));
#endif

#if QT_VERSION < 0x050000
# ifdef MEEGO_EDITION_HARMATTAN
    QScopedPointer<QDeclarativeView> view(MDeclarativeCache::qDeclarativeView());
# else
    QScopedPointer<QDeclarativeView> view(new QDeclarativeView());
# endif
    Cordova::instance()->setTopLevelEventsReceiver(view.data());
    view->setResizeMode(QDeclarativeView::SizeRootObjectToView);
    view->rootContext()->setContextProperty("cordova", Cordova::instance());
# ifdef MEEGO_EDITION_HARMATTAN
    view->setSource(QUrl(QString("%1/qml/main_harmattan.qml").arg(Cordova::instance()->workingDir())));
    view->showFullScreen();
# else
    view->setSource(QUrl(QString("%1/qml/main.qml").arg(Cordova::instance()->workingDir())));
    view->show();
# endif
#else // QT_VERSION >= 0x050000
    QQuickView view;
    Cordova::instance()->setTopLevelEventsReceiver(&view);
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.rootContext()->setContextProperty("cordova", Cordova::instance());
    view.setSource(QUrl(QString("%1/qml/main_qt5.qml").arg(Cordova::instance()->workingDir())));
    view.show();
#endif

    return app->exec();
}
<|endoftext|>


<commit_before>a38f3beb-2747-11e6-9ff6-e0f84713e7b8<commit_msg>Hey we can now do a thing<commit_after>a3a4a323-2747-11e6-a149-e0f84713e7b8<|endoftext|>


<commit_before>/* File: main.cpp
 * Contains base main function and usually all the other stuff that avr does...
 */
/* Copyright (c) 2012-2013 Domen Ipavec (domen.ipavec@z-v.si)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 #define F_CPU 8000000UL  // 8 MHz
//#include <util/delay.h>

#include <avr/io.h>
#include <avr/interrupt.h>
//#include <avr/pgmspace.h>
//#include <avr/eeprom.h>

#include <stdint.h>

#include "bitop.h"
#include "random32.h"

static const uint8_t I2C_ADDRESS = 0x40;

static volatile uint8_t n = 33;
static volatile uint8_t utrinek_timeout;
static volatile uint8_t utrinek_timeout_min = 5;
static volatile uint8_t utrinek_timeout_max = 30;

static void startUtrinek() {
	OCR0B = BIT(7);
	OCR1A = 0x0100;
	n = 0;
}

static void calcUtrinek() {
    utrinek_timeout = utrinek_timeout_min + get_random32(utrinek_timeout_max - utrinek_timeout_min);
}

int main() {
    init_random32();
    calcUtrinek();

	// init
    // led enable
	//SETBIT(DDRA, PA7);
	// led latch
	//SETBIT(DDRA, PA1);
    // led clock
	//SETBIT(DDRA, PA2);
    // led data
	//SETBIT(DDRA, PA3);
    DDRA = 0b10001110;

	// timer 1 for advancing led
    OCR1A = 0x0100;
    TCNT1 = 0;
	TCCR1B = 0b00001101;
	SETBIT(TIMSK1, OCIE1A);

	// timer 0 for pwm
	TCCR0A = 0b00110001;
	TCCR0B = 0b010;

	// timer 2 for triggering utrinek
    OCR2A = 31250;
    TCNT2 = 0;
    TCCR2B = 0b00001100;
    SETBIT(TIMSK2, OCIE2A);

    // init i2c
    TWSCRA = 0b00111000;
    TWSA = I2C_ADDRESS<<1;

	// enable interrupts
	sei();

	uint8_t i = 0;
	for (;;) {
        if (n < 33) {
            for (uint8_t j = 29-n; j > 0; j--) {
                SETBIT(PORTA, PA2);
                CLEARBIT(PORTA, PA2);
            }

            SETBIT(PORTA, PA3);
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            if (i>2) {
                CLEARBIT(PORTA, PA3);
            }
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            if (i>0) {
                CLEARBIT(PORTA, PA3);
            }
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            CLEARBIT(PORTA, PA3);
            for (uint8_t j = n; j > 0; j--) {
                SETBIT(PORTA, PA2);
                CLEARBIT(PORTA, PA2);
            }

            // latch
            SETBIT(PORTA, PA1);
            CLEARBIT(PORTA, PA1);

            i++;
            if (i > 32) {
                i = 0;
            }
        }
	}
}

ISR(TWI_SLAVE_vect) {
    static uint8_t state;
    static uint8_t command;
    if (BITSET(TWSSRA, TWASIF)) {
        // received address/stop
        if (BITSET(TWSSRA, TWAS)) {
            // received address
            if (BITSET(TWSSRA, TWDIR)) {
                // read operation
                TWSCRB = 0b00000110;
            } else {
                // write operation
                state = 0;
                TWSCRB = 0b00000011;
            }
        } else {
            // received stop
            TWSCRB = 0b00000010;
        }
    } else if (BITSET(TWSSRA, TWDIF)) {
        // received data
        if (state == 0) {
            command = TWSD;
            state++;
            if (TWSD == 0) {
                startUtrinek();
            }
        } else {
            if (command == 1) {
                utrinek_timeout_min = TWSD;
                if (utrinek_timeout_min == 0)  {
                    utrinek_timeout_min = 1;
                } else if (utrinek_timeout_min == 0xff) {
                    utrinek_timeout_min = 0xfe;
                }
            } else if (command == 2) {
                utrinek_timeout_max = TWSD;
            }
            if (utrinek_timeout_max <= utrinek_timeout_min) {
                utrinek_timeout_max = utrinek_timeout_min + 1;
            }
            if (utrinek_timeout > utrinek_timeout_max) {
                utrinek_timeout = utrinek_timeout_max;
            }
        }

        TWSCRB = 0b00000011;
    } else {
        TWSCRB = 0b00000111;
    }
}

ISR(TIMER1_COMPA_vect) {
	if (n < 33) {
		OCR1A -= 0x2;
		if (n%3 == 2 and n > 9) {
			OCR0B >>= 1;
		}
		if (n > 10) {
			OCR1A -= 0x4;
			if (n > 20 and OCR1A > 0x1F) {
				OCR1A -= 0xC;
			}
		}
		n++;
	}
}

ISR(TIMER2_COMPA_vect) {
    utrinek_timeout--;
    if (utrinek_timeout == 0) {
        calcUtrinek();
        startUtrinek();
    }
}<commit_msg>Enabled pwm.<commit_after>/* File: main.cpp
 * Contains base main function and usually all the other stuff that avr does...
 */
/* Copyright (c) 2012-2013 Domen Ipavec (domen.ipavec@z-v.si)
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

 #define F_CPU 8000000UL  // 8 MHz
//#include <util/delay.h>

#include <avr/io.h>
#include <avr/interrupt.h>
//#include <avr/pgmspace.h>
//#include <avr/eeprom.h>

#include <stdint.h>

#include "bitop.h"
#include "random32.h"

static const uint8_t I2C_ADDRESS = 0x40;

static volatile uint8_t n = 33;
static volatile uint8_t utrinek_timeout;
static volatile uint8_t utrinek_timeout_min = 5;
static volatile uint8_t utrinek_timeout_max = 30;

static void startUtrinek() {
	OCR0B = BIT(7);
	OCR1A = 0x0100;
	n = 0;
}

static void calcUtrinek() {
    utrinek_timeout = utrinek_timeout_min + get_random32(utrinek_timeout_max - utrinek_timeout_min);
}

int main() {
    init_random32();
    calcUtrinek();

	// init
    // led enable
	//SETBIT(DDRA, PA7);
	// led latch
	//SETBIT(DDRA, PA1);
    // led clock
	//SETBIT(DDRA, PA2);
    // led data
	//SETBIT(DDRA, PA3);
    DDRA = 0b10001110;

	// timer 1 for advancing led
    OCR1A = 0x0100;
    TCNT1 = 0;
	TCCR1B = 0b00001101;
	SETBIT(TIMSK1, OCIE1A);

	// timer 0 for pwm
	TCCR0A = 0b00110001;
	TCCR0B = 0b010;
    TOCPMCOE = 0b01000000;

	// timer 2 for triggering utrinek
    OCR2A = 31250;
    TCNT2 = 0;
    TCCR2B = 0b00001100;
    SETBIT(TIMSK2, OCIE2A);

    // init i2c
    TWSCRA = 0b00111000;
    TWSA = I2C_ADDRESS<<1;

	// enable interrupts
	sei();

	uint8_t i = 0;
	for (;;) {
        if (n < 33) {
            for (uint8_t j = 29-n; j > 0; j--) {
                SETBIT(PORTA, PA2);
                CLEARBIT(PORTA, PA2);
            }

            SETBIT(PORTA, PA3);
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            if (i>2) {
                CLEARBIT(PORTA, PA3);
            }
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            if (i>0) {
                CLEARBIT(PORTA, PA3);
            }
            SETBIT(PORTA, PA2);
            CLEARBIT(PORTA, PA2);

            CLEARBIT(PORTA, PA3);
            for (uint8_t j = n; j > 0; j--) {
                SETBIT(PORTA, PA2);
                CLEARBIT(PORTA, PA2);
            }

            // latch
            SETBIT(PORTA, PA1);
            CLEARBIT(PORTA, PA1);

            i++;
            if (i > 32) {
                i = 0;
            }
        }
	}
}

ISR(TWI_SLAVE_vect) {
    static uint8_t state;
    static uint8_t command;
    if (BITSET(TWSSRA, TWASIF)) {
        // received address/stop
        if (BITSET(TWSSRA, TWAS)) {
            // received address
            if (BITSET(TWSSRA, TWDIR)) {
                // read operation
                TWSCRB = 0b00000110;
            } else {
                // write operation
                state = 0;
                TWSCRB = 0b00000011;
            }
        } else {
            // received stop
            TWSCRB = 0b00000010;
        }
    } else if (BITSET(TWSSRA, TWDIF)) {
        // received data
        if (state == 0) {
            command = TWSD;
            state++;
            if (TWSD == 0) {
                startUtrinek();
            }
        } else {
            if (command == 1) {
                utrinek_timeout_min = TWSD;
                if (utrinek_timeout_min == 0)  {
                    utrinek_timeout_min = 1;
                } else if (utrinek_timeout_min == 0xff) {
                    utrinek_timeout_min = 0xfe;
                }
            } else if (command == 2) {
                utrinek_timeout_max = TWSD;
            }
            if (utrinek_timeout_max <= utrinek_timeout_min) {
                utrinek_timeout_max = utrinek_timeout_min + 1;
            }
            if (utrinek_timeout > utrinek_timeout_max) {
                utrinek_timeout = utrinek_timeout_max;
            }
        }

        TWSCRB = 0b00000011;
    } else {
        TWSCRB = 0b00000111;
    }
}

ISR(TIMER1_COMPA_vect) {
	if (n < 33) {
		OCR1A -= 0x2;
		if (n%3 == 2 and n > 9) {
			OCR0B >>= 1;
		}
		if (n > 10) {
			OCR1A -= 0x4;
			if (n > 20 and OCR1A > 0x1F) {
				OCR1A -= 0xC;
			}
		}
		n++;
	}
}

ISR(TIMER2_COMPA_vect) {
    utrinek_timeout--;
    if (utrinek_timeout == 0) {
        calcUtrinek();
        startUtrinek();
    }
}<|endoftext|>


<commit_before>3b107b75-ad5b-11e7-8c27-ac87a332f658<commit_msg>This'll fix that<commit_after>3b88e0f0-ad5b-11e7-bf3f-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

struct Room {
	Room(RoomID idnum, string i_description) : ID(idnum) {
		description = i_description;
	}
	virtual string describe() {
    stringstream ss;
    ss << description << "\n";
    ss << "Entities: "; for(auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
    ss << "Items: "; for(auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
    ss << "Obvious exits: "; for(auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
		return ss.str();
	}
  const RoomID ID; //unique id of the room
	string description; //general description of the room for the player
	vector<unique_ptr<Entity>> entities;
	vector<RoomObject> objects;
	unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>Structural stuff<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <functional>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

using RoomID = int;

struct RoomObject
{
	vector<string> names;
	string description;
	bool visible;
};

struct Room;

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
		UNKNOWN,
		GRAVEYARD,
		GRAVEYARD_GATES,
		KHATHARRS_MOMS_HOUSE,
		GATES_OF_SHOGUN,
		HOUSE_OF_BLUES,
		FOGGY_FOREST
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		/*map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
		map_location[50][52] = GATES_OF_SHOGUN;
		map_location[50][53] = HOUSE_OF_BLUES;
		map_location[50][54] = FOGGY_FOREST;*/
	}

  unordered_map<RoomID, unique_ptr<Room>> rooms;
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    //Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item
{
    BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

/*
struct ReallyFastSword : public Item
struct TheFastcall : public Entity
{
    TheFastcall() : Entity("The Fastcall", 22) {}
    virtual bool act(vector<string> commands) override
    {
    }
};
*/

struct Room {
    Room(RoomID idnum, string i_description) : ID(idnum) {
        description = i_description;
    }
    virtual string describe() {
        stringstream ss;
        ss << description << "\n";
        ss << "Entities: "; for (auto& ent : entities) { ss << ent->name << ", "; }; ss << "\n"; //make this look nice later
        ss << "Items: "; for (auto& obj : objects) { ss << obj.names[0] << ", "; }; ss << "\n";  //make this look nice later
        ss << "Obvious exits: "; for (auto kv : exits) { ss << kv.first << ", "; } ss << "\n"; //...
        return ss.str();
    }
    const RoomID ID; //unique id of the room
    string description; //general description of the room for the player
    vector<unique_ptr<Entity>> entities;
    vector<RoomObject> objects;
    unordered_map<string, RoomID> exits; //keys are things like "north", "down", "cave", etc.
};

typedef bool (*actionHandlerBYEBYENAMECOLLISION)(vector<string> commands); // unused, but we can't technically delete this, and commenting it out is just cheating.

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health)
    {
        map.rooms[Map::Location::GRAVEYARD] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard description"));
        map.rooms[Map::Location::GRAVEYARD_GATES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Graveyard gates description"));
        map.rooms[Map::Location::KHATHARRS_MOMS_HOUSE] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Moms house"));
        map.rooms[Map::Location::GATES_OF_SHOGUN] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Gates of shogun"));
        map.rooms[Map::Location::HOUSE_OF_BLUES] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Blues"));
        map.rooms[Map::Location::FOGGY_FOREST] = unique_ptr<Room>(new Room(Map::Location::GRAVEYARD, "Forest"));
    }

    virtual bool act(vector<string> commands) override
    {
        auto cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
		if ((direction == "north"&&map.map_location[map.x][map.y + 1] == Map::UNKNOWN) || (direction == "south"&&map.map_location[map.x][map.y - 1] == Map::UNKNOWN) || (direction == "east"&&map.map_location[map.x + 1][map.y] == Map::UNKNOWN)||(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN))return false;
		if (direction == "north")map.y++; if (direction == "south")map.y--; if (direction == "east")map.x++; if (direction == "west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
			case Map::GATES_OF_SHOGUN:
				cout << "Here lies the Gates of the Great Shogun. Creator of A1 weaponry; able to fork stakes by a mere glare. It is said that to look into his eyes is to see your future covered in darkness. As you notice the thick red stains which cover the gates, you are reminded of the villagers' tales of sacrifices hung from these very gates. The gate has no lock. Do you enter?" << endl;
				break;
			case Map::HOUSE_OF_BLUES:
				cout << "This is a place where men shed tears and pour out emotion! Of course, after 2 or 3 pints of the finest ale. The miscreants who frequent cavernous house know the warmth of beds not their own. Doors sing with laughter and a timely cry or two. Will you enter to find love?" << endl;
				break;
			case Map::FOGGY_FOREST:
				cout << "Not much is known about this forest. Only that a wolf howls 3 times in the night, every night. And those who enter have never been known to return. Do you risk your life for adventure?" << endl;
				break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(size_t index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
    unordered_map<string, function<bool(vector<string>)>> actions;

    Map map;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>


<commit_before>7c268fe6-4b02-11e5-b6ec-28cfe9171a43<commit_msg>bobby added more bugs<commit_after>7c370fde-4b02-11e5-b323-28cfe9171a43<|endoftext|>


<commit_before>#include <cstdio>
#include <bitset>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;

//Extra Parameters
#define ENCSIZE 10
#define POPSIZE 10
#define RANGEINF 0
#define RANGESUP 10
#define MUTATERT 5

bitset<POPSIZE> popbin[POPSIZE];
vector<int>     popint[POPSIZE];
vector<double>  popdou[POPSIZE];

default_random_engine generator;
uniform_real_distribution<double> distribution(RANGEINF, RANGESUP);

int bAlternados(int i, char tipo){
    int fitness=0;
    if(tipo == 'b'){
        for(int j=0; j<POPSIZE-1; j++){
            if(popbin[i][j] != popbin[i][j+1])
                fitness++;
        }
    }
    else if(tipo == 'i'){
        for(int j=0; j<POPSIZE-1; j++){
            // printf("\n%d %d\n", popint[i][j]%2, popint[i][j+1]%2);
            if(popint[i][j]%2 != popint[i][j+1]%2)
                fitness++;
        }
    }
    else
        printf("Tipo incorreto\n");
    return fitness;
}

double x2(int i){
    double fitness=0;
    for(int j=0; j<POPSIZE-1; j++){
        fitness += popdou[i][j]*popdou[i][j];
    }
    return fitness;
}

void mutation(char type){
    if(type == 'b'){
        for(int i=0; i<POPSIZE; i++){
            for (int j = 0; j<ENCSIZE; j++)
            {
                if(rand()%101 < MUTATERT)
                    popbin[i].flip(j);
            }
        }
    }
    if(type == 'i'){
        for(int i=0; i<POPSIZE; i++){
            for (int j = 0; j<ENCSIZE; j++)
            {
                if(rand()%101 < MUTATERT){
                    int temp = rand()%(RANGESUP - RANGEINF) + RANGEINF;
                    if(find(popint[i].begin(), popint[i].end(), temp) == popint[i].end()){
                        popint[i][j] = temp;
                    }
                }
            }
        }
    }
    else{
        for(int i=0; i<POPSIZE; i++){
            for (int j = 0; j<ENCSIZE; j++)
            {
                if(rand()%101 < MUTATERT)
                    popdou[i][j] = distribution(generator);
            }
        }
    }
}

int main(int argc, char **argv){
    if(argc != 2){
        printf("Wrong Parameters\n");
        printf("1- Population Type (b - Binary; i - Integer; r - Real)\n");
        exit(0);
    }
    char type = argv[1][0];
    srand(time(NULL));
    if(type == 'b'){
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                if(rand()%2==0)
                    popbin[i].reset(j);
                else
                    popbin[i].set(j);
                printf(" %d", (int)popbin[i][j]);
            }
            printf(" Fit = %d\n",bAlternados(i, type));
        }
    }
    else if(type == 'i'){
        int temp;
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                temp = rand()%(RANGESUP - RANGEINF) + RANGEINF;
                if(find(popint[i].begin(), popint[i].end(), temp) == popint[i].end()){
                    popint[i].push_back(temp);
                    printf(" %d", popint[i][j]);
                }
                else
                    j--;
            }
            printf(" Fit = %d\n",bAlternados(i, type));
        }
    }
    else{ //type == 'r'
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                popdou[i].push_back(distribution(generator));
                printf(" %lf", popdou[i][j]);
            }
            printf(" Fit = %lf\n",x2(i));
        }
    }
    return 0;
}
<commit_msg>Mutation changes<commit_after>#include <cstdio>
#include <bitset>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;

//Extra Parameters
#define ENCSIZE 10
#define POPSIZE 10
#define RANGEINF 0
#define RANGESUP 10
#define MUTATERT 5

bitset<POPSIZE> popbin[POPSIZE];
vector<int>     popint[POPSIZE];
vector<double>  popdou[POPSIZE];

default_random_engine generator;
uniform_real_distribution<double> distribution(RANGEINF, RANGESUP);

int bAlternados(int i, char tipo){
    int fitness=0;
    if(tipo == 'b'){
        for(int j=0; j<POPSIZE-1; j++){
            if(popbin[i][j] != popbin[i][j+1])
                fitness++;
        }
    }
    else if(tipo == 'i'){
        for(int j=0; j<POPSIZE-1; j++){
            // printf("\n%d %d\n", popint[i][j]%2, popint[i][j+1]%2);
            if(popint[i][j]%2 != popint[i][j+1]%2)
                fitness++;
        }
    }
    else
        printf("Tipo incorreto\n");
    return fitness;
}

double x2(int i){
    double fitness=0;
    for(int j=0; j<POPSIZE-1; j++){
        fitness += popdou[i][j]*popdou[i][j];
    }
    return fitness;
}

void mutation(char type){
    if(type == 'b'){
        for(int i=0; i<POPSIZE; i++){
            for (int j = 0; j<ENCSIZE; j++)
            {
                if(rand()%101 < MUTATERT)
                    popbin[i].flip(j);
            }
        }
    }
    if(type == 'i'){
        for(int i=0; i<POPSIZE; i++){
            for(auto j=popint[i].begin(); j<popint[i].end(); j++){
                if(rand()%101 < MUTATERT){
                    popint[i].erase(j);
                    int temp = rand()%(RANGESUP - RANGEINF) + RANGEINF;
                    if(find(popint[i].begin(), popint[i].end(), temp) == popint[i].end()){
                        popint[i].insert(j, temp);
                    }
                }
            }
        }
    }
    else{
        for(int i=0; i<POPSIZE; i++){
            for (int j = 0; j<ENCSIZE; j++)
            {
                if(rand()%101 < MUTATERT)
                    popdou[i][j] = distribution(generator);
            }
        }
    }
}

int main(int argc, char **argv){
    if(argc != 2){
        printf("Wrong Parameters\n");
        printf("1- Population Type (b - Binary; i - Integer; r - Real)\n");
        exit(0);
    }
    char type = argv[1][0];
    srand(time(NULL));
    if(type == 'b'){
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                if(rand()%2==0)
                    popbin[i].reset(j);
                else
                    popbin[i].set(j);
                printf(" %d", (int)popbin[i][j]);
            }
            printf(" Fit = %d\n",bAlternados(i, type));
        }
    }
    else if(type == 'i'){
        int temp;
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                temp = rand()%(RANGESUP - RANGEINF) + RANGEINF;
                if(find(popint[i].begin(), popint[i].end(), temp) == popint[i].end()){
                    popint[i].push_back(temp);
                    printf(" %d", popint[i][j]);
                }
                else
                    j--;
            }
            printf(" Fit = %d\n",bAlternados(i, type));
        }
    }
    else{ //type == 'r'
        for(int i=0; i<POPSIZE; i++){
            for(int j=0; j<ENCSIZE; j++){
                popdou[i].push_back(distribution(generator));
                printf(" %lf", popdou[i][j]);
            }
            printf(" Fit = %lf\n",x2(i));
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>// A very rough C++ version for the 2048 game
//
// Author: Olafur Waage / @olafurw
// olafurw@gmail.com
//
// Under the Apache License
// If you have any fun with this, please let me know, I would love to hear from you.

#include <iostream>

#include "utils.hpp"
#include "grid.hpp"

unsigned int tournament_selection(const std::vector<grid>& population)
{
    std::mt19937& r = rand_gen();

    unsigned int parent_a = r() % population.size();
    int parent_a_score = population[parent_a].score();

    unsigned int parent_b = r() % population.size();
    int parent_b_score = population[parent_b].score();

    return parent_a_score > parent_b_score ? parent_a : parent_b;
}

void mutation(std::vector<direction>& child_a_actions)
{
    std::mt19937& r = rand_gen();

    for(unsigned int i = 0; i < child_a_actions.size(); ++i)
    {
        if(r() % 100 < 10)
        {
            child_a_actions[i] = rand_action();
        }
    }
}

void one_point_crossover(const std::vector<direction>& parent_a,
                         const std::vector<direction>& parent_b,
                         grid& child_a,
                         grid& child_b)
{
    std::mt19937& r = rand_gen();

    std::vector<direction> child_a_actions;
    std::vector<direction> child_b_actions;

    unsigned int split_a = static_cast<unsigned int>(r() % parent_a.size());
    unsigned int smaller_parent = std::min(parent_a.size(), parent_b.size());
    unsigned int larger_parent = std::max(parent_a.size(), parent_b.size());
    unsigned int split = std::min(split_a, smaller_parent);

    for(unsigned int i = 0; i < smaller_parent; ++i)
    {
        if(i < split)
        {
            child_a_actions.push_back(parent_a.at(i));
            child_b_actions.push_back(parent_b.at(i));
        }
        else
        {
            child_a_actions.push_back(parent_b.at(i));
            child_b_actions.push_back(parent_a.at(i));
        }
    }

    // TODO: Refactor, doing this now since each
    // child can be of different lengths
    // and the split can be in the larger parent
    for(unsigned int i = smaller_parent; i < larger_parent; ++i)
    {
        if(i < split)
        {
            if(larger_parent == parent_b.size())
            {
                child_a_actions.push_back(parent_b.at(i));
            }
            else
            {
                child_b_actions.push_back(parent_b.at(i));
            }
        }
        else
        {
            if(larger_parent == parent_b.size())
            {
                child_a_actions.push_back(parent_b.at(i));
            }
            else
            {
                child_b_actions.push_back(parent_a.at(i));
            }
        }
    }

    mutation(child_a_actions);
    mutation(child_b_actions);

    child_a.add_actions(child_a_actions);
    child_b.add_actions(child_b_actions);
}

void sort_population(std::vector<grid>& population)
{
    std::sort(population.begin(), population.end(),
        [](const grid & a, const grid & b)
    {
        return a.score() > b.score();
    });
}

void sort_population_random(std::vector<grid>& population)
{
    std::shuffle(population.begin(), population.end(), rand_gen());
}

int main()
{
    // Initial population
    std::vector<grid> population;

    int largest = 0;

    for(int i = 0; i < 100; ++i)
    {
        grid g;

        while(g.can_move())
        {
            g.action(rand_action());
        }

        population.emplace_back(g);
    }

    for(unsigned int i = 0; i < 100000; ++i)
    {
        unsigned int parent_a = tournament_selection(population);
        unsigned int parent_b = tournament_selection(population);

        grid child_a;
        grid child_b;

        one_point_crossover(population.at(parent_a).actions(),
                            population.at(parent_b).actions(),
                            child_a,
                            child_b);

        population.emplace_back(child_a);
        population.emplace_back(child_b);

        sort_population(population);

        population.pop_back();
        population.pop_back();

        if(largest < population.at(0).score())
        {
            largest = population.at(0).score();

            std::cout << largest << std::endl;
        }

        sort_population_random(population);
    }

    sort_population(population);

    population.at(0).print();

    for(auto& p : population)
    {
        std::cout << p.score() << std::endl;
    }

    return 0;
}
<commit_msg>Additional fix #1 to main file, adding uniform distribution random generator.<commit_after>// A very rough C++ version for the 2048 game
//
// Author: Olafur Waage / @olafurw
// olafurw@gmail.com
//
// Under the Apache License
// If you have any fun with this, please let me know, I would love to hear from you.

#include <iostream>

#include "utils.hpp"
#include "grid.hpp"

unsigned int tournament_selection(const std::vector<grid>& population)
{
    std::uniform_int_distribution<> dis(0, population.size() - 1);

    unsigned int parent_a = dis(rand_gen());
    int parent_a_score = population[parent_a].score();

    unsigned int parent_b = dis(rand_gen());
    int parent_b_score = population[parent_b].score();

    return parent_a_score > parent_b_score ? parent_a : parent_b;
}

void mutation(std::vector<direction>& child_a_actions)
{
    std::uniform_int_distribution<> dis(0, 99);

    for(unsigned int i = 0; i < child_a_actions.size(); ++i)
    {
        if(dis(rand_gen()) < 10)
        {
            child_a_actions[i] = rand_action();
        }
    }
}

void one_point_crossover(const std::vector<direction>& parent_a,
                         const std::vector<direction>& parent_b,
                         grid& child_a,
                         grid& child_b)
{
    std::uniform_int_distribution<> dis(0, parent_a.size());

    std::vector<direction> child_a_actions;
    std::vector<direction> child_b_actions;

    unsigned int split_a = dis(rand_gen());
    unsigned int smaller_parent = std::min(parent_a.size(), parent_b.size());
    unsigned int larger_parent = std::max(parent_a.size(), parent_b.size());
    unsigned int split = std::min(split_a, smaller_parent);

    for(unsigned int i = 0; i < smaller_parent; ++i)
    {
        if(i < split)
        {
            child_a_actions.push_back(parent_a.at(i));
            child_b_actions.push_back(parent_b.at(i));
        }
        else
        {
            child_a_actions.push_back(parent_b.at(i));
            child_b_actions.push_back(parent_a.at(i));
        }
    }

    // TODO: Refactor, doing this now since each
    // child can be of different lengths
    // and the split can be in the larger parent
    for(unsigned int i = smaller_parent; i < larger_parent; ++i)
    {
        if(i < split)
        {
            if(larger_parent == parent_b.size())
            {
                child_a_actions.push_back(parent_b.at(i));
            }
            else
            {
                child_b_actions.push_back(parent_b.at(i));
            }
        }
        else
        {
            if(larger_parent == parent_b.size())
            {
                child_a_actions.push_back(parent_b.at(i));
            }
            else
            {
                child_b_actions.push_back(parent_a.at(i));
            }
        }
    }

    mutation(child_a_actions);
    mutation(child_b_actions);

    child_a.add_actions(child_a_actions);
    child_b.add_actions(child_b_actions);
}

void sort_population(std::vector<grid>& population)
{
    std::sort(population.begin(), population.end(),
        [](const grid & a, const grid & b)
    {
        return a.score() > b.score();
    });
}

void sort_population_random(std::vector<grid>& population)
{
    std::shuffle(population.begin(), population.end(), rand_gen());
}

int main()
{
    // Initial population
    std::vector<grid> population;

    int largest = 0;

    for(int i = 0; i < 100; ++i)
    {
        grid g;

        while(g.can_move())
        {
            g.action(rand_action());
        }

        population.emplace_back(g);
    }

    for(unsigned int i = 0; i < 100000; ++i)
    {
        unsigned int parent_a = tournament_selection(population);
        unsigned int parent_b = tournament_selection(population);

        grid child_a;
        grid child_b;

        one_point_crossover(population.at(parent_a).actions(),
                            population.at(parent_b).actions(),
                            child_a,
                            child_b);

        population.emplace_back(child_a);
        population.emplace_back(child_b);

        sort_population(population);

        population.pop_back();
        population.pop_back();

        if(largest < population.at(0).score())
        {
            largest = population.at(0).score();

            std::cout << largest << std::endl;
        }

        sort_population_random(population);
    }

    sort_population(population);

    population.at(0).print();

    for(auto& p : population)
    {
        std::cout << p.score() << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "widget.hpp"
#include "application.hpp"
#include "screen.hpp"
#include "base_text_buffer.hpp"

int main(int argc, char **argv)
{
    Application a(argc, argv);
    Widget w;

    Screen w2(&w);
    w2.setLeft(100);
    w2.setTop(100);
    w2.setWidth(500);
    w2.setHeight(100);
    BaseTextBuffer b;
    w2.setTextBuffer(&b);
    w2.setFocus();
    return a.exec();
}
<commit_msg>Increase Screen size<commit_after>#include "widget.hpp"
#include "application.hpp"
#include "screen.hpp"
#include "base_text_buffer.hpp"

int main(int argc, char **argv)
{
    Application a(argc, argv);
    Widget w;

    Screen w2(&w);
    w2.setLeft(0);
    w2.setTop(0);
    w2.setWidth(640);
    w2.setHeight(480);
    BaseTextBuffer b;
    w2.setTextBuffer(&b);
    w2.setFocus();
    return a.exec();
}
<|endoftext|>


<commit_before>#include <QtGui/QApplication>
#include "mainwindow.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include <stdio.h>
#include <iostream>
#include <vector>

#include "geom/chessgen.h"

using namespace cv;
using namespace std;
using namespace fr;

int main(int, char**)
{
    VideoCapture cap(1); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    cap.set(CV_CAP_PROP_FRAME_WIDTH,640);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT,480);
    Mat edges;
    Size size(12,9);

    int counter = 10;

    vector<Point2f> corners;
    bool found;

    vector<Point3f> chess = fr::ChessGen::getBoard(size,1,false);
   /* for(unsigned int i=0;i<chess.size();i++){
        cout << chess[i].x << "," << chess[i].y << endl;
    }*/

    vector<vector<Point3f> > objectPoints;
    vector<vector<Point2f> > imagePoints;

    Mat camera = Mat::eye(3,3,CV_64F);
    camera.at<double>(0,2) = 640/2;
    camera.at<double>(1,2) = 480/2;
    Mat distortion = Mat::zeros(8, 1, CV_64F);
    vector<Mat > rvecs;
    vector<Mat > tvecs;

    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);

        found = findChessboardCorners(edges,size,corners);
        /*
        found = findCirclesGrid(edges,size,corners
                                ,CALIB_CB_ASYMMETRIC_GRID
                                );//*/
        if(found) frame.convertTo(edges,-1,0.2);

        drawChessboardCorners(edges,size,corners,found);

        imshow("edges", edges);
        /*if(found){
            //if(waitKey(200)>=0){
            waitKey(300);
                objectPoints.push_back(chess);
                imagePoints.push_back(corners);
                if(--counter<= 0)
                    break;
            //}
        }
        else waitKey(30);*/
        if(waitKey(30)>1) break;
    }

    //double rpe = calibrateCamera(objectPoints,imagePoints,Size(800,600),camera,distortion,rvecs,tvecs,CV_CALIB_FIX_ASPECT_RATIO);

    if(found) imwrite("/home/ryan/chessboard.png",edges);

    //cout << camera << endl;
    //cout << rpe << endl;

    return 0;
}
<commit_msg>basic one-camera calibration works<commit_after>#include <QtGui/QApplication>
#include "mainwindow.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include <stdio.h>
#include <iostream>
#include <vector>

#include "geom/chessgen.h"

using namespace cv;
using namespace std;
using namespace fr;

int main(int, char**)
{
    VideoCapture cap1(1);
    if(!cap1.isOpened())
        return -1;

    unsigned int i;

    cap1.set(CV_CAP_PROP_FRAME_WIDTH,800);
    cap1.set(CV_CAP_PROP_FRAME_HEIGHT,600);
    Mat edges;
    Size size(4,11);

    int counter = 12;

    vector<Point2f> corners;
    bool found;

    vector<Point3f> chess = fr::ChessGen::getBoard(size,1,true);
   /* for(unsigned int i=0;i<chess.size();i++){
        cout << chess[i].x << "," << chess[i].y << endl;
    }*/

    vector<vector<Point3f> > objectPoints;
    vector<vector<Point2f> > imagePoints1,imagePoints0;

    Mat camera = Mat::eye(3,3,CV_64F);
    Mat distortion = Mat::zeros(8, 1, CV_64F);
    vector<Mat > rvecs;
    vector<Mat > tvecs;

    namedWindow("CAMERA 1",1);
    found = false;
    for(;;)
    {
        Mat frame;
        cap1 >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);

        //frame.convertTo(edges,-1,0.2);

        for(i=0;i<imagePoints1.size();i++)
            drawChessboardCorners(frame,size,imagePoints1[i],true);

        imshow("CAMERA 1", frame);
        if(waitKey(200)>=0){
            //found = findChessboardCorners(edges,size,corners);
            //*
            found = findCirclesGrid(edges,size,corners
                                    ,CALIB_CB_ASYMMETRIC_GRID
                                    );//*/
            if(found){
                objectPoints.push_back(chess);
                imagePoints1.push_back(corners);
                if(--counter<= 0)
                    break;
            }
        }
        //else waitKey(30);
        //if(waitKey(30)>1) break;
    }

    double rpe = calibrateCamera(objectPoints,imagePoints1,Size(edges.size[0],edges.size[1]),
                                 camera,distortion,rvecs,tvecs,
                                 CV_CALIB_FIX_ASPECT_RATIO|
                                 CV_CALIB_FIX_PRINCIPAL_POINT);

    if(found) imwrite("/home/ryan/chessboard.png",edges);

    cout << camera << endl;
    //cout << rpe << endl;

    return 0;
}
<|endoftext|>


<commit_before>#include "fast3x3.hpp"

#include <stdlib.h>

#include <chrono>  // note: C++11
#include <random>

// Build with: g++ main.cpp -std=c++0x -O3 -lblas -o test
// Use with:
//    ./test n numsteps
// n is the size of the matrix (default 2187)
// numsteps is the number of recursive steps (default 1)

int main(int argc, char **argv) {
    int n = 2187;
    int numsteps = 1;
    int run_classical = 0;
    int run_fast = 1;
    if (argc > 1) {
        n = atoi(argv[1]);
    }
    if (argc > 2) {
        numsteps = atoi(argv[2]);
    }
    if (argc > 3) {
        run_classical = atoi(argv[3]);
    }
    if (argc > 4) {
        run_fast = atoi(argv[4]);
    }

    std::cout << "n is: " << n << std::endl;
    std::cout << "number of recursive steps is: " << numsteps << std::endl;

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dist(0, 1e5);

    Matrix<double> A(n);
    Matrix<double> B(n);
    Matrix<double> C(n);
    for (int j = 0; j < n; ++j) {
        for (int i = 0; i < n; ++i) {
            A.data()[i + j * A.stride()] = dist(gen);
            B.data()[i + j * B.stride()] = dist(gen);
        }
    }

    if (run_classical) {
        std::cout << "Running classical gemm..." << std::endl;
        auto t1 = std::chrono::high_resolution_clock::now();
        Gemm(A, B, C);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "Classical gemm took "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
                  << " milliseconds"
                  << std::endl;
        C.deallocate();
    }

    if (run_fast) {
        std::cout << "Running fast matmul..." << std::endl;
        auto t3 = std::chrono::high_resolution_clock::now();
        FastMatmul3x3(A, B, C, numsteps);
        auto t4 = std::chrono::high_resolution_clock::now();
        std::cout << "Fast matmul took "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
                  << " milliseconds"
                  << std::endl;
        C.deallocate();
    }

#if 0
    // Test for correctness.
    double diff = FrobeniusDiff(C1, C2);
    std::cout << "Frobenius norm solution difference: "
              << diff
              << std::endl;

    // Component-wise differences
    int step = n / 3;
    Matrix<double> C11A(C1.data(), C1.stride(), step, step);
    Matrix<double> C21A(C1.data() + step, C1.stride(), step, step);
    Matrix<double> C31A(C1.data() + 2 * step, C1.stride(), step, step);
    Matrix<double> C12A(C1.data() + step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C22A(C1.data() + step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C32A(C1.data() + step * C1.stride() + 2 * step, C1.stride(), step, step);
    Matrix<double> C13A(C1.data() + 2 * step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C23A(C1.data() + 2 * step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C33A(C1.data() + 2 * step * C1.stride() + 2 * step, C1.stride(), step, step);

    Matrix<double> C11B(C2.data(), C2.stride(), step, step);
    Matrix<double> C21B(C2.data() + step, C2.stride(), step, step);
    Matrix<double> C31B(C2.data() + 2 * step, C2.stride(), step, step);
    Matrix<double> C12B(C2.data() + step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C22B(C2.data() + step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C32B(C2.data() + step * C2.stride() + 2 * step, C2.stride(), step, step);
    Matrix<double> C13B(C2.data() + 2 * step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C23B(C2.data() + 2 * step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C33B(C2.data() + 2 * step * C2.stride() + 2 * step, C2.stride(), step, step);

    std::cout << "(1, 1): " << FrobeniusDiff(C11A, C11B) << std::endl;
    std::cout << "(2, 1): " << FrobeniusDiff(C21A, C21B) << std::endl;
    std::cout << "(3, 1): " << FrobeniusDiff(C31A, C31B) << std::endl;

    std::cout << "(1, 2): " << FrobeniusDiff(C12A, C12B) << std::endl;
    std::cout << "(2, 2): " << FrobeniusDiff(C22A, C22B) << std::endl;
    std::cout << "(3, 2): " << FrobeniusDiff(C32A, C32B) << std::endl;

    std::cout << "(1, 3): " << FrobeniusDiff(C13A, C13B) << std::endl;
    std::cout << "(2, 3): " << FrobeniusDiff(C23A, C23B) << std::endl;
    std::cout << "(3, 3): " << FrobeniusDiff(C33A, C33B) << std::endl;
#endif

}
<commit_msg>C++11 random number generation is way too slow<commit_after>#include "fast3x3.hpp"

#include <stdlib.h>
#include <time.h>

#include <chrono>  // note: C++11
#include <random>

// Build with: g++ main.cpp -std=c++0x -O3 -lblas -o test
// Use with:
//    ./test n numsteps
// n is the size of the matrix (default 2187)
// numsteps is the number of recursive steps (default 1)

int main(int argc, char **argv) {
    int n = 2187;
    int numsteps = 1;
    int run_classical = 0;
    int run_fast = 1;
    if (argc > 1) {
        n = atoi(argv[1]);
    }
    if (argc > 2) {
        numsteps = atoi(argv[2]);
    }
    if (argc > 3) {
        run_classical = atoi(argv[3]);
    }
    if (argc > 4) {
        run_fast = atoi(argv[4]);
    }

    std::cout << "n is: " << n << std::endl;
    std::cout << "number of recursive steps is: " << numsteps << std::endl;

    srand (time(NULL));

    Matrix<double> A(n);
    Matrix<double> B(n);
    Matrix<double> C(n);
    for (int j = 0; j < n; ++j) {
        for (int i = 0; i < n; ++i) {
            A.data()[i + j * A.stride()] = ((double) rand() / RAND_MAX) * 1024;
            B.data()[i + j * B.stride()] = ((double) rand() / RAND_MAX) * 1024;
        }
    }

    if (run_classical) {
        std::cout << "Running classical gemm..." << std::endl;
        auto t1 = std::chrono::high_resolution_clock::now();
        Gemm(A, B, C);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "Classical gemm took "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
                  << " milliseconds"
                  << std::endl;
        C.deallocate();
    }

    if (run_fast) {
        std::cout << "Running fast matmul..." << std::endl;
        auto t3 = std::chrono::high_resolution_clock::now();
        FastMatmul3x3(A, B, C, numsteps);
        auto t4 = std::chrono::high_resolution_clock::now();
        std::cout << "Fast matmul took "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(t4-t3).count()
                  << " milliseconds"
                  << std::endl;
        C.deallocate();
    }

#if 0
    // Test for correctness.
    double diff = FrobeniusDiff(C1, C2);
    std::cout << "Frobenius norm solution difference: "
              << diff
              << std::endl;

    // Component-wise differences
    int step = n / 3;
    Matrix<double> C11A(C1.data(), C1.stride(), step, step);
    Matrix<double> C21A(C1.data() + step, C1.stride(), step, step);
    Matrix<double> C31A(C1.data() + 2 * step, C1.stride(), step, step);
    Matrix<double> C12A(C1.data() + step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C22A(C1.data() + step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C32A(C1.data() + step * C1.stride() + 2 * step, C1.stride(), step, step);
    Matrix<double> C13A(C1.data() + 2 * step * C1.stride(), C1.stride(), step, step);
    Matrix<double> C23A(C1.data() + 2 * step * C1.stride() + step, C1.stride(), step, step);
    Matrix<double> C33A(C1.data() + 2 * step * C1.stride() + 2 * step, C1.stride(), step, step);

    Matrix<double> C11B(C2.data(), C2.stride(), step, step);
    Matrix<double> C21B(C2.data() + step, C2.stride(), step, step);
    Matrix<double> C31B(C2.data() + 2 * step, C2.stride(), step, step);
    Matrix<double> C12B(C2.data() + step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C22B(C2.data() + step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C32B(C2.data() + step * C2.stride() + 2 * step, C2.stride(), step, step);
    Matrix<double> C13B(C2.data() + 2 * step * C2.stride(), C2.stride(), step, step);
    Matrix<double> C23B(C2.data() + 2 * step * C2.stride() + step, C2.stride(), step, step);
    Matrix<double> C33B(C2.data() + 2 * step * C2.stride() + 2 * step, C2.stride(), step, step);

    std::cout << "(1, 1): " << FrobeniusDiff(C11A, C11B) << std::endl;
    std::cout << "(2, 1): " << FrobeniusDiff(C21A, C21B) << std::endl;
    std::cout << "(3, 1): " << FrobeniusDiff(C31A, C31B) << std::endl;

    std::cout << "(1, 2): " << FrobeniusDiff(C12A, C12B) << std::endl;
    std::cout << "(2, 2): " << FrobeniusDiff(C22A, C22B) << std::endl;
    std::cout << "(3, 2): " << FrobeniusDiff(C32A, C32B) << std::endl;

    std::cout << "(1, 3): " << FrobeniusDiff(C13A, C13B) << std::endl;
    std::cout << "(2, 3): " << FrobeniusDiff(C23A, C23B) << std::endl;
    std::cout << "(3, 3): " << FrobeniusDiff(C33A, C33B) << std::endl;
#endif

}
<|endoftext|>


<commit_before>b055f0b5-4b02-11e5-8c04-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>b063ad97-4b02-11e5-97ac-28cfe9171a43<|endoftext|>