<commit_before>/**
 * SUBLEQ Assembly: main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author:       Pimenta
 *      Collaborator: Alexandre Dantas
 *
 * This program reads a SUBLEQ Assembly file and outputs
 * a well-formed object file.
 * It's supposed to be fed to the Linker.
 */

#include <cstdint>
#include <cstdio>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

typedef uint32_t uword_t;

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

/// Buffer that contains the entire contents
/// of the input file, with normalized line endings.
static stringstream f;

/// Global buffer that always contains the current
/// token being read by `readToken`
static string buf;

/// Set of all exported symbols.
/// They're used together with other object files
/// on the linker.
static set<string> exported;

/// All current symbols declared on this file.
/// Maps from a label to it's address in memory.
static map<string, uword_t> symbols;

/// Contains all symbols not found on this file.
///
/// It has labels supposed to be found on other
/// Assembly files.
/// They'll get resolved with the external symbols.
static map<string, set<uword_t>> references;

/// Relative addresses found on this file.
///
/// When you "call" a symbol on this file, it's address
/// is relative to the start of this file.
///
/// When the Linker joins several object files, it will
/// use the values on this set to relocate them all.
///
static set<uword_t> relatives;

/// Current size of the memory.
/// While parsing: points the current memory address
///                being read.
/// At the end:    has the entire size of the memory
///                read.
static uword_t mem_size = 0;

/// Raw memory.
/// It contains the assembled memory that will get
/// written at the end of the object file.
static uword_t* mem = new uword_t[MEM_WORDS];

static int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1;

/// Reads a string from `is` to the end-of-line, saving it on `t`.
///
/// @note It doesn't save the end-of-line character on `t`.
///
/// This is a "safe" implementation of `std::getline`.
/// It is "safe" in the sense that it does work with all possible
/// line endings ("\r", "\n" and "\r\n").
///
/// Taken straight from StackOverflow. Source:
/// http://stackoverflow.com/a/6089413
///
std::istream& safeGetline(std::istream& is, std::string& t)
{
  t.clear();

  // The characters in the stream are read one-by-one using a
  // std::streambuf. That is faster than reading them one-by-one
  // using the std::istream.
  //
  // Code that uses streambuf this way must be guarded by a sentry
  // object.
  // The sentry object performs various tasks, such as thread
  // synchronization and updating the stream state.

  std::istream::sentry se(is, true);

  std::streambuf* sb = is.rdbuf();

  while (true) {
    int c = sb->sbumpc();

    switch (c) {

    case '\n':
      return is;

    case '\r':
      if (sb->sgetc() == '\n')
        sb->sbumpc();

      return is;

    case EOF:
      // Also handle the case when the last line has no line ending
      if (t.empty())
        is.setstate(std::ios::eofbit);

      return is;

    default:
      t += (char)c;
    }
  }
}

/// Reads a token (separated by whitespaces) from the file,
/// char by char, putting on `buf`
inline static void readToken() {
  buf = "";
  lastTokenLine = currentTokenLine;

  // Will read all chars until:
  //
  // - Finding a whitespace (or tab)
  // - Finding a comment
  // - Finding an end-of-line
  // - File somehow ends
  //
  while (true)
  {
    char c = f.get();

    if (!f.good())
      break;

    // comment found
    if (c == '/') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine;
        return;
      }

      // ignoring entire comment
      do {
        c = f.get();
      } while (c != '\n' && f.good());

      currentLine++;
      continue;
    }

    // line break found
    if (c == '\n') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine++;
        return;
      }

      currentLine++;
      continue;
    }

    // white space found
    if (c == ' ' || c == '\t') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine;
        return;
      }
      continue;
    }

    // this character was none of the above
    // simply appending it
    buf += c;
  }

  currentTokenLine = currentLine;
}

/// Returns text on `buf` as data.
///
/// Converts textual data to words.
/// For example, converts "0x1" to 1.
inline static uword_t parseData() {
  uword_t data = 0;
  if (buf[0] == '0' && buf[1] == 'x') { // for hex notation
    sscanf(buf.c_str(), "%i", &data);
  }
  else { // for decimal notation
    stringstream ss;
    ss << buf;
    ss >> data;
  }
  return data;
}

/// Parses a single field contained on `buf`.
///
/// So for `SUBLEQ A B C` we call this function three times,
/// once for each field A, B and C.
///
/// Returns the address being "called" by the field.
///
/// For example, if we have:
///
///     .data
///         one: 1
///     .text
///       loop:
///         one one loop
///
/// For `one` on `loop:` it returns 0, since it's the
/// address of the thing being "called" by the instruction.
///
inline static uword_t parseField() {
  uword_t field = 0;
  // hex notation means absolute address
  if (buf[0] == '0' && buf[1] == 'x') {
    sscanf(buf.c_str(), "%i", &field);
  }
  // symbol means an address that needs to be relocated later
  else {
    relatives.emplace(mem_size);

    // looking for array offset
    if (buf.find("+") != buf.npos) {
      string offset = buf.substr(buf.find("+") + 1, buf.size());
      buf = buf.substr(0, buf.find("+"));
      stringstream ss;
      ss << offset;
      ss >> field;
    }

    auto sym = symbols.find(buf);
    // symbol not found. leave a reference
    if (sym == symbols.end()) {
      references[buf].emplace(mem_size);
    }
    // symbol found. the field is the address of the symbol
    else {
      field = sym->second;
    }
  }
  return field;
}

int main(int argc, char* argv[]) {
  if (argc != 3) {
    fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n");
    return 0;
  }

  // Making sure both files exist
  fstream input_file(argv[1]);
  fstream output_file(argv[2], fstream::out | fstream::binary);

  if (!input_file) {
    cout << "Input file '" << argv[1] << "' doesn't exist" << endl;
    return EXIT_FAILURE;
  }
  if (!output_file) {
    cout << "Output file '" << argv[2] << "' doesn't exist" << endl;
    return EXIT_FAILURE;
  }

  // Read the whole file and store on a buffer.
  //
  // This way we won't need to worry about specific
  // line-endings, since it will look like it only
  // has '\n'.
  while (true) {
    string str;
    safeGetline(input_file, str);
    f << (str + '\n');

    if (!input_file)
      break;
  }
  input_file.close();

  readToken(); // reading ".export"

  // reading export section
  for (readToken(); buf != ".data"; readToken()) {
    exported.insert(buf);
  }

  // reading data section
  for (readToken(); buf != ".text";) {
    symbols[buf.substr(0, buf.size() - 1)] = mem_size;
    readToken();
    if (buf == ".array") { // uninitialized array
      readToken();
      mem_size += parseData();
      readToken(); // next symbol
    }
    else if (buf == ".iarray") { // initialized array
      for (readToken(); currentTokenLine == lastTokenLine; readToken()) {
        mem[mem_size++] = parseData();
      }
    }
    else if (buf == ".ptr") { // pointer
      readToken();
      mem[mem_size] = parseField();
      mem_size++;
      readToken(); // next symbol
    }
    else { // initialized word
      mem[mem_size++] = parseData();
      readToken(); // next symbol
    }
  }

  // reading text section
  int field = 0;
  for (readToken(); buf.size();) {
    // field 2 omitted
    if (field == 2 && currentTokenLine != lastTokenLine) {
      relatives.emplace(mem_size);
      mem[mem_size] = mem_size + 1;
      mem_size++;
      field = (field + 1)%3;
    }
    // symbol found
    else if (buf[buf.size() - 1] == ':') {
      symbols[buf.substr(0, buf.size() - 1)] = mem_size;
      if (buf == "start:")
        exported.emplace("start");
      readToken();
    }
    // field 0, 1, or field 2 specified
    else {
      mem[mem_size] = parseField();
      mem_size++;
      field = (field + 1)%3;
      readToken();
    }
  }

  // Now we go through each symbol (label), resolving references.
  //
  // If it's not on this file (`symbols` map), we assume it's
  // found on other file (`references` map).
  //
  for (auto map_it = references.begin(); map_it != references.end(); ++map_it) {

    // Which symbol was referenced
    string symbol_name = map_it->first;

    // All addresses where the symbol above was referenced
    set<uword_t> symbol_called = map_it->second;

    // Is this symbol declared on this file?
    // If not then leave it be at `references`
    auto sym = symbols.find(symbol_name);

    if (sym == symbols.end())
      continue;

    // If it's on this file, we replace it's address on every
    // memory location that called it
    uword_t symbol_address = sym->second;

    for (auto it = symbol_called.begin(); it != symbol_called.end(); ++it)
      mem[*it] += symbol_address;

    // And remove it from the external reference map
    references.erase(map_it);
  }

  // Now, outputting the binary stuff
  {
    uword_t tmp;

    // write number of exported symbols
    tmp = exported.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write exported symbols
    for (auto& exp : exported) {
      // string
      output_file.write(exp.c_str(), exp.size() + 1);

      // address
      tmp = symbols[exp];
      output_file.write((const char*)&tmp, sizeof(uword_t));
    }

    // write number of symbols of pending references
    tmp = references.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write symbols of pending references
    for (auto& sym : references) {
      // string
      output_file.write(sym.first.c_str(), sym.first.size() + 1);

      // write number of references to current symbol
      tmp = sym.second.size();
      output_file.write((const char*)&tmp, sizeof(uword_t));

      // write references to current symbol
      for (auto ref : sym.second) {
        tmp = ref;
        output_file.write((const char*)&tmp, sizeof(uword_t));
      }
    }

    // write number of relative addresses
    tmp = relatives.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write relative addresses
    for (auto addr : relatives) {
      tmp = addr;
      output_file.write((const char*)&tmp, sizeof(uword_t));
    }

    // write assembled code size
    output_file.write((const char*)&mem_size, sizeof(uword_t));

    // write assembled code
    output_file.write((const char*)mem, sizeof(uword_t)*mem_size);
  }

  output_file.close();

  delete[] mem;

  return 0;
}
<commit_msg>Made sure we can write to output file<commit_after>/**
 * SUBLEQ Assembly: main.cpp
 *
 *  Created on: Apr 9, 2014
 *      Author:       Pimenta
 *      Collaborator: Alexandre Dantas
 *
 * This program reads a SUBLEQ Assembly file and outputs
 * a well-formed object file.
 * It's supposed to be fed to the Linker.
 */

#include <cstdint>
#include <cstdio>
#include <fstream>
#include <map>
#include <set>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

typedef uint32_t uword_t;

#ifndef MEM_WORDS
#define MEM_WORDS 0x2000
#endif

/// Buffer that contains the entire contents
/// of the input file, with normalized line endings.
static stringstream f;

/// Global buffer that always contains the current
/// token being read by `readToken`
static string buf;

/// Set of all exported symbols.
/// They're used together with other object files
/// on the linker.
static set<string> exported;

/// All current symbols declared on this file.
/// Maps from a label to it's address in memory.
static map<string, uword_t> symbols;

/// Contains all symbols not found on this file.
///
/// It has labels supposed to be found on other
/// Assembly files.
/// They'll get resolved with the external symbols.
static map<string, set<uword_t>> references;

/// Relative addresses found on this file.
///
/// When you "call" a symbol on this file, it's address
/// is relative to the start of this file.
///
/// When the Linker joins several object files, it will
/// use the values on this set to relocate them all.
///
static set<uword_t> relatives;

/// Current size of the memory.
/// While parsing: points the current memory address
///                being read.
/// At the end:    has the entire size of the memory
///                read.
static uword_t mem_size = 0;

/// Raw memory.
/// It contains the assembled memory that will get
/// written at the end of the object file.
static uword_t* mem = new uword_t[MEM_WORDS];

static int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1;

/// Reads a string from `is` to the end-of-line, saving it on `t`.
///
/// @note It doesn't save the end-of-line character on `t`.
///
/// This is a "safe" implementation of `std::getline`.
/// It is "safe" in the sense that it does work with all possible
/// line endings ("\r", "\n" and "\r\n").
///
/// Taken straight from StackOverflow. Source:
/// http://stackoverflow.com/a/6089413
///
std::istream& safeGetline(std::istream& is, std::string& t)
{
  t.clear();

  // The characters in the stream are read one-by-one using a
  // std::streambuf. That is faster than reading them one-by-one
  // using the std::istream.
  //
  // Code that uses streambuf this way must be guarded by a sentry
  // object.
  // The sentry object performs various tasks, such as thread
  // synchronization and updating the stream state.

  std::istream::sentry se(is, true);

  std::streambuf* sb = is.rdbuf();

  while (true) {
    int c = sb->sbumpc();

    switch (c) {

    case '\n':
      return is;

    case '\r':
      if (sb->sgetc() == '\n')
        sb->sbumpc();

      return is;

    case EOF:
      // Also handle the case when the last line has no line ending
      if (t.empty())
        is.setstate(std::ios::eofbit);

      return is;

    default:
      t += (char)c;
    }
  }
}

/// Reads a token (separated by whitespaces) from the file,
/// char by char, putting on `buf`
inline static void readToken() {
  buf = "";
  lastTokenLine = currentTokenLine;

  // Will read all chars until:
  //
  // - Finding a whitespace (or tab)
  // - Finding a comment
  // - Finding an end-of-line
  // - File somehow ends
  //
  while (true)
  {
    char c = f.get();

    if (!f.good())
      break;

    // comment found
    if (c == '/') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine;
        return;
      }

      // ignoring entire comment
      do {
        c = f.get();
      } while (c != '\n' && f.good());

      currentLine++;
      continue;
    }

    // line break found
    if (c == '\n') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine++;
        return;
      }

      currentLine++;
      continue;
    }

    // white space found
    if (c == ' ' || c == '\t') {

      // token was read
      if (buf.size()) {
        currentTokenLine = currentLine;
        return;
      }
      continue;
    }

    // this character was none of the above
    // simply appending it
    buf += c;
  }

  currentTokenLine = currentLine;
}

/// Returns text on `buf` as data.
///
/// Converts textual data to words.
/// For example, converts "0x1" to 1.
inline static uword_t parseData() {
  uword_t data = 0;
  if (buf[0] == '0' && buf[1] == 'x') { // for hex notation
    sscanf(buf.c_str(), "%i", &data);
  }
  else { // for decimal notation
    stringstream ss;
    ss << buf;
    ss >> data;
  }
  return data;
}

/// Parses a single field contained on `buf`.
///
/// So for `SUBLEQ A B C` we call this function three times,
/// once for each field A, B and C.
///
/// Returns the address being "called" by the field.
///
/// For example, if we have:
///
///     .data
///         one: 1
///     .text
///       loop:
///         one one loop
///
/// For `one` on `loop:` it returns 0, since it's the
/// address of the thing being "called" by the instruction.
///
inline static uword_t parseField() {
  uword_t field = 0;
  // hex notation means absolute address
  if (buf[0] == '0' && buf[1] == 'x') {
    sscanf(buf.c_str(), "%i", &field);
  }
  // symbol means an address that needs to be relocated later
  else {
    relatives.emplace(mem_size);

    // looking for array offset
    if (buf.find("+") != buf.npos) {
      string offset = buf.substr(buf.find("+") + 1, buf.size());
      buf = buf.substr(0, buf.find("+"));
      stringstream ss;
      ss << offset;
      ss >> field;
    }

    auto sym = symbols.find(buf);
    // symbol not found. leave a reference
    if (sym == symbols.end()) {
      references[buf].emplace(mem_size);
    }
    // symbol found. the field is the address of the symbol
    else {
      field = sym->second;
    }
  }
  return field;
}

int main(int argc, char* argv[]) {
  if (argc != 3) {
    fprintf(stderr, "Usage mode: subleq-asm <assembly_file> <object_file>\n");
    return 0;
  }

  fstream input_file(argv[1]);

  if (!input_file) {
    cout << "Input file '" << argv[1] << "' doesn't exist" << endl;
    return EXIT_FAILURE;
  }

  // Read the whole file and store on a buffer.
  //
  // This way we won't need to worry about specific
  // line-endings, since it will look like it only
  // has '\n'.
  while (true) {
    string str;
    safeGetline(input_file, str);
    f << (str + '\n');

    if (!input_file)
      break;
  }
  input_file.close();

  readToken(); // reading ".export"

  // reading export section
  for (readToken(); buf != ".data"; readToken()) {
    exported.insert(buf);
  }

  // reading data section
  for (readToken(); buf != ".text";) {
    symbols[buf.substr(0, buf.size() - 1)] = mem_size;
    readToken();
    if (buf == ".array") { // uninitialized array
      readToken();
      mem_size += parseData();
      readToken(); // next symbol
    }
    else if (buf == ".iarray") { // initialized array
      for (readToken(); currentTokenLine == lastTokenLine; readToken()) {
        mem[mem_size++] = parseData();
      }
    }
    else if (buf == ".ptr") { // pointer
      readToken();
      mem[mem_size] = parseField();
      mem_size++;
      readToken(); // next symbol
    }
    else { // initialized word
      mem[mem_size++] = parseData();
      readToken(); // next symbol
    }
  }

  // reading text section
  int field = 0;
  for (readToken(); buf.size();) {
    // field 2 omitted
    if (field == 2 && currentTokenLine != lastTokenLine) {
      relatives.emplace(mem_size);
      mem[mem_size] = mem_size + 1;
      mem_size++;
      field = (field + 1)%3;
    }
    // symbol found
    else if (buf[buf.size() - 1] == ':') {
      symbols[buf.substr(0, buf.size() - 1)] = mem_size;
      if (buf == "start:")
        exported.emplace("start");
      readToken();
    }
    // field 0, 1, or field 2 specified
    else {
      mem[mem_size] = parseField();
      mem_size++;
      field = (field + 1)%3;
      readToken();
    }
  }

  // Now we go through each symbol (label), resolving references.
  //
  // If it's not on this file (`symbols` map), we assume it's
  // found on other file (`references` map).
  //
  for (auto map_it = references.begin(); map_it != references.end(); ++map_it) {

    // Which symbol was referenced
    string symbol_name = map_it->first;

    // All addresses where the symbol above was referenced
    set<uword_t> symbol_called = map_it->second;

    // Is this symbol declared on this file?
    // If not then leave it be at `references`
    auto sym = symbols.find(symbol_name);

    if (sym == symbols.end())
      continue;

    // If it's on this file, we replace it's address on every
    // memory location that called it
    uword_t symbol_address = sym->second;

    for (auto it = symbol_called.begin(); it != symbol_called.end(); ++it)
      mem[*it] += symbol_address;

    // And remove it from the external reference map
    references.erase(map_it);
  }

  // Now, outputting the binary stuff
  fstream output_file(argv[2], fstream::out | fstream::binary);

  if (!output_file) {
    cout << "Couldn't write to file '" << argv[2] << "'" << endl;
    return EXIT_FAILURE;
  }

  {
    uword_t tmp;

    // write number of exported symbols
    tmp = exported.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write exported symbols
    for (auto& exp : exported) {
      // string
      output_file.write(exp.c_str(), exp.size() + 1);

      // address
      tmp = symbols[exp];
      output_file.write((const char*)&tmp, sizeof(uword_t));
    }

    // write number of symbols of pending references
    tmp = references.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write symbols of pending references
    for (auto& sym : references) {
      // string
      output_file.write(sym.first.c_str(), sym.first.size() + 1);

      // write number of references to current symbol
      tmp = sym.second.size();
      output_file.write((const char*)&tmp, sizeof(uword_t));

      // write references to current symbol
      for (auto ref : sym.second) {
        tmp = ref;
        output_file.write((const char*)&tmp, sizeof(uword_t));
      }
    }

    // write number of relative addresses
    tmp = relatives.size();
    output_file.write((const char*)&tmp, sizeof(uword_t));

    // write relative addresses
    for (auto addr : relatives) {
      tmp = addr;
      output_file.write((const char*)&tmp, sizeof(uword_t));
    }

    // write assembled code size
    output_file.write((const char*)&mem_size, sizeof(uword_t));

    // write assembled code
    output_file.write((const char*)mem, sizeof(uword_t)*mem_size);
  }

  output_file.close();

  delete[] mem;

  return 0;
}
<|endoftext|>


<commit_before>#include <CImg.h>
#include <json.hpp>
#include <boost/filesystem.hpp>
#include <vector>
#include <algorithm>
#include <math.h>
#include <iostream>

typedef std::vector<boost::filesystem::directory_entry> path_listing;

typedef std::vector<boost::filesystem::path> extension_list;

bool list_directory(const boost::filesystem::path root_directory,path_listing &files, path_listing &subdirectories, extension_list extensions)
{

  bool is_directory = true;

  if(boost::filesystem::exists(root_directory) && boost::filesystem::is_directory(root_directory))   {
    for(auto &entry: boost::filesystem::directory_iterator(root_directory))
      {
        if(boost::filesystem::is_directory(entry))
        {
          subdirectories.push_back(entry);
        }

        if(boost::filesystem::is_regular_file(entry) && std::find(extensions.begin(),extensions.end(),entry.path().extension()) != extensions.end())
        {
          files.push_back(entry);
        }
      }

  }else
  {
    is_directory = false;
  }

  return is_directory;

}

bool resize_pictures_in_directory(path_listing files, boost::filesystem::path output_directory, int new_width)
{
  if(!boost::filesystem::is_directory(output_directory))
  {
    return false;
  }

  int i = 0;

  for(auto &entry : files)
  {
   i++;
   std::string filepath = entry.path().string();

   cimg_library::CImg<uint8_t> img(filepath.c_str());
   double w = img.width();
   double h = img.height();

   double ratio = h/w;
   int new_height = floor(new_width * ratio);

   auto output_filepath = output_directory / entry.path().filename();
   std::string output_name(output_filepath.string());

   std::cout << "Resizing..." << output_name << std::endl;

   img.resize(new_width,new_height,1,3,6);
   img.save(output_name.c_str(),i,3);

  }

  return true;
}

int main(int argc, char** argv)
{

using json = nlohmann::json;

path_listing files, subdirectories;

extension_list allowed_extensions({".jpg",".jpeg",".JPG",".png",".PNG"});

list_directory(boost::filesystem::path(argv[1]),files, subdirectories, allowed_extensions);
resize_pictures_in_directory(files,boost::filesystem::path(argv[2]),std::stoi(argv[3]));

return 0;
}
<commit_msg>‼ Parallel resizing<commit_after>#include <CImg.h>
#include <json.hpp>
#include <boost/filesystem.hpp>
#include <vector>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <thread>

typedef std::vector<boost::filesystem::directory_entry> path_listing;

typedef std::vector<boost::filesystem::path> extension_list;

bool list_directory(const boost::filesystem::path root_directory,path_listing &files, path_listing &subdirectories, extension_list extensions)
{

  bool is_directory = true;

  if(boost::filesystem::exists(root_directory) && boost::filesystem::is_directory(root_directory))   {
    for(auto &entry: boost::filesystem::directory_iterator(root_directory))
      {
        if(boost::filesystem::is_directory(entry))
        {
          subdirectories.push_back(entry);
        }

        if(boost::filesystem::is_regular_file(entry) && std::find(extensions.begin(),extensions.end(),entry.path().extension()) != extensions.end())
        {
          files.push_back(entry);
        }
      }

  }else
  {
    is_directory = false;
  }

  return is_directory;

}

bool resize_pictures_in_directory(path_listing files, boost::filesystem::path output_directory, int new_width)
{
  if(!boost::filesystem::is_directory(output_directory))
  {
    return false;
  }

  int i = 0;

  for(auto &entry : files)
  {
   i++;
   std::string filepath = entry.path().string();

   cimg_library::CImg<uint8_t> img(filepath.c_str());
   double w = img.width();
   double h = img.height();

   double ratio = h/w;
   int new_height = floor(new_width * ratio);

   auto output_filepath = output_directory / entry.path().filename();
   std::string output_name(output_filepath.string());

   std::cout << "Resizing..." << output_name << std::endl;

   img.resize(new_width,new_height,1,3,6);
   img.save(output_name.c_str(),i,3);

  }

  return true;
}

bool parallel_resize(path_listing files, boost::filesystem::path output_directory, int new_width)
{

  size_t cores = std::thread::hardware_concurrency();

  int batch_size = files.size()/cores;
  int start = 0;
  int stop = batch_size;

  std::vector<std::thread> thread_pool;

  for(int p=0;p<cores;p++)
  {
    path_listing partitioned_files(files.begin()+start, files.begin()+stop);
    start += batch_size;
    stop += batch_size;

    thread_pool.push_back(std::thread(resize_pictures_in_directory,partitioned_files,output_directory,new_width));
    std::cout <<"NEWT" << std::endl;
  }

  for(auto &t : thread_pool)
  {
    t.join();
  }
  return true;

}

int main(int argc, char** argv)
{

using json = nlohmann::json;

path_listing files, subdirectories;

extension_list allowed_extensions({".jpg",".jpeg",".JPG",".png",".PNG"});

list_directory(boost::filesystem::path(argv[1]),files, subdirectories, allowed_extensions);
//resize_pictures_in_directory(files,boost::filesystem::path(argv[2]),std::stoi(argv[3]));
parallel_resize(files,boost::filesystem::path(argv[2]),std::stoi(argv[3]));

return 0;
}
<|endoftext|>


<commit_before>770e0391-2749-11e6-9716-e0f84713e7b8<commit_msg>Bug fixes and performance improvements<commit_after>771dee75-2749-11e6-a3cf-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "main.h"

void usage(char *e)
{
    puts("usage:");
    puts("  compression:");
    printf("    %s test.txt.compressed test.txt -c\n",e);
    printf("    %s test.txt.compressed test.txt -c -level 5\n",e);
    printf("    %s test.txt.compressed test.txt -c -lazy 128 -chain 100\n",e);
    puts("  uncompression:");
    printf("    %s test.txt test.txt.compressed -x\n",e);
    puts("  options:");
    puts("    c: compression");
    puts("    x: uncompression");
    printf("    level: compression level. 0 for store, %lu for highest compression ratio. default is %d\n",SIZEOF(config),DEFAULT_LEVEL);
    printf("    lazy : set max lazy match, default is %d\n",config[DEFAULT_LEVEL].lazy_match);
    printf("    chain: set max length of find in hash chain, default is %d\n",config[DEFAULT_LEVEL].max_chain);
    puts("    lazy and chain will be ignored if you setted level");
    exit(1);
}

int get_options(int argc,char **argv,const char *option)
{
    for(int i=1;i<argc;i++)if(argv[i][0]=='-'&&!strcmp(argv[i]+1,option))return i;
    return 0;
}
Config get_config(int argc,char **argv)
{
    int r;
    if((r=get_options(argc,argv,"level")))
    {
        int level=atoi(argv[r+1]);
        if(level<0)level=0;
        if(level>=SIZEOF(config))level=SIZEOF(config)-1;
        return config[level];
    }
    Config c=config[DEFAULT_LEVEL];
    if((r=get_options(argc,argv,"lazy")))c.lazy_match=atoi(argv[r+1]);
    if((r=get_options(argc,argv,"chain")))c.max_chain=atoi(argv[r+1]);
    return c;
}

int main(int argc,char **argv)
{
    if(argc<3||get_options(argc,argv,"h"))usage(argv[0]);
    bool isC=get_options(argc,argv,"c");
    bool isX=get_options(argc,argv,"x");
    if(isC&&isX)
    {
        fprintf(stderr,"-c and -x cannot exist at the same time\n");
        return 1;
    }
    if(!isC&&!isX)
    {
        fprintf(stderr,"please use -c to compression or -x to uncompression\n");
        return 1;
    }
    char *dest_file=argv[1];
    char *src_file=argv[2];
    FILE *src_fp=fopen(src_file,"r");
    if(!src_fp)
    {
        fprintf(stderr,"cannot open src file: %s\n",src_file);
        return 1;
    }
    FILE *dest_fp=fopen(dest_file,"w");
    if(!dest_fp)
    {
        fprintf(stderr,"cannot open dest file: %s\n",dest_file);
        return 1;
    }

    fseek(src_fp,0,SEEK_END);
    DWORD src_size=ftell(src_fp);
    if(src_size==0)
    {
        fprintf(stderr,"cannot compress empty file\n");
        fclose(src_fp);
        return 1;
    }
    BYTE *src=new BYTE[src_size];
    fseek(src_fp,0,SEEK_SET);
    fread(src,src_size,1,src_fp);
    fclose(src_fp);

    if(isC)
    {
        Config c=get_config(argc,argv);
        BYTE *buffer=new BYTE[getBufferSize(src_size)];
        puts("compressing...");
        DWORD compressed_size=compress(buffer,src,src_size,c.lazy_match,c.max_chain);
        puts("compression is complete");
        printf("original size: %u\n",src_size);
        printf("compressed size: %u\n",compressed_size+4);
        printf("compression ratio: %.2f\n",float(compressed_size+4)/src_size);
        fwrite(&src_size,4,1,dest_fp);
        fwrite(buffer,compressed_size,1,dest_fp);
        fclose(dest_fp);
        puts("saved.");
    }
    else
    {
        DWORD original_size=*(DWORD*)src;
        BYTE *buffer=new BYTE[original_size];
        puts("uncompressing...");
        uncompress(buffer,src+4);
        puts("uncompression is complete");
        printf("original size: %u\n",original_size);
        printf("compressed size: %u\n",src_size);
        printf("compression ratio: %.2f\n",float(src_size)/original_size);
        fwrite(buffer,original_size,1,dest_fp);
        fclose(dest_fp);
        puts("saved.");
    }
    return 0;
}
<commit_msg>fix incorrect max level 10 to 9<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "main.h"

void usage(char *e)
{
    puts("usage:");
    puts("  compression:");
    printf("    %s test.txt.compressed test.txt -c\n",e);
    printf("    %s test.txt.compressed test.txt -c -level 5\n",e);
    printf("    %s test.txt.compressed test.txt -c -lazy 128 -chain 100\n",e);
    puts("  uncompression:");
    printf("    %s test.txt test.txt.compressed -x\n",e);
    puts("  options:");
    puts("    c: compression");
    puts("    x: uncompression");
    printf("    level: compression level. 0 for store, %lu for highest compression ratio. default is %d\n",SIZEOF(config)-1,DEFAULT_LEVEL);
    printf("    lazy : set max lazy match, default is %d\n",config[DEFAULT_LEVEL].lazy_match);
    printf("    chain: set max length of find in hash chain, default is %d\n",config[DEFAULT_LEVEL].max_chain);
    puts("    lazy and chain will be ignored if you setted level");
    exit(1);
}

int get_options(int argc,char **argv,const char *option)
{
    for(int i=1;i<argc;i++)if(argv[i][0]=='-'&&!strcmp(argv[i]+1,option))return i;
    return 0;
}
Config get_config(int argc,char **argv)
{
    int r;
    if((r=get_options(argc,argv,"level")))
    {
        int level=atoi(argv[r+1]);
        if(level<0)level=0;
        if(level>=SIZEOF(config))level=SIZEOF(config)-1;
        return config[level];
    }
    Config c=config[DEFAULT_LEVEL];
    if((r=get_options(argc,argv,"lazy")))c.lazy_match=atoi(argv[r+1]);
    if((r=get_options(argc,argv,"chain")))c.max_chain=atoi(argv[r+1]);
    return c;
}

int main(int argc,char **argv)
{
    if(argc<3||get_options(argc,argv,"h"))usage(argv[0]);
    bool isC=get_options(argc,argv,"c");
    bool isX=get_options(argc,argv,"x");
    if(isC&&isX)
    {
        fprintf(stderr,"-c and -x cannot exist at the same time\n");
        return 1;
    }
    if(!isC&&!isX)
    {
        fprintf(stderr,"please use -c to compression or -x to uncompression\n");
        return 1;
    }
    char *dest_file=argv[1];
    char *src_file=argv[2];
    FILE *src_fp=fopen(src_file,"r");
    if(!src_fp)
    {
        fprintf(stderr,"cannot open src file: %s\n",src_file);
        return 1;
    }
    FILE *dest_fp=fopen(dest_file,"w");
    if(!dest_fp)
    {
        fprintf(stderr,"cannot open dest file: %s\n",dest_file);
        return 1;
    }

    fseek(src_fp,0,SEEK_END);
    DWORD src_size=ftell(src_fp);
    if(src_size==0)
    {
        fprintf(stderr,"cannot compress empty file\n");
        fclose(src_fp);
        return 1;
    }
    BYTE *src=new BYTE[src_size];
    fseek(src_fp,0,SEEK_SET);
    fread(src,src_size,1,src_fp);
    fclose(src_fp);

    if(isC)
    {
        Config c=get_config(argc,argv);
        BYTE *buffer=new BYTE[getBufferSize(src_size)];
        puts("compressing...");
        DWORD compressed_size=compress(buffer,src,src_size,c.lazy_match,c.max_chain);
        puts("compression is complete");
        printf("original size: %u\n",src_size);
        printf("compressed size: %u\n",compressed_size+4);
        printf("compression ratio: %.2f\n",float(compressed_size+4)/src_size);
        fwrite(&src_size,4,1,dest_fp);
        fwrite(buffer,compressed_size,1,dest_fp);
        fclose(dest_fp);
        puts("saved.");
    }
    else
    {
        DWORD original_size=*(DWORD*)src;
        BYTE *buffer=new BYTE[original_size];
        puts("uncompressing...");
        uncompress(buffer,src+4);
        puts("uncompression is complete");
        printf("original size: %u\n",original_size);
        printf("compressed size: %u\n",src_size);
        printf("compression ratio: %.2f\n",float(src_size)/original_size);
        fwrite(buffer,original_size,1,dest_fp);
        fclose(dest_fp);
        puts("saved.");
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int tab_width = 4;

int tsn(int xpos, int tsi) {	//lets try some
	int next_ts = ((xpos / tab_width) + 1) * tab_width;	//comments
	int spaces = (next_ts - xpos);	//inline
	return spaces;
}

struct LineType {
	int indent_level;
	vector<string> cell;
};

int next_stop(int pos) {
	return (pos / tab_width + 1) * tab_width;
}

string join(LineType line) {
	stringstream ss;
	int cur_width;

	int indent_width = tab_width * line.indent_level;
	ss <<string(indent_width, ' ');
	cur_width = indent_width;

	for (auto s : line.cell) {
		int w = cur_width + s.size();
	}

	return ss.str();
}

int main(int argc, char *argv[]) {
	if (argc == 2) tab_width = atoi(argv[1]);

	for (string line; getline(cin, line); ) {
		string::size_type pos;
		bool in_indent = true;
		int tsi = 0;
		int xpos = 0;

		stringstream ss;

		for (auto ch = line.begin(); ch != line.end(); ch++) {
			if (*ch == '\t') {
				int len = tsn(xpos, tsi);
				ss <<string(len, ' ');
				if (!in_indent) tsi++;
				xpos += len;
			} else {
				in_indent = false;
				xpos++;
				ss <<*ch;
			}
		}

		cout <<ss.str() <<endl;
	}
	return 0;
}
<commit_msg>debuggable<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;	//add

struct Line;
typedef string::size_type Width;	//some

int tab_width = 4;

struct Line {		//comments
	Line (string line) {	//to the file
		auto pos = line.begin();
		indent = 0;

		for (; pos < line.end() && *pos == '\t'; ++pos) indent++;

		auto last = pos;
		for (; pos < line.end(); ++pos) {
			if (*pos == '\t') {
				cell_widths.push_back(pos - last);
				cells.push_back(string(last, pos));
				last = pos;
			}
		}
		cells.push_back(string(last, pos));
	}
	int stop_count() { return indent + cell_widths.size(); }
	void print(vector<Width> stops) {
		Width leading_indent_size = tab_width * indent;
		auto cell = cells.begin();
		auto last_cell = cells.end();
		auto width_i = cell_widths.begin();
		auto last_width_i = cell_widths.end();
		Width w = leading_indent_size;

		if (leading_indent_size) cout <<string(leading_indent_size, ' ');
		if (!cells.empty()) {
			cout <<"~"; cout.flush();
			cout <<*cell;
			w += *width_i;
			cell++;
			width_i++;
		}
		cout <<"`"; cout.flush();

		if (!stops.empty()) {
			auto stop = stops.begin() + indent;
			while (cell < cells.end() && stop < stops.end()) {
				Width d = *stop - w;
				cout <<string(d, ' ');
				w = *stop;
				cout <<*cell;
				w += *(width_i++);
				cell++;
				stop++;
			}
		}
		cout <<"$" <<endl;
	}

	int indent;
	vector<Width> cell_widths;
	vector<string> cells;
};

struct Group {
	Group() : stop_count(-1) { }

	void reset() {
		lines.clear();
		cell_widths.clear();
		stop_count = -1;
	}

	void add_line(Line l) {
		if (l.stop_count() == stop_count) {
			lines.push_back(l);
			update_group_cell_widths(l);
		} else {
			lines.clear();
			set_group_cell_widths(l);
		}
	}

	void set_group_cell_widths(Line l) {
		cell_widths.clear();
		for (int i=0; i<l.indent; ++i) {
			cell_widths.push_back(0);
		}
		for (auto cw : l.cell_widths) {
			cell_widths.push_back(cw);
		}
	}

	void update_group_cell_widths(Line l) {
		int pos = l.indent;
		for (auto cw : l.cell_widths) {
			if (cw > cell_widths[pos]) cell_widths[pos] = cw;
			pos++;
		}
	};

	vector<Width> tabstops() {
		int xpos = 0;
		bool indent = true;
		vector<Width> ts;
		for (auto cell = cell_widths.begin(); cell < cell_widths.end(); cell++) {
			if (*cell == 0 && indent) {
				xpos += tab_width;
			} else if (*cell == 0) {
				xpos++;
			} else {
				xpos += *cell;
				indent = false;
			}
			ts.push_back(xpos);
		}
		return ts;
	}

	void print() {
		vector<Width> stops = tabstops();
		for (auto line : lines) {
			line.print(stops);
		}
	}

	vector<Width> cell_widths;
	vector<Line> lines;
	int stop_count;
};

int main(int argc, char *argv[]) {
	if (argc == 2) tab_width = atoi(argv[1]);

	Group g;

	for (string line; getline(cin, line); ) {
		Line l(line);

		if (g.stop_count == l.stop_count()) {
			cout <<"1: "; cout.flush();
			g.add_line(l);
		} else if (l.cells.size() <= 1) {
			cout <<"2: "; cout.flush();
			g.print();
			g.reset();
			l.print(vector<Width>());
		} else {
			cout <<"3: "; cout.flush();
			g.print();
			g.reset();
			g.add_line(l);
		}
	}
	g.print();
	return 0;
}
<|endoftext|>


<commit_before>83fa3297-4b02-11e5-a0c8-28cfe9171a43<commit_msg>Fix that bug where things didn't work but now they should<commit_after>84080d00-4b02-11e5-a3c1-28cfe9171a43<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include <execinfo.h>
#include "test/Problem.h"
#include "test/Timer.h"
#include <signal.h>

using namespace std;

struct Args {
    bool debug;
    bool optimized;
    int numThreads;
    int threadsPerQueue;
    int parallelFactor;
    double startParam;
    double endParam;
    int chunkSize;
};

void handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

Args parseArguments(int argc, const char *const *argv) {
    Args args;
    namespace po = boost::program_options;
    po::options_description desc("Divide & Conquer Framework demo");
    desc.add_options()
            ("debug,v", po::bool_switch(&args.debug)->default_value(false), "Display debug information")
            ("optimized,o", po::bool_switch(&args.optimized)->default_value(false), "Run optimized version")
            ("numThreads,n", po::value<int>(&args.numThreads)->default_value(1), "Number of threads")
            ("startParam,s", po::value<double>(&args.startParam)->default_value(0), "Start parameter")
            ("endParam,e", po::value<double>(&args.endParam)->default_value(100), "End parameter")
            ("threadsPerQueue,q", po::value<int>(&args.threadsPerQueue)->default_value(1),
             "Number of threads per queue (-o)")
            ("chunkSize,c", po::value<int>(&args.chunkSize)->default_value(1000),
             "Lock free factory chunk size (-o)")
            ("help,h", "Produce help message");
    ("parallelFactor,p", po::value<int>(&args.parallelFactor)->default_value(1), "Num task gained at once per thread.");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help")) {
        cout << desc << "\n";
        exit (0);
    }
    return args;
}

/**
 * usage
 * program [base_or_optimized] [numThreads] [threadsPerQueue] [parallelFactor]
 */
int main(int argc, char **argv) {
    signal(SIGSEGV, handler);   // install our handler
    Args config = parseArguments(argc, argv);

    IntProblem p;
    AbstractProblemSolver<IntParam, IntResult> *solver;
    if (!config.optimized) {
        cout << "\nrunning base solver";
        solver = new BaseProblemSolver<IntParam, IntResult>(p, config.numThreads);
    }
    else {
        cout << "\nrunning optimized solver";
        solver = new OptimizedProblemSolver<IntParam, IntResult>(p, config.numThreads, config.threadsPerQueue,
                                                                 config.parallelFactor, config.chunkSize);
    }

    // common config
    solver->debug = config.debug;

    // execution
    Timer timer;
    ThreadStats &threadStats = solver->getThreadStats();
    timer.start();
    IntResult d = solver->process({config.startParam, config.endParam});
    timer.stop();

    threadStats.calculate();
    cout << "\nresult: " << d
    << "\nduration: " << timer.getDurationString()
    << "\naverage load: " << threadStats.getAverage()
    << "\nstd deviation: " << threadStats.getStdDeviation()
    << "\n";

    // cleanup
    delete solver;
    return 0;
}<commit_msg>added initialQueueSize parameter<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include <execinfo.h>
#include "test/Problem.h"
#include "test/Timer.h"
#include <signal.h>

using namespace std;

struct Args {
    bool debug;
    bool optimized;
    int numThreads;
    int threadsPerQueue;
    int parallelFactor;
    double startParam;
    double endParam;
    int chunkSize;
    int initialQueueSize;
};

void handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

Args parseArguments(int argc, const char *const *argv) {
    Args args;
    namespace po = boost::program_options;
    po::options_description desc("Divide & Conquer Framework demo", 100);
    desc.add_options()

            ("debug,v", po::bool_switch(&args.debug)->default_value(false), "Display debug information")
            ("optimized,o", po::bool_switch(&args.optimized)->default_value(false), "Run optimized version")
            ("numThreads,n", po::value<int>(&args.numThreads)->default_value(1), "Number of threads")
            ("startParam,s", po::value<double>(&args.startParam)->default_value(0), "Start parameter")
            ("endParam,e", po::value<double>(&args.endParam)->default_value(100), "End parameter")
            ("threadsPerQueue,q", po::value<int>(&args.threadsPerQueue)->default_value(1), "Number of threads per queue (-o)")
            ("parallelFactor,p", po::value<int>(&args.parallelFactor)->default_value(1), "Num task gained at once per thread")
            ("chunkSize,c", po::value<int>(&args.chunkSize)->default_value(10000), "Lock free factory chunk size (-o)")
            ("initialQueueSize,i", po::value<int>(&args.initialQueueSize)->default_value(10000), "Initial size of lock-free queue (-o)")
            ("help,h", "Produce help message");

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help")) {
        cout << desc << "\n";
        exit(0);
    }
    return args;
}

/**
 * usage
 * program [base_or_optimized] [numThreads] [threadsPerQueue] [parallelFactor]
 */
int main(int argc, char **argv) {
    signal(SIGSEGV, handler);   // install our handler
    Args config = parseArguments(argc, argv);

    IntProblem p;
    AbstractProblemSolver<IntParam, IntResult> *solver;
    if (!config.optimized) {
        cout << "\nrunning base solver";
        solver = new BaseProblemSolver<IntParam, IntResult>(p, config.numThreads);
    }
    else {
        cout << "\nrunning optimized solver";
        solver = new OptimizedProblemSolver<IntParam, IntResult>(p, config.numThreads, config.threadsPerQueue,
                                                                 config.parallelFactor, config.chunkSize);
    }

    // common config
    solver->debug = config.debug;

    // execution
    Timer timer;
    ThreadStats &threadStats = solver->getThreadStats();
    timer.start();
    IntResult d = solver->process({config.startParam, config.endParam});
    timer.stop();

    threadStats.calculate();
    cout << "\nresult: " << d
    << "\nduration: " << timer.getDurationString()
    << "\naverage load: " << threadStats.getAverage()
    << "\nstd deviation: " << threadStats.getStdDeviation()
    << "\n";

    // cleanup
    delete solver;
    return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <sstream>
using namespace std;

//TODO:
//  Add execute functionality to both classes
//  Write function to delete everything after a # (fix comments)

class Shell{
    public:
        Shell* first;
        Shell* second;
        Shell(){};
        virtual bool execute() = 0;
};

class Connector : public Shell{
    public:
        // Shell* first;
        // Shell* second;
        Connector() : Shell(){};
        Connector(Shell* f, Shell* s){
            first = f;
            second = s;
        };
        virtual bool execute() = 0; // for compiler
};

class Bars : public Connector{
    public:
        Bars() : Connector (){};
        Bars(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            if(!first->execute()){
                return second->execute();
            }
            return true;
        }
};

class Semi : public Connector{
    public:
        Semi() : Connector (){};
        Semi(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            cout << "first: " << &first << endl;
            cout << "second: " << &second << endl;
            first->execute();
            return second->execute();
        }
};

class Amp : public Connector{
    public:
        Amp() : Connector (){};
        Amp(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            if(first->execute()){
                return second->execute();
            }
            return false; // else
        }
};

class Command : public Shell{
    public:
        const char* cmd;
        vector<string> args;
        Command() : Shell(){};
        Command(char c[], vector<string> a) : Shell(), cmd(c), args(a) {};
        bool execute(){
            cout << "Executed Command: " << cmd << endl;
            return true;

        // //real execute
        // pid_t pid;
        // int status;
        // //forks the process
        // if((pid = fork()) < 0){ //if fork() failed
        //     cout << "Error: fork failed" << endl;
        //     return false;
        // }
        // else if(pid == 0){ //if this is the child process

        // }
        // else{ //if it is the parent process
        //     while()
        // }
    }
};

Shell* stringToCommand(string commandLine){
    cout << "starting stringToCommand" << endl;
    stringstream ss;
    ss << commandLine;
    // //sets up everything to use stringstream
    //builds new command
    Shell* temp = new Command;
    string tempString;
    ss >> tempString;
    temp->cmd = tempString.c_str();
    cout << "cmd parsed: " << tempString << endl;
    //takes in any potential arguments
    while(ss >> tempString){
        temp->args.push_back(tempString);
    }
    return temp;
}

void parse(string commandLine){

    Shell* top = NULL;
    for(unsigned i = 0; i < commandLine.size(); ++i){
        string temp;
        if(commandLine.at(i) == ';'){
            //make substr
            temp = commandLine.substr(0, i);
            //delete what we took
            commandLine.erase(0, i + 1);
            //reset i
            i = 0;
            //issue where it never enteres the first if statement
            if(top == NULL){
                Shell* connect = new Semi;
                top = connect;
                //Shell*
                connect->first = stringToCommand(temp);
            }
            else{
                Shell* connect = new Semi;
                connect->first = top;
                top->second = stringToCommand(temp);
                top = connect;
            }
        }
        else if(commandLine.at(i) == '|'){
            if(commandLine.at(i + 1) == '|'){
                //make substr
                temp = commandLine.substr(0, i);
                //delete what we took
                commandLine.erase(0, i + 2);    //see below for deleting both connectors
                //reset i
                i = 0;
                if(top == NULL){
                    Shell* connect = new Bars;
                    top = connect;
                    connect->first = stringToCommand(temp);
                    top->execute();
                }
                else{
                    Shell* connect = new Bars;
                    connect->first = top;
                    top->second = stringToCommand(temp);
                    top = connect;
                }
            }
        }
        else if(commandLine.at(i) == '&'){
            if(commandLine.at(i + 1) == '&'){
                //make substr
                temp = commandLine.substr(0, i);
                //delete what we took
                commandLine.erase(0, i + 2);    //need to change it so that it deletes both connectors
                //reset i
                i = 0;
                if(top == NULL){
                    Shell* connect = new Amp;
                    top = connect;
                    connect->first = stringToCommand(temp);
                }
                else{
                    Shell* connect = new Amp;
                    connect->first = top;
                    top->second = stringToCommand(temp);
                    top = connect;
                }
            }
        }
    }
    string temp = commandLine;
    if(top == NULL){
        top = stringToCommand(temp);
    }
    else{
        top->second = stringToCommand(temp);
    }
    top->execute();
}

int main() {
    string commandLine;
    while(commandLine != "exit"){
        cout << '$';
        getline(cin, commandLine);
        parse(commandLine);
    }
    return 0;
}
// change
<commit_msg>i commented changes at the bottom<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <sstream>
using namespace std;

//TODO:
//  Add execute functionality to both classes
//  Write function to delete everything after a # (fix comments)

class Shell{
    public:
        Shell* first;
        Shell* second;
        Shell(){};
        virtual bool execute() = 0;
};

class Connector : public Shell{
    public:
        // Shell* first;
        // Shell* second;
        Connector() : Shell(){};
        Connector(Shell* f, Shell* s){
            first = f;
            second = s;
        };
        virtual bool execute() = 0; // for compiler
};

class Bars : public Connector{
    public:
        Bars() : Connector (){};
        Bars(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            if(!first->execute()){
                return second->execute();
            }
            return true;
        }
};

class Semi : public Connector{
    public:
        Semi() : Connector (){};
        Semi(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            first->execute();
            return second->execute();
        }
};

class Amp : public Connector{
    public:
        Amp() : Connector (){};
        Amp(Shell* f, Shell* s) : Connector(f, s){};
        bool execute(){
            if(first->execute()){
                return second->execute();
            }
            return false; // else
        }
};

class Command : public Shell{
    public:
        string cmd; // is it becuase you're trying to change a const?
        vector<string> args;
        Command() : Shell(){};
        Command(string c, vector<string> a) : Shell(), cmd(c), args(a) {};
        bool execute(){
            cout << "Executed Command: " << (const char *)cmd.c_str() << endl;
            return true;

        // //real execute
        // pid_t pid;
        // int status;
        // //forks the process
        // if((pid = fork()) < 0){ //if fork() failed
        //     cout << "Error: fork failed" << endl;
        //     return false;
        // }
        // else if(pid == 0){ //if this is the child process

        // }
        // else{ //if it is the parent process
        //     while()
        // }
    }
};

Shell* stringToCommand(string commandLine){
    stringstream ss;
    ss << commandLine;
    // //sets up everything to use stringstream
    //builds new command
    Command* temp = new Command;
    string tempString;
    ss >> tempString;
    temp->cmd = tempString;
    //takes in any potential arguments
    while(ss >> tempString){
        temp->args.push_back(tempString);
    }
    return temp;
}

void parse(string commandLine){

    Shell* top = NULL;
    for(unsigned i = 0; i < commandLine.size(); ++i){
        string temp;
        if(commandLine.at(i) == ';'){
            //make substr
            temp = commandLine.substr(0, i); // didn't include actual character
            //delete what we took
            commandLine.erase(0, i + 1);
            //reset i
            i = 0;
            //issue where it never enteres the first if statement
            if(top == NULL){
                Shell* connect = new Semi;
                top = connect;
                //Shell*
                connect->first = stringToCommand(temp);
            }
            else{
                Shell* connect = new Semi;
                connect->first = top;
                top->second = stringToCommand(temp);
                top = connect;
            }
        }
        else if(commandLine.at(i) == '|'){
            if(commandLine.at(i + 1) == '|'){
                //make substr
                temp = commandLine.substr(0, i);
                //delete what we took
                commandLine.erase(0, i + 2);    //see below for deleting both connectors
                //reset i
                i = 0;
                if(top == NULL){
                    Shell* connect = new Bars;
                    top = connect;
                    connect->first = stringToCommand(temp);
                    top->execute();
                }
                else{
                    Shell* connect = new Bars;
                    connect->first = top;
                    top->second = stringToCommand(temp);
                    top = connect;
                }
            }
        }
        else if(commandLine.at(i) == '&'){
            if(commandLine.at(i + 1) == '&'){
                //make substr
                temp = commandLine.substr(0, i);
                //delete what we took
                commandLine.erase(0, i + 2);    //need to change it so that it deletes both connectors
                //reset i
                i = 0;
                if(top == NULL){
                    Shell* connect = new Amp;
                    top = connect;
                    connect->first = stringToCommand(temp);
                }
                else{
                    Shell* connect = new Amp;
                    connect->first = top;
                    top->second = stringToCommand(temp);
                    top = connect;
                }
            }
        }
    }
    string temp = commandLine;
    if(top == NULL){
        top = stringToCommand(temp);
    }
    else{
        top->second = stringToCommand(temp);
    }
    top->execute();
}

int main() {
    string commandLine;
    while(cout << '$' && getline(cin, commandLine) && commandLine != "exit"){
        parse(commandLine);
    }
    return 0;
}
// changes made: changed while loop to exit correctly
// fixed problem. i think it had to do with polymorphism
// basically, just store cmd as a string. and when you want to use it
// cast it as (const char *)cmd.c_str()
<|endoftext|>


<commit_before>#include <array>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>

namespace {

const size_t BLOCK_LEN = 200; // Number ui64 in block

template<typename T, size_t BLOCK_SIZE>
class TExtMatrix {
public:
    TExtMatrix(const char* filename, size_t bytesOffset, size_t rows, size_t cols)
        : File(filename, std::fstream::in | std::fstream::binary)
        , Offset(bytesOffset)
        , Rows(rows)
        , Cols(cols)
    {
    }

    size_t RowsDiff() const {
        return (Cols < BLOCK_SIZE) ? (BLOCK_SIZE * BLOCK_SIZE / Cols) : BLOCK_SIZE;
    }

    size_t ColsDiff() const {
        return (Rows < BLOCK_SIZE) ? (BLOCK_SIZE * BLOCK_SIZE / Rows) : BLOCK_SIZE;
    }

    void Read(size_t leftCol, size_t upperRow) {
        if (LeftCacheCol == leftCol && UpperCacheRow == upperRow) {
            return;
        }
        if (leftCol >= Cols || upperRow >= Rows) {
            throw std::out_of_range("Tried to read with starting point out of bounds.");
        }
        LeftCacheCol = leftCol;
        UpperCacheRow = upperRow;
        BufferWidthUsed = std::min(ColsDiff(), Cols - leftCol);
        BufferHeightUsed = std::min(RowsDiff(), Rows - upperRow);

        size_t lineSize = BufferWidthUsed * sizeof(T);
        size_t upperLeftOffset = Offset + (UpperCacheRow * Cols + LeftCacheCol) * sizeof(T);
        char* bufferPtr = (char*)Buffer.data();
        bool skipPerRowSeek = (BufferWidthUsed == Cols);
        if (skipPerRowSeek) {
            File.seekg(upperLeftOffset, File.beg);
            File.read(bufferPtr, lineSize * BufferHeightUsed);
        } else {
            for (size_t row = 0; row < BufferHeightUsed; ++row) {
                File.seekg(upperLeftOffset + row * Cols * sizeof(T), File.beg);
                File.read(bufferPtr, lineSize);
                bufferPtr += lineSize;
            }
        }
    }

    void DebugPrint() const {
        auto bufferPtr = Buffer.data();
        for (size_t row = 0; row < BufferHeightUsed; ++row) {
            for (size_t col = 0; col < BufferWidthUsed; ++col, ++bufferPtr) {
                std::cout << (size_t)*bufferPtr << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }

    void WriteTransponsed(std::ofstream& output) {
        size_t upperLeftOffset = Offset + (LeftCacheCol * Rows + UpperCacheRow) * sizeof(T);
        if (Cols == 1 || Rows == 1) {
            output.seekp(upperLeftOffset, output.beg);
            output.write((char*)Buffer.data(), sizeof(T) * BufferWidthUsed * BufferHeightUsed);
            return;
        }
        output.seekp(upperLeftOffset, output.beg);
        bool skipPerColSeek = (BufferHeightUsed == Rows);
        for (size_t col = 0; col < BufferWidthUsed; ++col) {
            if (!skipPerColSeek) {
                output.seekp(upperLeftOffset + col * Rows * sizeof(T), output.beg);
            }
            for (size_t row = 0; row < BufferHeightUsed; ++row) {
                output.write((char*)(Buffer.data() + col + row * BufferWidthUsed), sizeof(T));
            }
        }
    }

private:
    std::array<T, BLOCK_SIZE * BLOCK_SIZE> Buffer;
    std::fstream File;
    size_t Offset;
    size_t Rows;
    size_t Cols;

    size_t LeftCacheCol = -1;
    size_t UpperCacheRow = -1;
    size_t BufferWidthUsed = 0;
    size_t BufferHeightUsed = 0;
};

void ReadInputShape(const char* path, uint32_t* rows, uint32_t* cols) {
    std::fstream input(path, std::fstream::in | std::fstream::binary);
    input.read((char*)rows, sizeof(*rows));
    input.read((char*)cols, sizeof(*cols));
}

std::ofstream InitOutputFile(const char* path, uint32_t rows, uint32_t cols) {
    std::ofstream output(path, std::fstream::binary);
    output.seekp(2 * sizeof(rows) + rows * cols * sizeof(uint8_t) - 1, output.beg);
    output.put(0);
    output.seekp(0, output.beg);
    output.write((char*)&rows, sizeof(rows));
    output.write((char*)&cols, sizeof(cols));
    return output;
}

} // anonymous namespace

int main() {
    uint32_t rowsCount = 0;
    uint32_t colsCount = 0;
    ReadInputShape("input.bin", &rowsCount, &colsCount);
    TExtMatrix<uint8_t, BLOCK_LEN> matrix("input.bin", 2 * sizeof(rowsCount), rowsCount, colsCount);
    auto outputFile = InitOutputFile("output.bin", colsCount, rowsCount);
    if (colsCount == 1 || rowsCount == 1) {

    }
    for (size_t upperRow = 0; upperRow < rowsCount; upperRow += matrix.RowsDiff()) {
        for (size_t leftCol = 0; leftCol < colsCount; leftCol += matrix.ColsDiff()) {
            matrix.Read(leftCol, upperRow);
            matrix.WriteTransponsed(outputFile);
        }
    }
    return 0;
}<commit_msg>Cleanup<commit_after>#include <array>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>

namespace {

const size_t BLOCK_LEN = 200; // Number ui64 in block

template<typename T, size_t BLOCK_SIZE>
class TExtMatrix {
public:
    TExtMatrix(const char* filename, size_t bytesOffset, size_t rows, size_t cols)
        : File(filename, std::fstream::in | std::fstream::binary)
        , Offset(bytesOffset)
        , Rows(rows)
        , Cols(cols)
    {
    }

    size_t RowsDiff() const {
        return (Cols < BLOCK_SIZE) ? (BLOCK_SIZE * BLOCK_SIZE / Cols) : BLOCK_SIZE;
    }

    size_t ColsDiff() const {
        return (Rows < BLOCK_SIZE) ? (BLOCK_SIZE * BLOCK_SIZE / Rows) : BLOCK_SIZE;
    }

    void Read(size_t leftCol, size_t upperRow) {
        if (LeftCacheCol == leftCol && UpperCacheRow == upperRow) {
            return;
        }
        if (leftCol >= Cols || upperRow >= Rows) {
            throw std::out_of_range("Tried to read with starting point out of bounds.");
        }
        LeftCacheCol = leftCol;
        UpperCacheRow = upperRow;
        BufferWidthUsed = std::min(ColsDiff(), Cols - leftCol);
        BufferHeightUsed = std::min(RowsDiff(), Rows - upperRow);

        size_t lineSize = BufferWidthUsed * sizeof(T);
        size_t upperLeftOffset = Offset + (UpperCacheRow * Cols + LeftCacheCol) * sizeof(T);
        char* bufferPtr = (char*)Buffer.data();
        bool skipPerRowSeek = (BufferWidthUsed == Cols);
        if (skipPerRowSeek) {
            File.seekg(upperLeftOffset, File.beg);
            File.read(bufferPtr, lineSize * BufferHeightUsed);
        } else {
            for (size_t row = 0; row < BufferHeightUsed; ++row) {
                File.seekg(upperLeftOffset + row * Cols * sizeof(T), File.beg);
                File.read(bufferPtr, lineSize);
                bufferPtr += lineSize;
            }
        }
    }

    void DebugPrint() const {
        auto bufferPtr = Buffer.data();
        for (size_t row = 0; row < BufferHeightUsed; ++row) {
            for (size_t col = 0; col < BufferWidthUsed; ++col, ++bufferPtr) {
                std::cout << (size_t)*bufferPtr << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }

    void WriteTransponsed(std::ofstream& output) {
        size_t upperLeftOffset = Offset + (LeftCacheCol * Rows + UpperCacheRow) * sizeof(T);
        if (Cols == 1 || Rows == 1) {
            output.seekp(upperLeftOffset, output.beg);
            output.write((char*)Buffer.data(), sizeof(T) * BufferWidthUsed * BufferHeightUsed);
            return;
        }
        output.seekp(upperLeftOffset, output.beg);
        bool skipPerColSeek = (BufferHeightUsed == Rows);
        for (size_t col = 0; col < BufferWidthUsed; ++col) {
            if (!skipPerColSeek) {
                output.seekp(upperLeftOffset + col * Rows * sizeof(T), output.beg);
            }
            for (size_t row = 0; row < BufferHeightUsed; ++row) {
                output.write((char*)(Buffer.data() + col + row * BufferWidthUsed), sizeof(T));
            }
        }
    }

private:
    std::array<T, BLOCK_SIZE * BLOCK_SIZE> Buffer;
    std::fstream File;
    size_t Offset;
    size_t Rows;
    size_t Cols;

    size_t LeftCacheCol = -1;
    size_t UpperCacheRow = -1;
    size_t BufferWidthUsed = 0;
    size_t BufferHeightUsed = 0;
};

void ReadInputShape(const char* path, uint32_t* rows, uint32_t* cols) {
    std::fstream input(path, std::fstream::in | std::fstream::binary);
    input.read((char*)rows, sizeof(*rows));
    input.read((char*)cols, sizeof(*cols));
}

std::ofstream InitOutputFile(const char* path, uint32_t rows, uint32_t cols) {
    std::ofstream output(path, std::fstream::binary);
    output.seekp(2 * sizeof(rows) + rows * cols * sizeof(uint8_t) - 1, output.beg);
    output.put(0);
    output.seekp(0, output.beg);
    output.write((char*)&rows, sizeof(rows));
    output.write((char*)&cols, sizeof(cols));
    return output;
}

} // anonymous namespace

int main() {
    uint32_t rowsCount = 0;
    uint32_t colsCount = 0;
    ReadInputShape("input.bin", &rowsCount, &colsCount);
    TExtMatrix<uint8_t, BLOCK_LEN> matrix("input.bin", 2 * sizeof(rowsCount), rowsCount, colsCount);
    auto outputFile = InitOutputFile("output.bin", colsCount, rowsCount);
    for (size_t upperRow = 0; upperRow < rowsCount; upperRow += matrix.RowsDiff()) {
        for (size_t leftCol = 0; leftCol < colsCount; leftCol += matrix.ColsDiff()) {
            matrix.Read(leftCol, upperRow);
            matrix.WriteTransponsed(outputFile);
        }
    }
    return 0;
}<|endoftext|>


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

int g_world_size;
int g_mpi_rank;
int g_global_max_id = 125000000;
int g_local_max_id;
std::map<int, std::set<int>> g_adj_list;

void parse_file();
void add_to_adjlist(std::string line);

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);

  // Print off a hello world message
  parse_file();
  printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  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;
}

void parse_file(){
  printf("parsing the file...\n");
  g_local_max_id = ceil((float)g_global_max_id / g_world_size)*(g_mpi_rank+1);
  printf("maximum id = %d\n", g_local_max_id);
  char filename[100];

  sprintf(filename, "com-friendster.ungraph.txt");
  //sprintf(filename, "/gpfs/u/home/PCP5/PCP5stns/scratch-shared/friendster_data/friends-%s%d______.txt", padding.c_str(), g_file);
  //printf("rank: %d  %s\n", g_mpi_rank, filename);

  MPI_File infile;
  MPI_File_open(MPI_COMM_SELF, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
  MPI_Offset filesize = 0;
  MPI_File_get_size(infile, &filesize);

  //printf("rank %d: %lld\n", g_mpi_rank, filesize);
  printf("rank %d: opened the file! %lld\n", g_mpi_rank, filesize);

  char * buffer;
  std::string chunk = "";
  unsigned int buffer_size = 1000;
  MPI_Offset offset = 124; // get rid of the stuff at the top of the file

  while(offset < filesize){
   buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
   // read it in
   MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
   offset += buffer_size;
   // end the string
   buffer[buffer_size] = '\0';
   std::string new_string(buffer);
   free(buffer);
   chunk += new_string;
   //std::cout << chunk << std::endl;;

   int found_newline = chunk.find('\n');

   while (found_newline < chunk.size()){
    std::string line = chunk.substr(0, found_newline);
    add_to_adjlist(line);
    chunk = chunk.substr(found_newline+1);
    found_newline = chunk.find('\n');
  }
 }

  MPI_File_close(&infile);
}

void add_to_adjlist(std::string line){
  //std::cout << "adding: " << line << " to adj list" << std::endl;
  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());
  if (one % 10000 == 0){
    std::cout << one << std::endl;
  }
  if (one < g_local_max_id){
    g_adj_list[one].insert(two);
    //printf("(ONE) Adding %d -> %d\n", one, two);
  }else if (two < g_local_max_id){
    g_adj_list[two].insert(one);
    //sprintf("(TWO) Adding %d -> %d\n", two, one);
  }
}
<commit_msg>blue gene changes<commit_after>#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>

int g_world_size;
int g_mpi_rank;
int g_global_max_id = 125000000;
int g_local_max_id;
std::map<int, std::set<int>> g_adj_list;

void parse_file();
void add_to_adjlist(std::string line);

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);

  // Print off a hello world message
  parse_file();
  printf("Rank: %d    g_adj_list.size(): %lu\n", g_mpi_rank, g_adj_list.size());
  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;
}

void parse_file(){
  printf("parsing the file...\n");
  g_local_max_id = ceil((float)g_global_max_id / g_world_size)*(g_mpi_rank+1);
  printf("maximum id = %d\n", g_local_max_id);
  char filename[100];

  //sprintf(filename, "com-friendster.ungraph.txt");
  sprintf(filename, "/gpfs/u/home/PCP5/PCP5stns/scratch-shared/com-friendster.ungraph.txt");
  //printf("rank: %d  %s\n", g_mpi_rank, filename);

  MPI_File infile;
  MPI_File_open(MPI_COMM_SELF, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &infile);
  MPI_Offset filesize = 0;
  MPI_File_get_size(infile, &filesize);

  //printf("rank %d: %lld\n", g_mpi_rank, filesize);
  printf("rank %d: opened the file! %lld\n", g_mpi_rank, filesize);

  char * buffer;
  std::string chunk = "";
  unsigned int buffer_size = 1000;
  MPI_Offset offset = 124; // get rid of the stuff at the top of the file

  while(offset < filesize){
   buffer = (char *)malloc( (buffer_size + 1)*sizeof(char));
   // read it in
   MPI_File_read_at(infile, offset, buffer, buffer_size, MPI_CHAR, MPI_STATUS_IGNORE);
   offset += buffer_size;
   // end the string
   buffer[buffer_size] = '\0';
   std::string new_string(buffer);
   free(buffer);
   chunk += new_string;
   //std::cout << chunk << std::endl;;

   int found_newline = chunk.find('\n');

   while (found_newline < chunk.size()){
    std::string line = chunk.substr(0, found_newline);
    add_to_adjlist(line);
    chunk = chunk.substr(found_newline+1);
    found_newline = chunk.find('\n');
  }
 }

  MPI_File_close(&infile);
}

void add_to_adjlist(std::string line){
  //std::cout << "adding: " << line << " to adj list" << std::endl;
  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());
  if (g_mpi_rank == 0 && one % 1000000 == 0){
    std::cout << one << std::endl;
  }
  if (one < g_local_max_id){
    g_adj_list[one].insert(two);
    //printf("(ONE) Adding %d -> %d\n", one, two);
  }else if (two < g_local_max_id){
    g_adj_list[two].insert(one);
    //sprintf("(TWO) Adding %d -> %d\n", two, one);
  }
}
<|endoftext|>


<commit_before>#include <string.h>
#include "Lcd.hpp"
#include "DistanceSensor.hpp"

#define ECHO 30
#define TRIG 31
DistanceSensor sensor(TRIG, ECHO);
Lcd &lcd = Lcd::getInstance();

void setup()
{
}

void dist_test()
{
   double distCm = sensor.getDistanceCm();
   double distIn = sensor.getDistanceIn();
   lcd.home();
   lcd.print(distCm);
   lcd.print(" cm");
   lcd.setCursor(0, 1);
   lcd.print(distIn);
   lcd.print(" in");
   delay(60);     // 60ms between measurements
}

void loop()
{
   lcd.clear();

   dist_test();

   delay(1000);
}
<commit_msg>I hate avr-gcc<commit_after>#include <string.h>
#include "Lcd.hpp"
#include "DistanceSensor.hpp"

#define ECHO 30
#define TRIG 31
DistanceSensor sensor(TRIG, ECHO);

void setup()
{
}

void dist_test()
{
   double distCm = sensor.getDistanceCm();
   double distIn = sensor.getDistanceIn();
   Lcd::getInstance().home();
   Lcd::getInstance().print(distCm);
   Lcd::getInstance().print(" cm");
   Lcd::getInstance().setCursor(0, 1);
   Lcd::getInstance().print(distIn);
   Lcd::getInstance().print(" in");
   delay(60);     // 60ms between measurements
}

void loop()
{
   Lcd::getInstance().clear();

   dist_test();

   delay(1000);
}
<|endoftext|>


<commit_before>#include <iostream>
#include "TestSuite.h"

using namespace std;

//define EXECUTE_TEST_SUITE to run tests
//#define TESTING

#ifndef TESTING
int main() {
	cout << "Normal program execution.." << endl;
	cin.get();
}
#else
int main() {
	EXECUTE_TEST_SUITE();
}
#endif
<commit_msg>updated comments<commit_after>#include <iostream>
#include "TestSuite.h"

using namespace std;

//define TESTING to run tests
//#define TESTING

#ifndef TESTING
int main() {
	cout << "Normal program execution.." << endl;
	cin.get();
}
#else
int main() {
	EXECUTE_TEST_SUITE();
}
#endif
<|endoftext|>


<commit_before>#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Lex/Preprocessor.h"

#include <iostream>
#include <sstream>

using namespace clang;
using namespace clang::tooling;

std::string escapeString(std::string const& input)
{
    std::ostringstream ss;
    for (auto c : input)
    {
        switch (c)
        {
        case '\\':
            ss << "\\\\";
            break;
        case '"':
            ss << "\\\"";
            break;
        case '/':
            ss << "\\/";
            break;
        case '\b':
            ss << "\\b";
            break;
        case '\f':
            ss << "\\f";
            break;
        case '\n':
            ss << "\\n";
            break;
        case '\r':
            ss << "\\r";
            break;
        case '\t':
            ss << "\\t";
            break;
        default:
            ss << c;
            break;
        }
    }
    return ss.str();
}

class DumpVisitor : public RecursiveASTVisitor<DumpVisitor>
{
  public:
    explicit DumpVisitor(ASTContext* context) : context(context) {}

    void TraverseNewScope(Stmt* stmt)
    {
        if (!isa<CompoundStmt>(stmt))
        {
            depth++;
            WriteDepth();
        }

        TraverseStmt(stmt);

        if (!isa<CompoundStmt>(stmt))
        {
            std::cout << "\n";
            depth--;
        }
    }

    bool TraverseStmt(Stmt* stmt)
    {
        if (!stmt)
            return RecursiveASTVisitor::TraverseStmt(stmt);

        if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt))
        {
            depth++;
            for (auto stmt : compoundStmt->body())
            {
                if (!stmt)
                    continue;

                WriteDepth();
                TraverseStmt(stmt);
                std::cout << "\n";
            }
            depth--;
            return true;
        }

        if (auto callExpr = dyn_cast<CallExpr>(stmt))
        {
            TraverseStmt(callExpr->getCallee());
            bool first = true;
            std::cout << "(";
            for (auto param : callExpr->arguments())
            {
                if (!first)
                    std::cout << ", ";

                TraverseStmt(param);
                first = false;
            }
            std::cout << ")";
            return true;
        }

        if (auto ifStmt = dyn_cast<IfStmt>(stmt))
        {
            std::cout << "if ";
            TraverseStmt(ifStmt->getCond());
            std::cout << " then\n";

            TraverseNewScope(ifStmt->getThen());

            WriteDepth();
            std::cout << "end";
            return true;
        }

        if (auto arraySubscriptExpr = dyn_cast<ArraySubscriptExpr>(stmt))
        {
            TraverseStmt(arraySubscriptExpr->getBase());
            std::cout << "[";
            TraverseStmt(arraySubscriptExpr->getIdx());
            // Add 1 to compensate for 1-based indexing
            std::cout << "+1]";
            return true;
        }

        if (auto binaryOperator = dyn_cast<BinaryOperator>(stmt))
        {
            TraverseStmt(binaryOperator->getLHS());
            std::cout << " " << binaryOperator->getOpcodeStr().str() << " ";
            TraverseStmt(binaryOperator->getRHS());
            return true;
        }

        if (auto parenExpr = dyn_cast<ParenExpr>(stmt))
        {
            std::cout << "(";
            TraverseStmt(parenExpr->getSubExpr());
            std::cout << ")";
            return true;
        }

        return RecursiveASTVisitor::TraverseStmt(stmt);
    }

    bool TraverseDecl(Decl* decl)
    {
        if (auto functionDecl = dyn_cast<FunctionDecl>(decl))
        {
            // Skip over function declarations
            if (!functionDecl->doesThisDeclarationHaveABody())
                return true;

            if (functionDecl->isMain())
                foundMain = true;

            WriteDepth();
            std::cout << "function " << functionDecl->getNameAsString();
            std::cout << "(";
            bool first = true;
            for (auto param : functionDecl->params())
            {
                if (!first)
                    std::cout << ", ";

                std::cout << param->getNameAsString();
                first = false;
            }
            std::cout << ")";
            std::cout << "\n";

            if (functionDecl->hasBody())
                TraverseStmt(functionDecl->getBody());

            WriteDepth();
            std::cout << "end\n";
            return true;
        }

        return RecursiveASTVisitor::TraverseDecl(decl);
    }

    bool VisitStmt(Stmt* stmt)
    {
        if (auto stringLiteral = dyn_cast<StringLiteral>(stmt))
        {
            std::cout << '"' << escapeString(stringLiteral->getString().str()) << '"';
            return true;
        }

        if (auto integerLiteral = dyn_cast<IntegerLiteral>(stmt))
        {
            std::cout << integerLiteral->getValue().toString(10, true);
            return true;
        }

        if (auto declRefExpr = dyn_cast<DeclRefExpr>(stmt))
        {
            std::cout << declRefExpr->getDecl()->getNameAsString();
            return true;
        }

        if (auto returnStmt = dyn_cast<ReturnStmt>(stmt))
        {
            std::cout << "return";
            if (returnStmt->getRetValue())
                std::cout << " ";

            return true;
        }

        return true;
    }

    bool VisitDecl(Decl* decl)
    {
        if (auto varDecl = dyn_cast<VarDecl>(decl))
        {
            auto name = varDecl->getNameAsString();
            if (name.empty())
                return true;

            std::cout << "local " << name;
            if (varDecl->hasInit())
                std::cout << " = ";
        }

        return true;
    }

    void WriteDepth()
    {
        for (uint32_t i = 0; i < depth * 4; ++i)
            std::cout << ' ';
    }

    bool HasFoundMain() { return foundMain; }

  private:
    ASTContext* context;
    uint32_t depth = 0;
    bool foundMain = false;
};

class DumpConsumer : public ASTConsumer
{
  public:
    explicit DumpConsumer(CompilerInstance& compiler)
        : visitor(&compiler.getASTContext()), sourceManager(compiler.getSourceManager())
    {
    }

    virtual void HandleTranslationUnit(ASTContext& context) override
    {
        auto decls = context.getTranslationUnitDecl()->decls();
        for (auto decl : decls)
        {
            auto const& fileId = sourceManager.getFileID(decl->getLocation());
            if (fileId != sourceManager.getMainFileID())
                continue;

            visitor.TraverseDecl(decl);
        }

        // Pass args to main(), and call it
        if (visitor.HasFoundMain())
        {
            std::cout << "return (function() "
                      << "table.insert(arg, 1, arg[0]); "
                      << "return main(#arg, arg) end)()\n";
        }
    }

  private:
    DumpVisitor visitor;
    SourceManager& sourceManager;
};

class DumpAction : public ASTFrontendAction
{
  public:
    virtual bool BeginSourceFileAction(CompilerInstance& compiler, StringRef) override
    {
        class PrintIncludes : public PPCallbacks
        {
            virtual void InclusionDirective(SourceLocation, Token const&, StringRef fileName,
                                            bool isAngled, CharSourceRange, FileEntry const*,
                                            StringRef, StringRef, Module const*) override
            {
                auto newFileName = fileName.str();
                newFileName = newFileName.substr(0, newFileName.find_last_of('.'));
                newFileName += ".lua";

                if (isAngled)
                    newFileName = "shim/lua/" + newFileName;

                std::cout << "dofile \"" << newFileName << "\"\n";
            }
        };

        std::unique_ptr<PrintIncludes> callback(new PrintIncludes);
        auto& preprocessor = compiler.getPreprocessor();
        preprocessor.addPPCallbacks(std::move(callback));

        return true;
    }

    virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance& compiler,
                                                           llvm::StringRef inFile) override
    {
        return std::unique_ptr<ASTConsumer>(new DumpConsumer(compiler));
    }
};

int main(int argc, char const** argv)
{
    llvm::cl::OptionCategory category("irradiant");
    // Ugly hack to get around there being no easy way of adding arguments
    std::vector<char const*> arguments(argv, argv + argc);
    if (strcmp(arguments.back(), "--") == 0)
        arguments.pop_back();
    arguments.push_back("-extra-arg=-fno-builtin");
    arguments.push_back("-extra-arg=-nostdlib");
    arguments.push_back("-extra-arg=-nostdinc");
    arguments.push_back("-extra-arg=-Ishim/c");
    arguments.push_back("--");

    int size = arguments.size();
    CommonOptionsParser parser(size, arguments.data(), category);

    ClangTool tool(parser.getCompilations(), parser.getSourcePathList());
    return tool.run(newFrontendActionFactory<DumpAction>().get());
}
<commit_msg>Added a temporary hack to handle compound assignment operators<commit_after>#include "clang/AST/ASTConsumer.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Lex/Preprocessor.h"

#include <iostream>
#include <sstream>

using namespace clang;
using namespace clang::tooling;

std::string escapeString(std::string const& input)
{
    std::ostringstream ss;
    for (auto c : input)
    {
        switch (c)
        {
        case '\\':
            ss << "\\\\";
            break;
        case '"':
            ss << "\\\"";
            break;
        case '/':
            ss << "\\/";
            break;
        case '\b':
            ss << "\\b";
            break;
        case '\f':
            ss << "\\f";
            break;
        case '\n':
            ss << "\\n";
            break;
        case '\r':
            ss << "\\r";
            break;
        case '\t':
            ss << "\\t";
            break;
        default:
            ss << c;
            break;
        }
    }
    return ss.str();
}

class DumpVisitor : public RecursiveASTVisitor<DumpVisitor>
{
  public:
    explicit DumpVisitor(ASTContext* context) : context(context) {}

    void TraverseNewScope(Stmt* stmt)
    {
        if (!isa<CompoundStmt>(stmt))
        {
            depth++;
            WriteDepth();
        }

        TraverseStmt(stmt);

        if (!isa<CompoundStmt>(stmt))
        {
            std::cout << "\n";
            depth--;
        }
    }

    bool TraverseStmt(Stmt* stmt)
    {
        if (!stmt)
            return RecursiveASTVisitor::TraverseStmt(stmt);

        if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt))
        {
            depth++;
            for (auto stmt : compoundStmt->body())
            {
                if (!stmt)
                    continue;

                WriteDepth();
                TraverseStmt(stmt);
                std::cout << "\n";
            }
            depth--;
            return true;
        }

        if (auto callExpr = dyn_cast<CallExpr>(stmt))
        {
            TraverseStmt(callExpr->getCallee());
            bool first = true;
            std::cout << "(";
            for (auto param : callExpr->arguments())
            {
                if (!first)
                    std::cout << ", ";

                TraverseStmt(param);
                first = false;
            }
            std::cout << ")";
            return true;
        }

        if (auto ifStmt = dyn_cast<IfStmt>(stmt))
        {
            std::cout << "if ";
            TraverseStmt(ifStmt->getCond());
            std::cout << " then\n";

            TraverseNewScope(ifStmt->getThen());

            WriteDepth();
            std::cout << "end";
            return true;
        }

        if (auto arraySubscriptExpr = dyn_cast<ArraySubscriptExpr>(stmt))
        {
            TraverseStmt(arraySubscriptExpr->getBase());
            std::cout << "[";
            TraverseStmt(arraySubscriptExpr->getIdx());
            // Add 1 to compensate for 1-based indexing
            std::cout << "+1]";
            return true;
        }

        if (auto binaryOperator = dyn_cast<BinaryOperator>(stmt))
        {
            // TODO: Replace this with something more robust
            TraverseStmt(binaryOperator->getLHS());
            auto opcodeStr = binaryOperator->getOpcodeStr().str();

            if (binaryOperator->isCompoundAssignmentOp())
            {
                opcodeStr = opcodeStr.substr(0, opcodeStr.find_last_of('='));
                std::cout << " = ";
                TraverseStmt(binaryOperator->getLHS());
            }

            std::cout << " " << opcodeStr << " ";
            TraverseStmt(binaryOperator->getRHS());
            return true;
        }

        if (auto parenExpr = dyn_cast<ParenExpr>(stmt))
        {
            std::cout << "(";
            TraverseStmt(parenExpr->getSubExpr());
            std::cout << ")";
            return true;
        }

        return RecursiveASTVisitor::TraverseStmt(stmt);
    }

    bool TraverseDecl(Decl* decl)
    {
        if (auto functionDecl = dyn_cast<FunctionDecl>(decl))
        {
            // Skip over function declarations
            if (!functionDecl->doesThisDeclarationHaveABody())
                return true;

            if (functionDecl->isMain())
                foundMain = true;

            WriteDepth();
            std::cout << "function " << functionDecl->getNameAsString();
            std::cout << "(";
            bool first = true;
            for (auto param : functionDecl->params())
            {
                if (!first)
                    std::cout << ", ";

                std::cout << param->getNameAsString();
                first = false;
            }
            std::cout << ")";
            std::cout << "\n";

            if (functionDecl->hasBody())
                TraverseStmt(functionDecl->getBody());

            WriteDepth();
            std::cout << "end\n";
            return true;
        }

        return RecursiveASTVisitor::TraverseDecl(decl);
    }

    bool VisitStmt(Stmt* stmt)
    {
        if (auto stringLiteral = dyn_cast<StringLiteral>(stmt))
        {
            std::cout << '"' << escapeString(stringLiteral->getString().str()) << '"';
            return true;
        }

        if (auto integerLiteral = dyn_cast<IntegerLiteral>(stmt))
        {
            std::cout << integerLiteral->getValue().toString(10, true);
            return true;
        }

        if (auto declRefExpr = dyn_cast<DeclRefExpr>(stmt))
        {
            std::cout << declRefExpr->getDecl()->getNameAsString();
            return true;
        }

        if (auto returnStmt = dyn_cast<ReturnStmt>(stmt))
        {
            std::cout << "return";
            if (returnStmt->getRetValue())
                std::cout << " ";

            return true;
        }

        return true;
    }

    bool VisitDecl(Decl* decl)
    {
        if (auto varDecl = dyn_cast<VarDecl>(decl))
        {
            auto name = varDecl->getNameAsString();
            if (name.empty())
                return true;

            std::cout << "local " << name;
            if (varDecl->hasInit())
                std::cout << " = ";
        }

        return true;
    }

    void WriteDepth()
    {
        for (uint32_t i = 0; i < depth * 4; ++i)
            std::cout << ' ';
    }

    bool HasFoundMain() { return foundMain; }

  private:
    ASTContext* context;
    uint32_t depth = 0;
    bool foundMain = false;
};

class DumpConsumer : public ASTConsumer
{
  public:
    explicit DumpConsumer(CompilerInstance& compiler)
        : visitor(&compiler.getASTContext()), sourceManager(compiler.getSourceManager())
    {
    }

    virtual void HandleTranslationUnit(ASTContext& context) override
    {
        auto decls = context.getTranslationUnitDecl()->decls();
        for (auto decl : decls)
        {
            auto const& fileId = sourceManager.getFileID(decl->getLocation());
            if (fileId != sourceManager.getMainFileID())
                continue;

            visitor.TraverseDecl(decl);
        }

        // Pass args to main(), and call it
        if (visitor.HasFoundMain())
        {
            std::cout << "return (function() "
                      << "table.insert(arg, 1, arg[0]); "
                      << "return main(#arg, arg) end)()\n";
        }
    }

  private:
    DumpVisitor visitor;
    SourceManager& sourceManager;
};

class DumpAction : public ASTFrontendAction
{
  public:
    virtual bool BeginSourceFileAction(CompilerInstance& compiler, StringRef) override
    {
        class PrintIncludes : public PPCallbacks
        {
            virtual void InclusionDirective(SourceLocation, Token const&, StringRef fileName,
                                            bool isAngled, CharSourceRange, FileEntry const*,
                                            StringRef, StringRef, Module const*) override
            {
                auto newFileName = fileName.str();
                newFileName = newFileName.substr(0, newFileName.find_last_of('.'));
                newFileName += ".lua";

                if (isAngled)
                    newFileName = "shim/lua/" + newFileName;

                std::cout << "dofile \"" << newFileName << "\"\n";
            }
        };

        std::unique_ptr<PrintIncludes> callback(new PrintIncludes);
        auto& preprocessor = compiler.getPreprocessor();
        preprocessor.addPPCallbacks(std::move(callback));

        return true;
    }

    virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance& compiler,
                                                           llvm::StringRef inFile) override
    {
        return std::unique_ptr<ASTConsumer>(new DumpConsumer(compiler));
    }
};

int main(int argc, char const** argv)
{
    llvm::cl::OptionCategory category("irradiant");
    // Ugly hack to get around there being no easy way of adding arguments
    std::vector<char const*> arguments(argv, argv + argc);
    if (strcmp(arguments.back(), "--") == 0)
        arguments.pop_back();
    arguments.push_back("-extra-arg=-fno-builtin");
    arguments.push_back("-extra-arg=-nostdlib");
    arguments.push_back("-extra-arg=-nostdinc");
    arguments.push_back("-extra-arg=-Ishim/c");
    arguments.push_back("--");

    int size = arguments.size();
    CommonOptionsParser parser(size, arguments.data(), category);

    ClangTool tool(parser.getCompilations(), parser.getSourcePathList());
    return tool.run(newFrontendActionFactory<DumpAction>().get());
}
<|endoftext|>


<commit_before>ef8439d9-2747-11e6-ae1a-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>efb392b3-2747-11e6-a594-e0f84713e7b8<|endoftext|>


<commit_before>c9e5cd5e-2747-11e6-89da-e0f84713e7b8<commit_msg>My Backup<commit_after>c9f792f8-2747-11e6-9f2a-e0f84713e7b8<|endoftext|>


<commit_before>4c55a46b-2748-11e6-b1e7-e0f84713e7b8<commit_msg>Introduced random NullPointerException bug<commit_after>4c6a6794-2748-11e6-9553-e0f84713e7b8<|endoftext|>


<commit_before>69dd6763-ad5b-11e7-843a-ac87a332f658<commit_msg>I am finally done<commit_after>6a92d0ae-ad5b-11e7-a621-ac87a332f658<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

#include "main/spine.hpp"

static std::string LoggerName = "SpineLogger";

class SpineTestsFixture {
	private:
		Spine spine;
	public:
		SpineTestsFixture() {
			REQUIRE(SpineOpenSockets());
		}
	protected:
		bool SpineOpenSockets() {
			REQUIRE_NOTHROW(spine.openSockets());
			REQUIRE(spine.areSocketsValid());
			return spine.areSocketsOpen();
		}
		bool SpineLoadModules() {
			return spine.loadModules(spine.moduleFileLocation);
		}
		bool SpineDefaultModulesLoaded() {
			return spine.isModuleLoaded("mainline_config");
		}
 };

TEST_CASE_METHOD(SpineTestsFixture, "All", "[spine]") {
	SECTION("Spine loads default modules") {
		REQUIRE(SpineLoadModules());
		REQUIRE(SpineDefaultModulesLoaded());
	}
}

int main(int argc, char* const argv[]) {
	// Create the logger we will test later
	auto logger = Spine::createLogger(false);
	// run tests
	return Catch::Session().run(argc, argv);
}
<commit_msg>Added a test for Spine::loadConfig();<commit_after>#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

#include "main/spine.hpp"

static std::string LoggerName = "SpineLogger";

class SpineTestsFixture {
	private:
		Spine spine;
	public:
		SpineTestsFixture() {
			REQUIRE(SpineOpenSockets());
		}
	protected:
		bool SpineOpenSockets() {
			REQUIRE_NOTHROW(spine.openSockets());
			REQUIRE(spine.areSocketsValid());
			return spine.areSocketsOpen();
		}
		bool SpineLoadModules() {
			return spine.loadModules(spine.moduleFileLocation);
		}
		bool SpineDefaultModulesLoaded() {
			return spine.isModuleLoaded("mainline_config");
		}
		bool SpineConfigIsLoaded() {
			return spine.loadConfig("./modules/main.cfg");
		}
 };

TEST_CASE_METHOD(SpineTestsFixture, "All", "[spine,modules,config]") {
	SECTION("Public spine functions") {
		REQUIRE(SpineLoadModules());
		REQUIRE(SpineDefaultModulesLoaded());
		REQUIRE(SpineConfigIsLoaded());
	}
}

int main(int argc, char* const argv[]) {
	// Create the logger we will test later
	auto logger = Spine::createLogger(false);
	// run tests
	return Catch::Session().run(argc, argv);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <vector>
#include <array>

#include "simulated_annealing.hpp"

int main()
{
//////////////////////Camera//////////////////////

    // // building reference
    // PinholeCameraModel reference_camera(50.0, 200.0, 200.0, 1.0, 1.0);
    // std::cout << "reference_camera:\n" << reference_camera << std::endl;

    // // computing model
    // Observations observations{
    //       {{1,2,50}, {3,4,50}, {5,6,50}, {7,8,50}, {9,10,50}, {11,12,50}, {13,14,50}, {15,16,50}, {17,18,50}}
    // };

    // observations.pixels.resize(observations.p3ds.size());
    // for (size_t i=0 ; i<observations.pixels.size() ; ++i)
    //     observations.pixels[i] = reference_camera.project(observations.p3ds[i]);

    // PinholeCameraModel to_optimize{1.0, 1.0, 1.0, 1.0, 1.0};
    // CameraState<PinholeCameraModel> camera_state{reference_camera, 1.1};

    // SimulatedAnnealing<decltype(camera_state), Energy> sa{
    //     camera_state
    //     , Energy{camera_state, observations}
    //     , CoolingSchedule{}
    //     , 10.0
    //     , 0.0
    //     , int(1e4)
    //     , 1e3
    // };

    // std::cout << "camera_to_optimize:\n" << camera_state.f << std::endl;
    // sa.run();
    // std::cout << "camera_to_optimize:\n" << camera_state.f << std::endl;

    return 0;
}
<commit_msg>[] removed useless main.cpp<commit_after><|endoftext|>