<commit_before>#include <cstdio>
#include <string>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <enet/enet.h>

#include "inputcatcher.h"
#include "engine.h"
#include "renderer.h"
#include "datastructures.h"
#include "global_constants.h"
#include "mainmenu.h"

long int getmillisec();

int main(int argc, char **argv)
{
    // Initialize Allegro
    if (!al_init())
    {
        fprintf(stderr, "Fatal Error: Allegro initialization failed!\n");
        return -1;
    }

    // Initialize the Allegro Image addon, used to load sprites and maps
    if (!al_init_image_addon())
    {
        fprintf(stderr, "Fatal Error: Allegro Image Addon initialization failed!\n");
        return -1;
    }

    // Initialize primitives for drawing
    if (!al_init_primitives_addon())
    {
        fprintf(stderr, "Fatal Error: Could not initialize primitives module!");
        throw -1;
    }

    // Initialize keyboard modules
    if (!al_install_keyboard())
    {
        fprintf(stderr, "Fatal Error: Could not initialize keyboard module!");
        throw -1;
    }

    // Initialize mouse
    if (!al_install_mouse())
    {
        fprintf(stderr, "Fatal Error: Could not initialize mouse module!");
        throw -1;
    }

    // Initialize networking system
    if (enet_initialize())
    {
        fprintf(stderr, "Fatal Error: Could not initialize enet!");
        throw -1;
    }

    // Create a display
    ALLEGRO_DISPLAY *display;
    al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);
    al_set_new_display_flags(ALLEGRO_OPENGL);
    display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
    if(!display)
    {
        // FIXME: Make the error argument mean anything?
        fprintf(stderr, "Fatal Error: Could not create display\n");
        throw -1;
    }

    //load font
    //gg2 font as placeholder for now i guess
    al_init_font_addon();
    al_init_ttf_addon();
    ALLEGRO_FONT *font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME);
    if (!font)
    {
      fprintf(stderr, "Could not load 'gg2bold.ttf'.\n");
      throw -1;
    }

//    MainMenu *mainmenu = new MainMenu(display);
    bool isserver;
    if (argc >= 2)
    {
        // If there are any arguments
        isserver = false;
    }
    else
    {
        isserver = true;
    }
    double lasttimeupdated = al_get_time();
//    bool run = true;
//    while (run)
//    {
//        if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)
//        {
//            run = mainmenu->run(display, &gametype);
//            lasttimeupdated = al_get_time();
//    }
//        }
//    delete mainmenu;

    InputCatcher *inputcatcher;
    Engine *engine;
    Renderer *renderer;
    Gamestate *renderingstate;
    try
    {
        // Initialize everything
        // The various allegro initializations can throw errors
        engine = new Engine(isserver);
        renderer = new Renderer(font);
        inputcatcher = new InputCatcher(display);
        renderingstate = new Gamestate(engine);
    }
    catch (int e)
    {
        if (e == -1)
        {
            fprintf(stderr, "\nAllegro initialization failed.");
        }
        else
        {
            fprintf(stderr, "\nUNKNOWN ERROR HAPPENED");
        }
        return -1;
    }
    engine->loadmap("conflict");
    EntityPtr myself = engine->newplayer();
    // FIXME: Hack to make sure the oldstate is properly initialized
    engine->update(0);

    lasttimeupdated = al_get_time();
    while (true)
    {
        try
        {
            while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP)
            {
                inputcatcher->run(myself, engine, renderer);
                engine->update(ENGINE_TIMESTEP);

                lasttimeupdated += ENGINE_TIMESTEP;
            }
            renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)/ENGINE_TIMESTEP);
            renderer->render(display, renderingstate, myself);
        }
        catch (int e)
        {
            if (e != 0)
            {
                fprintf(stderr, "\nError during regular loop.");
                fprintf(stderr, "\nExiting..");
            }
            al_destroy_display(display);
            return 0;
        }
    }
    al_destroy_display(display);
    enet_deinitialize();
    return 0;
}
<commit_msg>Replaced some not-freed pointers with unique_ptrs.<commit_after>#include <cstdio>
#include <string>
#include <memory>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <enet/enet.h>

#include "inputcatcher.h"
#include "engine.h"
#include "renderer.h"
#include "datastructures.h"
#include "global_constants.h"
#include "mainmenu.h"

long int getmillisec();

int main(int argc, char **argv)
{
    // Initialize Allegro
    if (!al_init())
    {
        fprintf(stderr, "Fatal Error: Allegro initialization failed!\n");
        return -1;
    }

    // Initialize the Allegro Image addon, used to load sprites and maps
    if (!al_init_image_addon())
    {
        fprintf(stderr, "Fatal Error: Allegro Image Addon initialization failed!\n");
        return -1;
    }

    // Initialize primitives for drawing
    if (!al_init_primitives_addon())
    {
        fprintf(stderr, "Fatal Error: Could not initialize primitives module!");
        throw -1;
    }

    // Initialize keyboard modules
    if (!al_install_keyboard())
    {
        fprintf(stderr, "Fatal Error: Could not initialize keyboard module!");
        throw -1;
    }

    // Initialize mouse
    if (!al_install_mouse())
    {
        fprintf(stderr, "Fatal Error: Could not initialize mouse module!");
        throw -1;
    }

    // Initialize networking system
    if (enet_initialize())
    {
        fprintf(stderr, "Fatal Error: Could not initialize enet!");
        throw -1;
    }

    // Create a display
    ALLEGRO_DISPLAY *display;
    al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);
    al_set_new_display_flags(ALLEGRO_OPENGL);
    display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
    if(!display)
    {
        // FIXME: Make the error argument mean anything?
        fprintf(stderr, "Fatal Error: Could not create display\n");
        throw -1;
    }

    //load font
    //gg2 font as placeholder for now i guess
    al_init_font_addon();
    al_init_ttf_addon();
    ALLEGRO_FONT *font = al_load_font("gg2bold.ttf", 12, ALLEGRO_TTF_MONOCHROME);
    if (!font)
    {
      fprintf(stderr, "Could not load 'gg2bold.ttf'.\n");
      throw -1;
    }

//    MainMenu *mainmenu = new MainMenu(display);
    bool isserver;
    if (argc >= 2)
    {
        // If there are any arguments
        isserver = false;
    }
    else
    {
        isserver = true;
    }
    double lasttimeupdated = al_get_time();
//    bool run = true;
//    while (run)
//    {
//        if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)
//        {
//            run = mainmenu->run(display, &gametype);
//            lasttimeupdated = al_get_time();
//    }
//        }
//    delete mainmenu;

    std::unique_ptr<Engine> engine;
    std::unique_ptr<Renderer> renderer;
    std::unique_ptr<InputCatcher> inputcatcher;
    std::unique_ptr<Gamestate> renderingstate;

    try
    {
        // Initialize everything
        // The various allegro initializations can throw errors
        engine = std::unique_ptr<Engine>(new Engine(isserver));
        renderer = std::unique_ptr<Renderer>(new Renderer(font));
        inputcatcher = std::unique_ptr<InputCatcher>(new InputCatcher(display));
        renderingstate = std::unique_ptr<Gamestate>(new Gamestate(engine.get()));
    }
    catch (int e)
    {
        if (e == -1)
        {
            fprintf(stderr, "\nAllegro initialization failed.");
        }
        else
        {
            fprintf(stderr, "\nUNKNOWN ERROR HAPPENED");
        }
        return -1;
    }
    engine->loadmap("conflict");
    EntityPtr myself = engine->newplayer();
    // FIXME: Hack to make sure the oldstate is properly initialized
    engine->update(0);

    lasttimeupdated = al_get_time();
    while (true)
    {
        try
        {
            while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP)
            {
                inputcatcher->run(myself, engine.get(), renderer.get());
                engine->update(ENGINE_TIMESTEP);

                lasttimeupdated += ENGINE_TIMESTEP;
            }
            renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)/ENGINE_TIMESTEP);
            renderer->render(display, renderingstate.get(), myself);
        }
        catch (int e)
        {
            if (e != 0)
            {
                fprintf(stderr, "\nError during regular loop.");
                fprintf(stderr, "\nExiting..");
            }
            al_destroy_display(display);
            return 0;
        }
    }
    al_destroy_display(display);
    enet_deinitialize();
    return 0;
}
<|endoftext|>


<commit_before>0f9c26c2-2748-11e6-bc23-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>0faf4568-2748-11e6-8ecc-e0f84713e7b8<|endoftext|>


<commit_before>0d303963-2748-11e6-908a-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>0d3c8c00-2748-11e6-badc-e0f84713e7b8<|endoftext|>


<commit_before>45bc5185-ad5d-11e7-a4f8-ac87a332f658<commit_msg>updated some files<commit_after>47099128-ad5d-11e7-b793-ac87a332f658<|endoftext|>


<commit_before>d7897fd7-4b02-11e5-b7de-28cfe9171a43<commit_msg>compiles now<commit_after>d7991c5c-4b02-11e5-8127-28cfe9171a43<|endoftext|>


<commit_before>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>
#include <time.h>
#include <limits.h> // PATH_MAX

// STL
#include <system_error>
#include <map>
#include <set>
#include <string>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <iostream>

namespace posix
{
  static const int success_response = 0;
  static const int error_response = -1;
  static int success(void) { errno = 0; return success_response; }
  static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }
}

namespace circlefs
{
  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  std::map<uid_t, std::set<file_entry_t>> files;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)
  {
    const char* dir_pos = std::strchr(path, '/') + 1;
    const char* file_pos = std::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == nullptr)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = ::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set)
  {
    char path[PATH_MAX + 1];
    struct stat info;

    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      // Linux only
      sprintf(path, "/proc/%d", pos->pid);
      if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }

  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)
  {
    (void)fileInfo;
    filler(buf, "." , nullptr, 0);
    filler(buf, "..", nullptr, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
        {
          posix::error(std::errc::no_such_file_or_directory);
          return 0 - errno;
        }

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success();
  }

  int mknod(const char* path, mode_t mode, dev_t rdev)
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return posix::error(std::errc::permission_denied);

    Epath type;
    passwd* pw_ent = nullptr;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return posix::error(std::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
        stat.st_atim =
        stat.st_ctim =
        stat.st_mtim = time;

        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success();
  }

  int getattr(const char* path, struct stat* statbuf)
  {
    Epath type;
    passwd* pw_ent = nullptr;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root:      // root directory (always exists)
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        posix::success();
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        if(pw_ent == nullptr)
          posix::error(std::errc::no_such_file_or_directory);
        else
          posix::success();
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
        {
          posix::error(std::errc::no_such_file_or_directory);
          break;
        }

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            posix::success();
            return 0 - errno;
          }
        }

        posix::error(std::errc::no_such_file_or_directory); // no file matched
        break;
    }
    return 0 - errno;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  ops.readdir   = circlefs::readdir;
  ops.mknod     = circlefs::mknod;
  ops.getattr   = circlefs::getattr;

  return fuse_main(argc, argv, &ops, nullptr);
}
<commit_msg>cleanup<commit_after>#define FUSE_USE_VERSION 30
#include <fuse.h>

// POSIX
#include <sys/types.h>
#include <sys/stat.h> // mode info
#include <pwd.h> // user id
#include <grp.h> // group id
#include <unistd.h>
#include <time.h>
#include <limits.h> // PATH_MAX

// STL
#include <system_error>
#include <map>
#include <set>
#include <string>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <iostream>

namespace posix
{
  static const int success_response = 0;
  static const int error_response = -1;
  static int success(void) { errno = 0; return success_response; }
  static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }
}

namespace circlefs
{
  enum class Epath
  {
    root,
    directory,
    file,
  };

  struct file_entry_t
  {
    bool operator < (const file_entry_t& other) const // for locating files by name
      { return name < other.name; }

    std::string name;
    pid_t pid;
    struct stat stat;
  };

  std::map<uid_t, std::set<file_entry_t>> files;

  void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)
  {
    const char* dir_pos = std::strchr(path, '/') + 1;
    const char* file_pos = std::strchr(dir_pos, '/');
    std::string dir;

    if(path[1] == '\0')
    {
      type = Epath::root;
      pw_ent = nullptr;
      filename.clear();
    }
    else
    {
      if(file_pos == nullptr)
      {
        dir = dir_pos;
        filename.clear();
        type = Epath::directory;
      }
      else
      {
        dir = std::string(dir_pos, file_pos - dir_pos);
        filename = file_pos + 1;
        type = Epath::file;
      }

      pw_ent = ::getpwnam(dir.c_str());
    }
  }

  void clean_set(std::set<file_entry_t>& dir_set)
  {
    char path[PATH_MAX + 1];
    struct stat info;

    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      // Linux only
      sprintf(path, "/proc/%d", pos->pid);
      if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) // if process
        pos = dir_set.erase(pos);
      else
        ++pos;
    }
  }

  struct timespec get_oldest(std::set<file_entry_t>& dir_set)
  {
    struct timespec oldest = dir_set.begin()->stat.st_atim;
    auto pos = dir_set.begin();
    while(pos != dir_set.end())
    {
      if(pos->stat.st_atim.tv_sec < oldest.tv_sec)
        oldest.tv_sec = pos->stat.st_atim.tv_sec;
    }
    return oldest;
  }

  int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)
  {
    (void)fileInfo;
    filler(buf, "." , nullptr, 0);
    filler(buf, "..", nullptr, 0);

    Epath type;
    passwd* pw_ent;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory (fill with usernames in use)
      {
        auto pos = files.begin();
        while(pos != files.end())
        {
          clean_set(pos->second);

          if(pos->second.empty())
            pos = files.erase(pos);
          else
          {
            filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);
            ++pos;
          }
        }
        break;
      }

      case Epath::directory: // list files in directory (based on username)
      {
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username has no files
        {
          posix::error(std::errc::no_such_file_or_directory);
          return 0 - errno;
        }

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second)
          filler(buf, entry.name.c_str(), &entry.stat, offset);

        break;
      }

      case Epath::file: // there must have been a parsing error (impossible situation)
        assert(false);
    }

    return posix::success();
  }

  int mknod(const char* path, mode_t mode, dev_t rdev)
  {
    (void)rdev;
    if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) // if not a socket or execution flag is set
      return posix::error(std::errc::permission_denied);

    Epath type;
    passwd* pw_ent = nullptr;
    std::string filename;
    struct stat stat = {};
    struct timespec time;
    clock_gettime(CLOCK_REALTIME, &time);

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root: // root directory - cannot make root!
      case Epath::directory: // directory (based on username) - cannot make directory!
        return posix::error(std::errc::permission_denied);

      case Epath::file: // create a node file!
        fuse_context* ctx = fuse_get_context();
        auto& dir = files[pw_ent->pw_uid];
        auto entry = dir.find({ filename, 0, stat });
        if(entry != dir.end())
          dir.erase(entry);

        stat.st_uid = pw_ent->pw_uid;
        stat.st_gid = pw_ent->pw_gid;
        stat.st_mode = mode;
        stat.st_ctim =
        stat.st_mtim =
        stat.st_atim = time;

        dir.insert({ filename, ctx->pid, stat });
        break;
    }
    return posix::success();
  }

  int getattr(const char* path, struct stat* statbuf)
  {
    Epath type;
    passwd* pw_ent = nullptr;
    std::string filename;

    deconstruct_path(path, type, pw_ent, filename);

    switch(type)
    {
      case Epath::root:      // root directory (always exists)
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        posix::success();
        break;

      case Epath::directory: // username (exists if username exists)
        statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;
        if(pw_ent == nullptr)
          posix::error(std::errc::no_such_file_or_directory);
        else
          posix::success();
        break;

      case Epath::file:
        auto pos = files.find(pw_ent->pw_uid);
        if(pos == files.end()) // username not registered
        {
          posix::error(std::errc::no_such_file_or_directory);
          break;
        }

        clean_set(pos->second);

        for(const file_entry_t& entry : pos->second) // check every file
        {
          if(entry.name == filename)
          {
            *statbuf = entry.stat;
            posix::success();
            return 0 - errno;
          }
        }

        posix::error(std::errc::no_such_file_or_directory); // no file matched
        break;
    }
    return 0 - errno;
  }
}

int main(int argc, char *argv[])
{
  static struct fuse_operations ops;

  ops.readdir = circlefs::readdir;
  ops.mknod   = circlefs::mknod;
  ops.getattr = circlefs::getattr;

  return fuse_main(argc, argv, &ops, nullptr);
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  Calculator
//
//  Created by Gavin Scheele on 4/6/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "Solver.h"
using namespace std;
int main(int argc, char * argv[])
{

//    Rational *a = new Rational(2,1);
//    Rational *b = new Rational(1,-8);
//    Rational *c = new Rational(2,1);
//    Integer *d = new Integer(4);
//    Integer *e = new Integer(-1);
//    Integer *f = new Integer(0);
//
//    cout << *a->add(c) << endl;
//    cout << *a->subtract(d) << endl;
//    cout << *a->multiply(e) << endl;
//    cout << *a->divide(b) << endl;

    Solver *s = new Solver("3 - 300");
    cout << s->solve() << endl;;

    return 0;
}<commit_msg>got started<commit_after>//
//  main.cpp
//  Calculator
//
//  Created by Gavin Scheele on 4/6/14.
//  Copyright (c) 2014 Gavin Scheele. All rights reserved.
//

#include "Solver.h"
using namespace std;
int main(int argc, char * argv[])  //a main method shouldn't have perameters - at least I don't think so. -Dan
{
    string choice;
    choice = "z";
    cout << "Menu" << "\n" <<
           "a. Compute a New Expression" << "\n" <<
           "b. Help" << "\n" <<
           "c. Review Previous Expressions and Answers" << "\n";
    cin >> choice;
    cout << "\n";
    if (choice.compare("a") == 0) {
        string secondChoice = "n"
        while (secondChoice.compare("y") == 0) {
            string expression;
            cin >> expression;
            //that's the input - I don't know how you want to handle it
            cout <<"\n" << "Would you like to go back to the menu? (y/n)" << "\n";
            cin >> secondChoice;
            cout << "\n";
        }
    }
//    Rational *a = new Rational(2,1);
//    Rational *b = new Rational(1,-8);
//    Rational *c = new Rational(2,1);
//    Integer *d = new Integer(4);
//    Integer *e = new Integer(-1);
//    Integer *f = new Integer(0);
//
//    cout << *a->add(c) << endl;
//    cout << *a->subtract(d) << endl;
//    cout << *a->multiply(e) << endl;
//    cout << *a->divide(b) << endl;

    Solver *s = new Solver("3 - 300");
    cout << s->solve() << endl;;

    return 0;
}
<|endoftext|>


<commit_before>7977a0b3-4b02-11e5-911d-28cfe9171a43<commit_msg>Long commit messages are not required<commit_after>7983f754-4b02-11e5-8d5d-28cfe9171a43<|endoftext|>


<commit_before>e0bf882b-4b02-11e5-9982-28cfe9171a43<commit_msg>My Life for Auir<commit_after>e0c8e7ee-4b02-11e5-b74c-28cfe9171a43<|endoftext|>


<commit_before>#include <algorithm>
#include <map>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "document.h"

extern FILE * xmlin;
extern int xmlparse(Document **);

static std::string help_message = "Available commands are:\n\
../xmltool -p file.xml : parse and display the xml file\n\
../xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n\
../xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n\
../xmltool -h : displays this help\n";

static int handle_help(int, const char **);
static int handle_validate(int, const char **);
static int handle_parse(int, const char **);
static int handle_transform(int, const char **);

// Valid commands (no dash character)
typedef int (*command_handler)(int, const char **) ;
static std::map<std::string, command_handler> command_map = {
  { "h", handle_help},
  { "v", handle_validate },
  { "p", handle_parse },
  { "t", handle_transform }
};

int main(int argc, const char ** argv)
{
  // Command must be given
  if (argc < 2)
  {
    std::cerr << "No argument given" << std::endl;
    return handle_help(argc, argv);
  }

  // Command must be handled
  std::string cmd(argv[1] + 1);
  std::map<std::string, command_handler>::const_iterator it;
  if ((it = command_map.find(cmd)) == command_map.end())
  {
    std::cerr << "Bad argument given" << std::endl;
    return handle_help(argc, argv);
  }

  // Call command handler, making argc and argv correspond
  int nb_ignored = 2;
  argc -= nb_ignored;
  argv += nb_ignored;
  return it->second(argc, argv);
}

int handle_help(int, const char **)
{
  std::cerr << help_message;
  return 1;
}

static Document * read_document(const char * fname)
{
  // Change xmlparse input
  FILE * fp = fopen(fname, "r");
  if (fp == nullptr)
  {
    return nullptr;
  }
  xmlin = fp;

  // Construct document
  Document * doc = nullptr;
  xmlparse(&doc); // who gives a f**k about the return code ?

  // TODO semantic analysis

  return doc;
}

int handle_parse(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide an argument to the command -p" << std::endl;
    return EXIT_FAILURE;
  }

  // XML
  Document * doc = read_document(argv[0]);
  if (doc == nullptr) { return EXIT_FAILURE; }
  std::cout << doc->str() << std::endl;
  delete doc;

  return EXIT_SUCCESS;
}

int handle_validate(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl;
    return EXIT_FAILURE;
  }
  else if (argc < 2)
  {
    std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl;
    return EXIT_FAILURE;
  }

  // XML/XSD
  Document * xml_doc = read_document(argv[0]);
  Document * xsd_doc = read_document(argv[1]);

  // TODO

  delete xml_doc;
  delete xsd_doc;

  return EXIT_SUCCESS;
}

int handle_transform(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl;
    return EXIT_FAILURE;
  }
  else if (argc < 2)
  {
    std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl;
    return EXIT_FAILURE;
  }

  // XML/XSL
  Document * xml_doc = read_document(argv[0]);
  Document * xsl_doc = read_document(argv[1]);

  // TODO

  delete xsl_doc;
  delete xml_doc;

  return EXIT_FAILURE;
}

// vim:ft=cpp et sw=2 sts=2:
<commit_msg>More tests<commit_after>#include <algorithm>
#include <map>
#include <iostream>
#include <fstream>
#include <cstdio>
#include "document.h"

extern FILE * xmlin;
extern int xmlparse(Document **);

static std::string help_message = "Available commands are:\n\
../xmltool -p file.xml : parse and display the xml file\n\
../xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\n\
../xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\n\
../xmltool -h : displays this help\n";

static int handle_help(int, const char **);
static int handle_validate(int, const char **);
static int handle_parse(int, const char **);
static int handle_transform(int, const char **);

// Valid commands (no dash character)
typedef int (*command_handler)(int, const char **) ;
static std::map<std::string, command_handler> command_map = {
  { "h", handle_help},
  { "v", handle_validate },
  { "p", handle_parse },
  { "t", handle_transform }
};

int main(int argc, const char ** argv)
{
  // Command must be given
  if (argc < 2)
  {
    std::cerr << "No argument given" << std::endl;
    return handle_help(argc, argv);
  }

  // Command must be handled
  std::string cmd(argv[1] + 1);
  std::map<std::string, command_handler>::const_iterator it;
  if ((it = command_map.find(cmd)) == command_map.end())
  {
    std::cerr << "Bad argument given" << std::endl;
    return handle_help(argc, argv);
  }

  // Call command handler, making argc and argv correspond
  int nb_ignored = 2;
  argc -= nb_ignored;
  argv += nb_ignored;
  return it->second(argc, argv);
}

int handle_help(int, const char **)
{
  std::cerr << help_message;
  return 1;
}

static Document * read_document(const char * fname)
{
  // Change xmlparse input
  FILE * fp = fopen(fname, "r");
  if (fp == nullptr)
  {
    std::cerr << "Unable to open does_not_exist.xml" << std::endl;
    return nullptr;
  }
  xmlin = fp;

  // Construct document
  Document * doc = nullptr;
  xmlparse(&doc); // who gives a f**k about the return code ?

  // TODO semantic analysis

  return doc;
}

int handle_parse(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide an argument to the command -p" << std::endl;
    return 1;
  }

  // XML
  Document * doc = read_document(argv[0]);
  if (doc == nullptr) { return 1; }
  std::cout << doc->str() << std::endl;
  delete doc;

  return 0;
}

int handle_validate(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl;
    return 1;
  }
  else if (argc < 2)
  {
    std::cerr << "You must provide two arguments to the command -v: an xml file and an xsd file" << std::endl;
    return 1;
  }

  // XML/XSD
  Document * xml_doc = read_document(argv[0]);
  Document * xsd_doc = read_document(argv[1]);

  // TODO

  delete xml_doc;
  delete xsd_doc;

  return 0;
}

int handle_transform(int argc, const char ** argv)
{
  if (argc < 1)
  {
    std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl;
    return 1;
  }
  else if (argc < 2)
  {
    std::cerr << "You must provide two arguments to the command -t: an xml file and an xsl file" << std::endl;
    return 1;
  }

  // XML/XSL
  Document * xml_doc = read_document(argv[0]);
  Document * xsl_doc = read_document(argv[1]);

  // TODO

  delete xsl_doc;
  delete xml_doc;

  return 1;
}

// vim:ft=cpp et sw=2 sts=2:
<|endoftext|>


<commit_before>#ifndef Rice__Hash__hpp_
#define Rice__Hash__hpp_

#include "Builtin_Object_defn.hpp"
#include "to_from_ruby_defn.hpp"
#include "detail/ruby.hpp"
#include "detail/st.hpp"
#include "detail/remove_const.hpp"
#include <iterator>

namespace Rice
{

//! A wrapper for the ruby Hash class.
//! This class provides a C++-style interface to ruby's Hash class and
//! its associated rb_hash_* functions.
//! Example:
//! \code
//!   Hash h;
//!   h[42] = String("foo");
//!   h[10] = String("bar");
//!   std::cout << String(h[42]) << std::endl;
//! \endcode
class Hash
  : public Builtin_Object<RHash, T_HASH>
{
public:
  //! Construct a new hash.
  Hash();

  //! Wrap an existing hash.
  /*! \param v the hash to wrap.
   */
  Hash(Object v);

  //! Return the number of elements in the hash.
  size_t size() const;

private:
  //! A helper class so hash[key]=value can work.
  class Proxy;

public:
  //! Get the value for the given key.
  /*! \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key.
   */
  template<typename Key_T>
  Proxy const operator[](Key_T const & key) const;

  //! Get the value for the given key.
  /*! \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key.
   */
  template<typename Key_T>
  Proxy operator[](Key_T const & key);

  //! Get the value for the given key
  /*! The returned value is converted to the type given by Value_T.
   *  \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key, converted to C++
   *  type Value_T.
   */
  template<typename Value_T, typename Key_T>
  Value_T get(Key_T const & key);

  //! A helper class for dereferencing iterators
  class Entry;

  //! A helper class for implementing iterators for a Hash.
  template<typename Hash_Ref_T, typename Value_T>
  class Iterator;

public:
  //! An iterator.
  typedef Iterator<Hash &, Entry> iterator;

  //! A const iterator.
  typedef Iterator<Hash const &, Entry const> const_iterator;

public:
  //! Return an iterator to the beginning of the hash.
  iterator begin();

  //! Return a const iterator to the beginning of the hash.
  const_iterator begin() const;

  //! Return an iterator to the end of the hash.
  iterator end();

  //! Return a const to the end of the hash.
  const_iterator end() const;
};

//! A helper class so hash[key]=value can work.
class Hash::Proxy
{
public:
  //! Construct a new Proxy.
  Proxy(Hash hash, Object key);

  //! Implicit conversion to Object.
  operator Object() const;

  //! Explicit conversion to VALUE.
  VALUE value() const;

  //! Assignment operator.
  template<typename T>
  Object operator=(T const & value);

  void swap(Proxy & proxy);

private:
  Hash hash_;
  Object key_;
};

//! A helper class for dereferencing iterators
/*! This class is intended to look similar to an std::pair.
 */
class Hash::Entry
{
public:
  //! Construct a new Entry.
  Entry(Hash hash, Object key);

  //! Copy constructor.
  Entry(Entry const & entry);

  Object const key;          //!< The key
  Object const & first;      //!< An alias for the key

  Proxy value;              //!< The value
  Proxy & second;           //!< An alias for the value

  Entry & operator=(Entry const & rhs);

  void swap(Entry & entry);

  friend bool operator<(Entry const & lhs, Entry const & rhs);
};

bool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs);

//! A helper class for implementing iterators for a Hash.
template<typename Hash_Ref_T, typename Value_T>
class Hash::Iterator
  : public std::iterator<
      std::input_iterator_tag,
      Value_T>
{
public:
  //! Construct a new Iterator.
  Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr);

  //! Copy construct an Iterator.
  Iterator(Iterator const & iterator);

  //! Construct an Iterator from another Iterator of a different const
  //! qualification.
  template<typename Iterator_T>
  Iterator(Iterator_T const & iterator);

  //! Assignment operator.
  Iterator & operator=(Iterator const & rhs);

  //! Preincrement operator.
  Iterator & operator++();

  //! Postincrement operator.
  Iterator operator++(int);

  //! Dereference operator.
  Value_T operator*();

  //! Dereference operator.
  Value_T * operator->();

  //! Equality operator.
  bool operator==(Iterator const & rhs) const;

  //! Inequality operator.
  bool operator!=(Iterator const & rhs) const;

  template<typename Hash_Ref_T_, typename Value_T_>
  friend class Hash::Iterator;

  //! Swap with another iterator of the same type.
  void swap(Iterator & iterator);

private:
  Hash hash_;
  st_table * tbl_;
  st_data_t bin_;
  st_table_entry * ptr_;

  mutable typename detail::remove_const<Value_T>::Type tmp_;
};

} // namespace Rice

#include "Hash.ipp"

#endif // Rice__Hash__hpp_

<commit_msg>Use int for type of bin_ on ruby 1.8.x.<commit_after>#ifndef Rice__Hash__hpp_
#define Rice__Hash__hpp_

#include "Builtin_Object_defn.hpp"
#include "to_from_ruby_defn.hpp"
#include "detail/ruby.hpp"
#include "detail/st.hpp"
#include "detail/remove_const.hpp"
#include <iterator>

namespace Rice
{

//! A wrapper for the ruby Hash class.
//! This class provides a C++-style interface to ruby's Hash class and
//! its associated rb_hash_* functions.
//! Example:
//! \code
//!   Hash h;
//!   h[42] = String("foo");
//!   h[10] = String("bar");
//!   std::cout << String(h[42]) << std::endl;
//! \endcode
class Hash
  : public Builtin_Object<RHash, T_HASH>
{
public:
  //! Construct a new hash.
  Hash();

  //! Wrap an existing hash.
  /*! \param v the hash to wrap.
   */
  Hash(Object v);

  //! Return the number of elements in the hash.
  size_t size() const;

private:
  //! A helper class so hash[key]=value can work.
  class Proxy;

public:
  //! Get the value for the given key.
  /*! \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key.
   */
  template<typename Key_T>
  Proxy const operator[](Key_T const & key) const;

  //! Get the value for the given key.
  /*! \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key.
   */
  template<typename Key_T>
  Proxy operator[](Key_T const & key);

  //! Get the value for the given key
  /*! The returned value is converted to the type given by Value_T.
   *  \param key the key whose value should be retrieved from the hash.
   *  \return the value associated with the given key, converted to C++
   *  type Value_T.
   */
  template<typename Value_T, typename Key_T>
  Value_T get(Key_T const & key);

  //! A helper class for dereferencing iterators
  class Entry;

  //! A helper class for implementing iterators for a Hash.
  template<typename Hash_Ref_T, typename Value_T>
  class Iterator;

public:
  //! An iterator.
  typedef Iterator<Hash &, Entry> iterator;

  //! A const iterator.
  typedef Iterator<Hash const &, Entry const> const_iterator;

public:
  //! Return an iterator to the beginning of the hash.
  iterator begin();

  //! Return a const iterator to the beginning of the hash.
  const_iterator begin() const;

  //! Return an iterator to the end of the hash.
  iterator end();

  //! Return a const to the end of the hash.
  const_iterator end() const;
};

//! A helper class so hash[key]=value can work.
class Hash::Proxy
{
public:
  //! Construct a new Proxy.
  Proxy(Hash hash, Object key);

  //! Implicit conversion to Object.
  operator Object() const;

  //! Explicit conversion to VALUE.
  VALUE value() const;

  //! Assignment operator.
  template<typename T>
  Object operator=(T const & value);

  void swap(Proxy & proxy);

private:
  Hash hash_;
  Object key_;
};

//! A helper class for dereferencing iterators
/*! This class is intended to look similar to an std::pair.
 */
class Hash::Entry
{
public:
  //! Construct a new Entry.
  Entry(Hash hash, Object key);

  //! Copy constructor.
  Entry(Entry const & entry);

  Object const key;          //!< The key
  Object const & first;      //!< An alias for the key

  Proxy value;              //!< The value
  Proxy & second;           //!< An alias for the value

  Entry & operator=(Entry const & rhs);

  void swap(Entry & entry);

  friend bool operator<(Entry const & lhs, Entry const & rhs);
};

bool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs);

//! A helper class for implementing iterators for a Hash.
template<typename Hash_Ref_T, typename Value_T>
class Hash::Iterator
  : public std::iterator<
      std::input_iterator_tag,
      Value_T>
{
public:
  //! Construct a new Iterator.
  Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr);

  //! Copy construct an Iterator.
  Iterator(Iterator const & iterator);

  //! Construct an Iterator from another Iterator of a different const
  //! qualification.
  template<typename Iterator_T>
  Iterator(Iterator_T const & iterator);

  //! Assignment operator.
  Iterator & operator=(Iterator const & rhs);

  //! Preincrement operator.
  Iterator & operator++();

  //! Postincrement operator.
  Iterator operator++(int);

  //! Dereference operator.
  Value_T operator*();

  //! Dereference operator.
  Value_T * operator->();

  //! Equality operator.
  bool operator==(Iterator const & rhs) const;

  //! Inequality operator.
  bool operator!=(Iterator const & rhs) const;

  template<typename Hash_Ref_T_, typename Value_T_>
  friend class Hash::Iterator;

  //! Swap with another iterator of the same type.
  void swap(Iterator & iterator);

private:
  Hash hash_;
  st_table * tbl_;
#if RUBY_VERSION_CODE >= 190
  st_index_t bin_;
#else
  int bin_;
#endif
  st_table_entry * ptr_;

  mutable typename detail::remove_const<Value_T>::Type tmp_;
};

} // namespace Rice

#include "Hash.ipp"

#endif // Rice__Hash__hpp_

<|endoftext|>


<commit_before>#include <QApplication>

#include <QTranslator>

#include "qtbleditor.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("kambala");
    app.setApplicationName("QTblEditor");
    app.setApplicationVersion("1.2");
#ifdef Q_OS_MAC
    app.setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

    QString locale = QLocale::system().name(), translationsPath =
#ifdef Q_OS_MAC
                     qApp->applicationDirPath() + "/../Resources/" +
#endif
                     "Translations/" + locale;

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + locale, translationsPath);
    app.installTranslator(&qtTranslator);

    QTranslator myappTranslator;
    myappTranslator.load("qtbleditor_" + locale, translationsPath);
    app.installTranslator(&myappTranslator);

    QTblEditor w;
    w.show();

    return app.exec();
}
<commit_msg>bump version<commit_after>#include <QApplication>

#include <QTranslator>

#include "qtbleditor.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("kambala");
    app.setApplicationName("QTblEditor");
    app.setApplicationVersion("1.3");
#ifdef Q_OS_MAC
    app.setAttribute(Qt::AA_DontShowIconsInMenus);
#endif

    QString locale = QLocale::system().name(), translationsPath =
#ifdef Q_OS_MAC
                     qApp->applicationDirPath() + "/../Resources/" +
#endif
                     "Translations/" + locale;

    QTranslator qtTranslator;
    qtTranslator.load("qt_" + locale, translationsPath);
    app.installTranslator(&qtTranslator);

    QTranslator myappTranslator;
    myappTranslator.load("qtbleditor_" + locale, translationsPath);
    app.installTranslator(&myappTranslator);

    QTblEditor w;
    w.show();

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


<commit_before>a58a668f-2747-11e6-b623-e0f84713e7b8<commit_msg>I finished programming, there is nothing left to program<commit_after>a59e1711-2747-11e6-8080-e0f84713e7b8<|endoftext|>


<commit_before>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

static char *
load_text_file(const char *file_name, size_t *size)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	*size = 0;
	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) malloc(st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
			*size = total_read;
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_lir = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { NULL, 0, NULL, 0 }
};

void
compile_shader(struct glsl_shader *prog)
{
   struct _mesa_glsl_parse_state state;

   memset(& state, 0, sizeof(state));
   switch (prog->Type) {
   case GL_VERTEX_SHADER:   state.target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;
   }

   state.scanner = NULL;
   state.translation_unit.make_empty();
   state.symbols = new glsl_symbol_table;
   state.error = false;
   state.temp_index = 0;
   state.loop_or_switch_nesting = NULL;
   state.ARB_texture_rectangle_enable = true;

   _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen);
   _mesa_glsl_parse(& state);
   _mesa_glsl_lexer_dtor(& state);

   if (dump_ast) {
      foreach_list_const(n, &state.translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   prog->ir.make_empty();
   if (!state.error && !state.translation_unit.is_empty())
      _mesa_ast_to_hir(&prog->ir, &state);

   /* Optimization passes */
   if (!state.error && !prog->ir.is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(&prog->ir) || progress;
	 progress = do_if_simplification(&prog->ir) || progress;
	 progress = do_copy_propagation(&prog->ir) || progress;
	 progress = do_dead_code_local(&prog->ir) || progress;
	 progress = do_dead_code_unlinked(&prog->ir) || progress;
	 progress = do_constant_variable_unlinked(&prog->ir) || progress;
	 progress = do_constant_folding(&prog->ir) || progress;
	 progress = do_vec_index_to_swizzle(&prog->ir) || progress;
	 progress = do_swizzle_swizzle(&prog->ir) || progress;
      } while (progress);
   }

   /* Print out the resulting IR */
   if (!state.error && dump_lir) {
      _mesa_print_ir(&prog->ir, &state);
   }

   prog->symbols = state.symbols;
   prog->CompileStatus = !state.error;
   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct glsl_shader **prog_list = NULL;
   unsigned prog_list_len = 0;

   for (/* empty */; argc > optind; optind++) {
      prog_list = (struct glsl_shader **)
	 realloc(prog_list,
		 sizeof(struct glsl_shader *) * (prog_list_len + 1));
      assert(prog_list != NULL);

      struct glsl_shader *prog = new glsl_shader;
      memset(prog, 0, sizeof(*prog));

      prog_list[prog_list_len] = prog;
      prog_list_len++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 prog->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 prog->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 prog->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      prog->Source = load_text_file(argv[optind], &prog->SourceLen);

      compile_shader(prog);

      if (!prog->CompileStatus) {
	 status = EXIT_FAILURE;
	 break;
      }
   }

   return status;
}
<commit_msg>Use glsl_program instead of an open-coded vector of shaders<commit_after>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

static char *
load_text_file(const char *file_name, size_t *size)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	*size = 0;
	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) malloc(st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
			*size = total_read;
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_lir = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { NULL, 0, NULL, 0 }
};

void
compile_shader(struct glsl_shader *prog)
{
   struct _mesa_glsl_parse_state state;

   memset(& state, 0, sizeof(state));
   switch (prog->Type) {
   case GL_VERTEX_SHADER:   state.target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;
   }

   state.scanner = NULL;
   state.translation_unit.make_empty();
   state.symbols = new glsl_symbol_table;
   state.error = false;
   state.temp_index = 0;
   state.loop_or_switch_nesting = NULL;
   state.ARB_texture_rectangle_enable = true;

   _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen);
   _mesa_glsl_parse(& state);
   _mesa_glsl_lexer_dtor(& state);

   if (dump_ast) {
      foreach_list_const(n, &state.translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   prog->ir.make_empty();
   if (!state.error && !state.translation_unit.is_empty())
      _mesa_ast_to_hir(&prog->ir, &state);

   /* Optimization passes */
   if (!state.error && !prog->ir.is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(&prog->ir) || progress;
	 progress = do_if_simplification(&prog->ir) || progress;
	 progress = do_copy_propagation(&prog->ir) || progress;
	 progress = do_dead_code_local(&prog->ir) || progress;
	 progress = do_dead_code_unlinked(&prog->ir) || progress;
	 progress = do_constant_variable_unlinked(&prog->ir) || progress;
	 progress = do_constant_folding(&prog->ir) || progress;
	 progress = do_vec_index_to_swizzle(&prog->ir) || progress;
	 progress = do_swizzle_swizzle(&prog->ir) || progress;
      } while (progress);
   }

   /* Print out the resulting IR */
   if (!state.error && dump_lir) {
      _mesa_print_ir(&prog->ir, &state);
   }

   prog->symbols = state.symbols;
   prog->CompileStatus = !state.error;
   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct glsl_program whole_program;
   memset(&whole_program, 0, sizeof(whole_program));

   for (/* empty */; argc > optind; optind++) {
      whole_program.Shaders = (struct glsl_shader **)
	 realloc(whole_program.Shaders,
		 sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1));
      assert(whole_program.Shaders != NULL);

      struct glsl_shader *prog = new glsl_shader;
      memset(prog, 0, sizeof(*prog));

      whole_program.Shaders[whole_program.NumShaders] = prog;
      whole_program.NumShaders++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 prog->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 prog->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 prog->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      prog->Source = load_text_file(argv[optind], &prog->SourceLen);

      compile_shader(prog);

      if (!prog->CompileStatus) {
	 status = EXIT_FAILURE;
	 break;
      }
   }

   return status;
}
<|endoftext|>


<commit_before>a7a0d182-4b02-11e5-a29a-28cfe9171a43<commit_msg>my cat is cute<commit_after>a7acc49e-4b02-11e5-bd26-28cfe9171a43<|endoftext|>


<commit_before>#include <fstream>
#include <cstring>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

//~ string revComp(const string& seq){
	//~ string revCompSeq = "";
	//~ int pos = seq.size()-1;
	//~ char nt;
	//~ do{
		//~ nt = seq[pos];
		//~ switch (nt) {
			//~ case 'A':
				//~ revCompSeq += 'T';
				//~ break;
			//~ case 'T':
				//~ revCompSeq += 'A';
				//~ break;
			//~ case 'C':
				//~ revCompSeq += 'G';
				//~ break;
			//~ case 'G':
				//~ revCompSeq += 'C';
				//~ break;
		//~ }
		//~ --pos;
	//~ } while (pos>=0);
	//~ return revCompSeq;
//~ }

//~ string getCanonical(const string& seq){
	//~ string revCompSeq = revComp(seq);
	//~ return min(seq, revCompSeq);
//~ }

//~ string getKmer(const string& sequence, int posi, int k){
	//~ return getCanonical(sequence.substr(posi, k));
//~ }

//~ void getKmersFromRead(const string& readSeq, int k, unordered_map<string, int>& kmersFromFile){
	//~ for (uint posi(0); posi < readSeq.size()-k+1; ++posi){
		//~ string kmer = getKmer(readSeq, posi, k);
		//~ if (not kmersFromFile.count(kmer)){
			//~ kmersFromFile[kmer] = 1;
		//~ } else {
			//~ kmersFromFile[kmer] += 1;
		//~ }
	//~ }
//~ }

//~ void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){
	 //~ for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){
		//~ if (iter->second >1){
			//~ solidKmers[iter->first] = iter->second;
		//~ }
	 //~ }
//~ }

//~ vector<int> removeDuplicates(const vector<int>& vect){
	//~ vector<int> vectResult;
	//~ for (uint i(0); i< vect.size(); ++i){
		//~ if (i == vect.size()-1 or vect[i]!=vect[i+1]){
			//~ vectResult.push_back(vect[i]);
		//~ }
	//~ }
	//~ return vectResult;
//~ }

//~ void putKmersToWindowsTarget(const unordered_map <string, int>& solidKmers, unordered_map <string, vector<int>>& kmerToWindows, const string& target, int indexWindow, uint posiOnTarget, int w, int k){
	//~ for (uint posInW(0); posInW < posiOnTarget+w; ++posInW){
		//~ string kmer = getKmer(target, posInW, k);
		//~ if (solidKmers.count(kmer)){
			//~ if (not kmerToWindows.count(kmer)){
				//~ vector<int> vecIndexes;
				//~ vecIndexes.push_back(indexWindow);
				//~ kmerToWindows[kmer] = vecIndexes;
			//~ } else {
				//~ kmerToWindows[kmer].push_back(indexWindow);
				//~ sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end());
				//~ vector <int> vect = removeDuplicates(kmerToWindows[kmer]);
				//~ kmerToWindows[kmer] = vect;
			//~ }
		//~ } else {
			//~ cout << kmer << endl;
		//~ }
	//~ }
//~ }

//~ void getSimilarityWindowQuery(int posiOnQuery, string readSeq, int k, int w, unordered_map <string, int> solidKmers, unordered_map <string, vector<int>> kmerToWindowsTarget, unordered_map<int,double>& similarity){
	//~ int nbKmersinWindowQuery(0);
	//~ for (int posInW(0); posInW < posiOnQuery+w; ++posInW){
		//~ string kmer = getKmer(readSeq, posInW, k);
		//~ if (solidKmers.count(kmer)){
			//~ ++ nbKmersinWindowQuery;
			//~ if (kmerToWindowsTarget.count(kmer)){ //  kmer is in target
				//~ for (uint i(0); i<kmerToWindowsTarget[kmer].size();++i){
					//~ int winT(kmerToWindowsTarget[kmer][i]);
					//~ if (similarity.count(winT)==1){
						//~ ++ similarity[winT];
					//~ } else {
						//~ similarity[winT] = 1;
					//~ }
				//~ }
			//~ }
		//~ }
	//~ }
	//~ for (auto iter(similarity.begin()); iter != similarity.end(); ++iter ){
		//~ if (iter->second != 0){
			//~ iter->second /= nbKmersinWindowQuery;
		//~ }
	//~ }
//~ }

//~ int main(int argc, char ** argv){
	//~ if (argc < 4){
		//~ cout << "command line: ./rnaLR reads.fasta k w" << endl;
	//~ } else {
		//~ int k = stoi(argv[2]);
		//~ int w = stoi(argv[3]);
		//~ string target = "AATCGATTCTT";
		//~ vector<string> query = {"AATCGATTCTTGTGGGCCCTGAGATCGATTCTT", revComp(target)};
		//~ unordered_map <string, int> kmersFromFile;
		//~ unordered_map <string, int> solidKmers;
		//~ unordered_map <string, vector<int>> kmerToWindows;
		//~ getKmersFromRead(target, k, kmersFromFile);
		//~ for (uint s(0); s < query.size(); ++s){
			//~ getKmersFromRead(query[s], k, kmersFromFile);
		//~ }
		//~ getSolidKmers(kmersFromFile, solidKmers);
		//~ uint posi(0);
		//~ int indexWindow(0);
		//~ do{
			//~ putKmersToWindowsTarget(solidKmers, kmerToWindows, target, indexWindow, posi, w, k);
			//~ ++ indexWindow;
			//~ posi += w;
		//~ } while (posi < target.size()-w-k+2);

		//~ for (uint reads(0); reads < query.size(); ++reads){
			//~ cout << "read n" <<  reads << endl;
			//~ uint posiOnQuery(0);
			//~ int indexWindowQuery(0);
			//~ do{
			//~ unordered_map<int,double> similarity;  //key: window on target/value: score
			//~ getSimilarityWindowQuery(posiOnQuery, query[reads], k, w, solidKmers, kmerToWindows, similarity);
			//~ for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){
				//~ if (iter->second >= 0.5){
					//~ cout << iter->first << " " << indexWindowQuery << " " << iter->second << endl;
				//~ }
			//~ }
			//~ ++ indexWindowQuery;
			//~ posiOnQuery += w;
			//~ } while (posiOnQuery < query[reads].size()-w-k+2);
		//~ }
		//~ return 0;
	//~ }
//~ }

struct window{
	int index;
	int read;

    bool operator==(const window& a) const
	{
		return (index == a.index && read == a.read);
	}
};

uint64_t transformWindowToHash(window win){
	hash<int> winHash;
	return winHash(win.read + win.index);
}

namespace std { template <> struct hash<window> {
	typedef window argument_type;
	typedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; }

struct compareWindow{
    bool operator()(const window& win1, const window& win2){
        return win1.index <win2.index;
    }
};

vector<window> removeDuplicates(const vector<window>& vect){
	vector<window> vectResult;
	for (uint i(0); i< vect.size(); ++i){
		if (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){
			vectResult.push_back(vect[i]);
		}
	}
	return vectResult;
}

string revComp(const string& seq){
	string revCompSeq = "";
	int pos = seq.size()-1;
	char nt;
	do{
		nt = seq[pos];
		switch (nt) {
			case 'A':
				revCompSeq += 'T';
				break;
			case 'T':
				revCompSeq += 'A';
				break;
			case 'C':
				revCompSeq += 'G';
				break;
			case 'G':
				revCompSeq += 'C';
				break;
		}
		--pos;
	} while (pos>=0);
	return revCompSeq;
}

string getCanonical(const string& seq){
	string revCompSeq = revComp(seq);
	return min(seq, revCompSeq);
}

string getKmer(const string& sequence, int posi, int k){
	return getCanonical(sequence.substr(posi, k));
}

void setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){
	if (solidKmers.count(kmer)){
		window win({indexWindow, indexRead});
		if (kmerToWindows.count(kmer)){
			kmerToWindows[kmer].push_back(win);
			sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow());
			kmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]);
		} else {
			vector <window> vectWin({win});
			kmerToWindows[kmer] = vectWin;
		}
	}
}

void getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){
	for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){
		string readSequence(readSet[indexRead]);
		if (not readSequence.empty()) {
			int position(0);
			int posiForKmer;
			string kmer;
			int indexWindow(0);
			while (position != -1){
				if (position + w + k - 1 < (int)readSequence.size()){
					posiForKmer = position;
					position += w;
				} else {
					posiForKmer = readSequence.size() - w - k + 1;
					position = -1;
				}
				for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){
					kmer = getKmer(readSequence, iter, k);
					setKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows);
				}
				++indexWindow;
			}
			//~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){
				//~ cout << iter->first << endl;
				//~ for (uint i(0); i <iter->second.size();++i){
					//~ cout << "index:"<<iter->second[i].index <<  " read:" <<iter->second[i].read << endl;
				//~ }
			//~ }
		}
	}
}

void getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){
	for (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){
		string readSequence(readSet[readIndex]);
		if (not readSequence.empty()){
			int position(0);
			string kmer;

			while (position + k - 1 < (int)readSequence.size()){
				kmer = getKmer(readSequence, position, k);
				if (kmersFromFile.count(kmer)){
					++kmersFromFile[kmer];
				} else {
					kmersFromFile[kmer] = 1;
				}
				++position;
			}
		}
	}
}

void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){
	 for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){
		if (iter->second > 1){
			solidKmers[iter->first] = iter->second;
		}
	 }
}

void compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){
	for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){
		string readSequence(readSet[indexRead]);
		if (not readSequence.empty()){
			int position(0), posiForKmer(0);
			uint indexWindow(0);
			while (position != -1){
				uint nbKmers(0);
				unordered_map<window, double> similarity;
				if (position + w + k - 1 <(int) readSequence.size()){
					posiForKmer = position;
					position += w;
				} else {
					posiForKmer = readSequence.size() - w - k + 1;
					position = -1;
				}
				for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){
					string kmer = getKmer(readSequence, iter, k);
					if (solidKmers.count(kmer)){
						++ nbKmers;
						for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){
							for (uint i(0); i<iter->second.size(); ++i){
								if (iter->second[i].read != (int)indexRead){
									if (kmer == iter->first){
										if (similarity.count(iter->second[i])){
											++similarity[iter->second[i]];
										} else {
											similarity[iter->second[i]] = 1;
										}
									}
								}
							}
						}
					}
				}
				for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){
					iter->second /= nbKmers;
					if (iter->second >= 0.7){
						cout << "reads:" << iter->first.read << " " << indexRead << " windows:" << iter->first.index << " " << indexWindow <<  " score:" << iter->second <<endl;
					}
				}
				++indexWindow;
			}
		}
		break;
	}
}

int main(int argc, char ** argv){
	if (argc < 4){
		cout << "command line: ./rnaLR reads.fasta k w" << endl;
	} else {
		string fileName = argv[1];
		uint k = stoi(argv[2]);
		uint w = stoi(argv[3]);
		ifstream readFile(fileName);
        //~ ofstream out("out.fa");
		//~ vector <string> readSet ({"AATCGATTCTT", "AATCGATTCTT", "AATCGATTCTT"});
		//~ vector <string> readSet ({"AATCGATTCTT", revComp("AATCGATTCTT")});
		vector <string> readSet;
		string sequence;
		while (not readFile.eof()){
            getline(readFile, sequence);
			getline(readFile, sequence);
			readSet.push_back(sequence);
		}
		unordered_map <string, int> kmersFromFile; //  TODO: destroy
		unordered_map <string, int> solidKmers;
		unordered_map <string, vector<window>> kmerToWindows;
		getKmersinFromReadsInMap(k, readSet, kmersFromFile);
		getSolidKmers(kmersFromFile, solidKmers);
		getKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows);
		compareReadWindows(k, w, readSet, solidKmers, kmerToWindows);
	}
	return 0;
}

<commit_msg>ordered output<commit_after>#include <fstream>
#include <cstring>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

struct window{
	int index;
	int read;

    bool operator==(const window& a) const
	{
		return (index == a.index && read == a.read);
	}
};

uint64_t transformWindowToHash(window win){
	hash<int> winHash;
	return winHash(win.read + win.index);
}

namespace std { template <> struct hash<window> {
	typedef window argument_type;
	typedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; }

struct compareWindow{
    bool operator()(const window& win1, const window& win2){
        return win1.index <win2.index;
    }
};

vector<window> removeDuplicates(const vector<window>& vect){
	vector<window> vectResult;
	for (uint i(0); i< vect.size(); ++i){
		if (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){
			vectResult.push_back(vect[i]);
		}
	}
	return vectResult;
}

string revComp(const string& seq){
	string revCompSeq = "";
	int pos = seq.size()-1;
	char nt;
	do{
		nt = seq[pos];
		switch (nt) {
			case 'A':
				revCompSeq += 'T';
				break;
			case 'T':
				revCompSeq += 'A';
				break;
			case 'C':
				revCompSeq += 'G';
				break;
			case 'G':
				revCompSeq += 'C';
				break;
		}
		--pos;
	} while (pos>=0);
	return revCompSeq;
}

string getCanonical(const string& seq){
	string revCompSeq = revComp(seq);
	return min(seq, revCompSeq);
}

string getKmer(const string& sequence, int posi, int k){
	return getCanonical(sequence.substr(posi, k));
}

void setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){
	if (solidKmers.count(kmer)){
		window win({indexWindow, indexRead});
		if (kmerToWindows.count(kmer)){
			kmerToWindows[kmer].push_back(win);
			sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow());
			kmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]);
		} else {
			vector <window> vectWin({win});
			kmerToWindows[kmer] = vectWin;
		}
	}
}

void getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){
	for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){
		string readSequence(readSet[indexRead]);
		if (not readSequence.empty()) {
			int position(0);
			int posiForKmer;
			string kmer;
			int indexWindow(0);
			while (position != -1){
				if (position + w + k - 1 < (int)readSequence.size()){
					posiForKmer = position;
					position += w;
				} else {
					posiForKmer = readSequence.size() - w - k + 1;
					position = -1;
				}
				for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){
					kmer = getKmer(readSequence, iter, k);
					setKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows);
				}
				++indexWindow;
			}
			//~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){
				//~ cout << iter->first << endl;
				//~ for (uint i(0); i <iter->second.size();++i){
					//~ cout << "index:"<<iter->second[i].index <<  " read:" <<iter->second[i].read << endl;
				//~ }
			//~ }
		}
	}
}

void getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){
	for (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){
		string readSequence(readSet[readIndex]);
		if (not readSequence.empty()){
			int position(0);
			string kmer;

			while (position + k - 1 < (int)readSequence.size()){
				kmer = getKmer(readSequence, position, k);
				if (kmersFromFile.count(kmer)){
					++kmersFromFile[kmer];
				} else {
					kmersFromFile[kmer] = 1;
				}
				++position;
			}
		}
	}
}

void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){
	 for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){
		if (iter->second > 1){
			solidKmers[iter->first] = iter->second;
		}
	 }
}

void compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){
	for (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){
		string readSequence(readSet[indexRead]);
		if (not readSequence.empty()){
			int position(0), posiForKmer(0);
			uint indexWindow(0);
			while (position != -1){
				uint nbKmers(0);
				unordered_map<window, double> similarity;
				if (position + w + k - 1 <(int) readSequence.size()){
					posiForKmer = position;
					position += w;
				} else {
					posiForKmer = readSequence.size() - w - k + 1;
					position = -1;
				}
				for (int iter(posiForKmer); iter < posiForKmer + w; ++iter){
					string kmer = getKmer(readSequence, iter, k);
					if (solidKmers.count(kmer)){
						++ nbKmers;
						for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){
							for (uint i(0); i<iter->second.size(); ++i){
								if (iter->second[i].read != (int)indexRead){
									if (kmer == iter->first){
										if (similarity.count(iter->second[i])){
											++similarity[iter->second[i]];
										} else {
											similarity[iter->second[i]] = 1;
										}
									}
								}
							}
						}
					}
				}
				for (uint rIndex(0); rIndex<readSet.size();++rIndex){  // to order the output in cout
					//~ cout << rIndex << endl;
					for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){
						if (iter->first.read == rIndex){  // to order the output in cout
							iter->second /= nbKmers;
							if (iter->second >= 0.7){
								cout << "reads:" << iter->first.read << " " << indexRead << " windows:" << iter->first.index << " " << indexWindow <<  " score:" << iter->second <<endl;
							}
						}
					}
				}
				++indexWindow;
			}
		}
		break; // REMOVE IF all v all
	}
}

int main(int argc, char ** argv){
	if (argc < 4){
		cout << "command line: ./rnaLR reads.fasta k w" << endl;
	} else {
		string fileName = argv[1];
		uint k = stoi(argv[2]);
		uint w = stoi(argv[3]);
		ifstream readFile(fileName);
		vector <string> readSet;
		string sequence;
		while (not readFile.eof()){
            getline(readFile, sequence);
			getline(readFile, sequence);
			readSet.push_back(sequence);
		}
		unordered_map <string, int> kmersFromFile; //  TODO: destroy
		unordered_map <string, int> solidKmers;
		unordered_map <string, vector<window>> kmerToWindows;
		getKmersinFromReadsInMap(k, readSet, kmersFromFile);
		getSolidKmers(kmersFromFile, solidKmers);
		getKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows);
		compareReadWindows(k, w, readSet, solidKmers, kmerToWindows);
	}
	return 0;
}

<|endoftext|>


<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>
#include "utils/utils.h"

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

// TODO: box instead of triangle
// TODO: mouse, keyboard (camera.cpp / hpp ? )

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(800, 600, "Triangle", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); // TODO: describe GL_CULL_FACE!
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  float speed = 0.1f; // units per second
  glm::vec3 position(0, 0, 5); // Camera is at (0, 0, 5)
  float horizontalAngleRad = 3.14f; // horizontal angle : toward -Z
  float verticalAngleRad = 0.0f; // vertical angle : 0, look at the horizon
  float mouseSpeedRad = 0.0025f;

  glm::mat4 projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.3f, 100.0f);

  GLint matrixId = glGetUniformLocation(programId, "MVP");

  auto startTime = std::chrono::high_resolution_clock::now();

  // hide cursor
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    auto duration = currentTime - startTime;
    float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    float deltaTimeSec = deltaTimeMs/1000.0f;
    float rotationTimeMs = 3000.0f;
    float currentRotation = deltaTimeMs / rotationTimeMs;
    float angle = 360.0f*(currentRotation - (long)currentRotation);

    int windowWidth, windowHeight;
    glfwGetWindowSize(window, &windowWidth, &windowHeight);

    double mouseX, mouseY;
    glfwGetCursorPos(window, &mouseX, &mouseY);

    horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth/2 - mouseX);
    verticalAngleRad   += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight/2 - mouseY);

    glfwSetCursorPos(window, windowWidth/2, windowHeight/2);

    // Direction : Spherical coordinates to Cartesian coordinates conversion
    glm::vec3 direction(
        cos(verticalAngleRad) * sin(horizontalAngleRad),
        sin(verticalAngleRad),
        cos(verticalAngleRad) * cos(horizontalAngleRad)
    );

    // Right vector
    glm::vec3 right = glm::vec3(
        sin(horizontalAngleRad - 3.14f/2.0f),
        0,
        cos(horizontalAngleRad - 3.14f/2.0f)
    );

    glm::vec3 up = glm::cross( right, direction );

    // Move forward
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){
      position += direction * deltaTimeSec * speed;
    }
    // Move backward
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){
      position -= direction * deltaTimeSec * speed;
    }
    // Strafe left
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){
      position -= right * deltaTimeSec * speed;
    }
    // Strafe right
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){
      position += right * deltaTimeSec * speed;
    }

    // Camera matrix
    glm::mat4 view = glm::lookAt(position, position + direction, up);
    glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f);
    glm::mat4 mvp = projection * view * model; // Remember, matrix multiplication is the other way around
    glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  return 0;
}
<commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>
#include "utils/utils.h"

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

// TODO: box instead of triangle
// TODO: mouse, keyboard (camera.cpp / hpp ? )

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(800, 600, "Triangle", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); // TODO: describe GL_CULL_FACE!
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  static const float speed = 0.1f; // units per second
  glm::vec3 position(0, 0, 5); // Camera is at (0, 0, 5)
  float horizontalAngleRad = 3.14f; // horizontal angle : toward -Z
  float verticalAngleRad = 0.0f; // vertical angle : 0, look at the horizon
  static const float mouseSpeedRad = 0.0025f;

  glm::mat4 projection = glm::perspective(90.0f, 4.0f / 3.0f, 0.3f, 100.0f);

  GLint matrixId = glGetUniformLocation(programId, "MVP");

  auto startTime = std::chrono::high_resolution_clock::now();

  // TODO: getViewMatrix
  // in: float deltaTimeMs, context: { horizontalAngleRad, verticalAngleRad, position, ... }
  // out: view metrix

  // hide cursor
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    auto duration = currentTime - startTime;
    float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    float deltaTimeSec = deltaTimeMs/1000.0f;
    float rotationTimeMs = 3000.0f;
    float currentRotation = deltaTimeMs / rotationTimeMs;
    float angle = 360.0f*(currentRotation - (long)currentRotation);

    int windowWidth, windowHeight;
    glfwGetWindowSize(window, &windowWidth, &windowHeight);

    double mouseX, mouseY;
    glfwGetCursorPos(window, &mouseX, &mouseY);

    horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth/2 - mouseX);
    verticalAngleRad   += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight/2 - mouseY);

    glfwSetCursorPos(window, windowWidth/2, windowHeight/2);

    // Direction : Spherical coordinates to Cartesian coordinates conversion
    glm::vec3 direction(
        cos(verticalAngleRad) * sin(horizontalAngleRad),
        sin(verticalAngleRad),
        cos(verticalAngleRad) * cos(horizontalAngleRad)
    );

    // Right vector
    glm::vec3 right = glm::vec3(
        sin(horizontalAngleRad - 3.14f/2.0f),
        0,
        cos(horizontalAngleRad - 3.14f/2.0f)
    );

    glm::vec3 up = glm::cross( right, direction );

    // Move forward
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){
      position += direction * deltaTimeSec * speed;
    }
    // Move backward
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){
      position -= direction * deltaTimeSec * speed;
    }
    // Strafe left
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){
      position -= right * deltaTimeSec * speed;
    }
    // Strafe right
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){
      position += right * deltaTimeSec * speed;
    }

    // Camera matrix
    glm::mat4 view = glm::lookAt(position, position + direction, up);
    glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f);
    glm::mat4 mvp = projection * view * model; // Remember, matrix multiplication is the other way around
    glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  return 0;
}
<|endoftext|>