<commit_before>#include <SDL2/SDL.h>

#include "kdmap.h"
#include "kdtree.h"
#include "client.h"
#include "renderer.h"
#include "engine.h"

// we load assets in a different thread
enum {
    kLoadInProgress, // loading in progress
    kLoadFailed,     // loading failed
    kLoadSucceeded   // loading succeeded
};

struct loadThreadData {
    kdMap gMap;
    world gWorld;
    SDL_atomic_t done;
};

static bool loadThread(void *threadData) {
    loadThreadData *data = (loadThreadData*)threadData;

    auto read = u::read("maps/garden.kdgz", "rb");
    if (read) {
        if (!data->gMap.load(*read))
            goto error;
        if (!data->gWorld.load(data->gMap))
            goto error;
        SDL_AtomicSet(&data->done, kLoadSucceeded);
        return true;
    }
error:
    SDL_AtomicSet(&data->done, kLoadFailed);
    return false;
}

static void screenShot(const u::string &file) {
    const size_t screenWidth = neoWidth();
    const size_t screenHeight = neoHeight();
    const size_t screenSize = screenWidth * screenHeight;
    SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, screenWidth, screenHeight,
        8*3, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
    SDL_LockSurface(temp);
    unsigned char *pixels = new unsigned char[screenSize * 3];
    // make sure we're reading from the final framebuffer when obtaining the pixels
    // for the screenshot.
    gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    gl::ReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    texture::reorient(pixels, screenWidth, screenHeight, 3, screenWidth * 3,
        (unsigned char *)temp->pixels, false, true, false);
    SDL_UnlockSurface(temp);
    delete[] pixels;
    SDL_SaveBMP(temp, file.c_str());
    SDL_FreeSurface(temp);
}

int neoMain(int argc, char **argv) {
    argc--;
    argv++;
    if (argc == 2)
        neoResize(atoi(argv[0]), atoi(argv[1]));

    splashScreen gSplash;
    gSplash.load("textures/logo.png");
    gSplash.upload();

    rendererPipeline pipeline;
    m::perspectiveProjection projection;
    projection.fov = 90.0f;
    projection.width = neoWidth();
    projection.height = neoHeight();
    projection.nearp = 1.0f;
    projection.farp = 2048.0f;

    pipeline.setPerspectiveProjection(projection);
    pipeline.setWorldPosition(m::vec3(0.0f, 0.0f, 0.0f));

    // create a loader thread
    loadThreadData loadData;
    SDL_AtomicSet(&loadData.done, kLoadInProgress);
    SDL_CreateThread((SDL_ThreadFunction)&loadThread, nullptr, (void*)&loadData);

    // while that thread is running render the loading screen
    uint32_t splashTime = SDL_GetTicks();
    while (SDL_AtomicGet(&loadData.done) == kLoadInProgress) {
        glClear(GL_COLOR_BUFFER_BIT);
        gSplash.render(0.002f * (float)(SDL_GetTicks() - splashTime), pipeline);
        neoSwap();
    }

    if (SDL_AtomicGet(&loadData.done) != kLoadSucceeded)
        return 1;

    // we're done loading the resources, now upload them (we can't render a loading
    // screen when uploading so we assume the process will be sufficently fast.)
    loadData.gWorld.upload(projection);

    // Now render the world
    client gClient;

    uint32_t time;
    uint32_t oldTime;
    uint32_t fpsTime;
    uint32_t fpsCounter = 0;

    uint32_t curTime = SDL_GetTicks();
    oldTime = curTime;
    fpsTime = curTime;

    bool running = true;
    while (running) {
        time = SDL_GetTicks();
        float dt = 0.001f * (float)(time - oldTime);
        oldTime = time;
        fpsCounter++;
        if (time - fpsTime > 1000.0f) {
            u::string title = u::format("Neothyne: (%zu FPS)", fpsCounter);
            neoSetWindowTitle(title.c_str());
            fpsCounter = 0;
            fpsTime = time;
        }

        gClient.update(loadData.gMap, dt);

        pipeline.setRotation(gClient.getRotation());
        pipeline.setPosition(gClient.getPosition());

        loadData.gWorld.render(pipeline);

        neoSwap();

        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            switch (e.type) {
                case SDL_QUIT:
                    SDL_Quit();
                    return 0;
                case SDL_WINDOWEVENT:
                    switch (e.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            // Resize the window
                            neoResize(e.window.data1, e.window.data2);
                            projection.width = neoWidth();
                            projection.height = neoHeight();
                            pipeline.setPerspectiveProjection(projection);
                            break;
                    }
                    break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            running = false;
                            break;
                        case SDLK_F8:
                            screenShot("screenshot.bmp");
                            break;
                        case SDLK_F12:
                            neoToggleRelativeMouseMode();
                            break;
                    }
                    neoKeyState(e.key.keysym.sym, true);
                    break;
                case SDL_KEYUP:
                    neoKeyState(e.key.keysym.sym, false, true);
                    break;
            }
        }
    }
    return 0;
}
<commit_msg>More accurate frame timer.<commit_after>#include <SDL2/SDL.h>

#include "kdmap.h"
#include "kdtree.h"
#include "client.h"
#include "renderer.h"
#include "engine.h"

// we load assets in a different thread
enum {
    kLoadInProgress, // loading in progress
    kLoadFailed,     // loading failed
    kLoadSucceeded   // loading succeeded
};

struct loadThreadData {
    kdMap gMap;
    world gWorld;
    SDL_atomic_t done;
};

static bool loadThread(void *threadData) {
    loadThreadData *data = (loadThreadData*)threadData;

    auto read = u::read("maps/garden.kdgz", "rb");
    if (read) {
        if (!data->gMap.load(*read))
            goto error;
        if (!data->gWorld.load(data->gMap))
            goto error;
        SDL_AtomicSet(&data->done, kLoadSucceeded);
        return true;
    }
error:
    SDL_AtomicSet(&data->done, kLoadFailed);
    return false;
}

static void screenShot(const u::string &file) {
    const size_t screenWidth = neoWidth();
    const size_t screenHeight = neoHeight();
    const size_t screenSize = screenWidth * screenHeight;
    SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, screenWidth, screenHeight,
        8*3, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
    SDL_LockSurface(temp);
    unsigned char *pixels = new unsigned char[screenSize * 3];
    // make sure we're reading from the final framebuffer when obtaining the pixels
    // for the screenshot.
    gl::BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    gl::ReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pixels);
    texture::reorient(pixels, screenWidth, screenHeight, 3, screenWidth * 3,
        (unsigned char *)temp->pixels, false, true, false);
    SDL_UnlockSurface(temp);
    delete[] pixels;
    SDL_SaveBMP(temp, file.c_str());
    SDL_FreeSurface(temp);
}

struct frameTimer {
    frameTimer() :
        m_deltaTime(0.0f),
        m_lastFrameTicks(0),
        m_currentTicks(0),
        m_frameAverage(0.0f),
        m_framesPerSecond(0)
    {
        reset();
        cap(kMaxFPS);
    }

    static constexpr size_t kMaxFPS = 0; // For capping framerate (0 = disabled)
    static constexpr float kDampenEpsilon = 0.00001f; // The dampening to remove flip-flip in frame metrics

    void cap(float maxFps) {
        m_maxFrameTicks = maxFps <= 0.0f
            ? -1 : (1000.0f / maxFps) - kDampenEpsilon;
    }

    void reset(void) {
        m_frameCount = 0;
        m_minTicks = 1000;
        m_maxTicks = 0;
        m_averageTicks = 0;
        m_lastSecondTicks = SDL_GetTicks();
    }

    bool update(void) {
        m_frameCount++;
        m_targetTicks = m_maxFrameTicks != -1 ?
            m_lastSecondTicks + uint32_t(m_frameCount * m_maxFrameTicks) : 0;
        m_currentTicks = SDL_GetTicks();
        m_averageTicks += m_currentTicks - m_lastFrameTicks;
        if (m_currentTicks - m_lastFrameTicks <= m_minTicks)
            m_minTicks = m_currentTicks - m_lastFrameTicks;
        if (m_currentTicks - m_lastFrameTicks >= m_maxTicks)
            m_maxTicks = m_currentTicks - m_lastFrameTicks;
        if (m_targetTicks && m_currentTicks < m_targetTicks) {
            uint32_t beforeDelay = SDL_GetTicks();
            SDL_Delay(m_targetTicks - m_currentTicks);
            m_currentTicks = SDL_GetTicks();
            m_averageTicks += m_currentTicks - beforeDelay;
        }
        m_deltaTime = 0.001f * (m_currentTicks - m_lastFrameTicks);
        m_lastFrameTicks = m_currentTicks;
        if (m_currentTicks - m_lastSecondTicks >= 1000) {
            m_framesPerSecond = m_frameCount;
            m_frameAverage = m_averageTicks / m_frameCount;
            m_frameMin = m_minTicks;
            m_frameMax = m_maxTicks;
            reset();
            return true;
        }
        return false;
    }

    float mspf(void) const {
        return m_frameAverage;
    }

    int fps(void) const {
        return m_framesPerSecond;
    }

    float delta(void) const {
        return m_deltaTime;
    }

    uint32_t ticks(void) const {
        return m_currentTicks;
    }

private:
    float m_maxFrameTicks;
    uint32_t m_lastSecondTicks;
    int m_frameCount;
    uint32_t m_minTicks;
    uint32_t m_maxTicks;
    float m_averageTicks;
    float m_deltaTime;
    uint32_t m_lastFrameTicks;
    uint32_t m_currentTicks;
    uint32_t m_targetTicks;
    uint32_t m_frameMin;
    uint32_t m_frameMax;
    float m_frameAverage;
    int m_framesPerSecond;
};

int neoMain(int argc, char **argv) {
    argc--;
    argv++;
    if (argc == 2)
        neoResize(atoi(argv[0]), atoi(argv[1]));

    frameTimer gTimer;

    splashScreen gSplash;
    gSplash.load("textures/logo.png");
    gSplash.upload();

    rendererPipeline pipeline;
    m::perspectiveProjection projection;
    projection.fov = 90.0f;
    projection.width = neoWidth();
    projection.height = neoHeight();
    projection.nearp = 1.0f;
    projection.farp = 2048.0f;

    pipeline.setPerspectiveProjection(projection);
    pipeline.setWorldPosition(m::vec3(0.0f, 0.0f, 0.0f));

    // create a loader thread
    loadThreadData loadData;
    SDL_AtomicSet(&loadData.done, kLoadInProgress);
    SDL_CreateThread((SDL_ThreadFunction)&loadThread, nullptr, (void*)&loadData);

    // while that thread is running render the loading screen
    gTimer.cap(30); // Loading screen at 30fps
    while (SDL_AtomicGet(&loadData.done) == kLoadInProgress) {
        glClear(GL_COLOR_BUFFER_BIT);
        gSplash.render(gTimer.ticks() / 500.0f, pipeline);
        neoSwap();
        gTimer.update();
    }

    if (SDL_AtomicGet(&loadData.done) != kLoadSucceeded)
        return 1;

    // we're done loading the resources, now upload them (we can't render a loading
    // screen when uploading so we assume the process will be sufficently fast.)
    loadData.gWorld.upload(projection);

    // Now render the world
    client gClient;

    gTimer.cap(0); // don't cap the world
    bool running = true;
    while (running) {
        neoSetWindowTitle(u::format("Neothyne: %d fps : %.2f mspf",
            gTimer.fps(), gTimer.mspf()).c_str());

        gClient.update(loadData.gMap, gTimer.delta());

        pipeline.setRotation(gClient.getRotation());
        pipeline.setPosition(gClient.getPosition());

        loadData.gWorld.render(pipeline);

        neoSwap();
        gTimer.update();

        SDL_Event e;
        while (SDL_PollEvent(&e)) {
            switch (e.type) {
                case SDL_QUIT:
                    SDL_Quit();
                    return 0;
                case SDL_WINDOWEVENT:
                    switch (e.window.event) {
                        case SDL_WINDOWEVENT_RESIZED:
                            // Resize the window
                            neoResize(e.window.data1, e.window.data2);
                            projection.width = neoWidth();
                            projection.height = neoHeight();
                            pipeline.setPerspectiveProjection(projection);
                            break;
                    }
                    break;
                case SDL_KEYDOWN:
                    switch (e.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            running = false;
                            break;
                        case SDLK_F8:
                            screenShot("screenshot.bmp");
                            break;
                        case SDLK_F12:
                            neoToggleRelativeMouseMode();
                            break;
                    }
                    neoKeyState(e.key.keysym.sym, true);
                    break;
                case SDL_KEYUP:
                    neoKeyState(e.key.keysym.sym, false, true);
                    break;
            }
        }
    }
    return 0;
}
<|endoftext|>


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

class NFA
{
private:
	struct State
	{
		// TODO: variabl state_number is for debugging purpose
		// and should be removed later
		int state_number;
		std::vector<std::pair<char, State*>> next;
	};

public:
	NFA() : head(nullptr), tail(nullptr)
	{ }

	explicit NFA(char c)
	{
		// TODO: SHOULD I EMPLACE OR PUSH BACK ??
		states.emplace_back(std::make_unique<State>());
		states.emplace_back(std::make_unique<State>());

		head = states.front().get();
		tail = states.back().get();

		head->next.push_back(std::make_pair(c, tail));
	}

	bool empty()
	{
		return head == tail && head == nullptr;
	}

	void concat(NFA&& nfa)
	{
		tail->next.push_back(std::make_pair('\0', nfa.head));
		tail = nfa.tail;

		states.insert(states.end(),
		              make_move_iterator(nfa.states.begin()),
		              make_move_iterator(nfa.states.end()));
	}

	void make_union(NFA&& nfa)
	{
		states.emplace_back(std::make_unique<State>());
		auto new_head = states.back().get();
		states.emplace_back(std::make_unique<State>());
		auto new_tail = states.back().get();

		new_head->next.push_back(std::make_pair('\0', head));
		new_head->next.push_back(std::make_pair('\0', nfa.head));

		tail->next.push_back(std::make_pair('\0', new_tail));
		nfa.tail->next.push_back(std::make_pair('\0', new_tail));

		head = new_head;
		tail = new_tail;

		states.insert(states.end(),
		              std::make_move_iterator(nfa.states.begin()),
		              std::make_move_iterator(nfa.states.end()));
	}

	void make_kleen()
	{
		states.emplace_back(std::make_unique<State>());
		auto new_head = states.back().get();
		states.emplace_back(std::make_unique<State>());
		auto new_tail = states.back().get();

		tail->next.push_back(std::make_pair('\0', head));
		tail->next.push_back(std::make_pair('\0', new_tail));
		new_head->next.push_back(std::make_pair('\0', head));
		new_head->next.push_back(std::make_pair('\0', new_tail));

		head = new_head;
		tail = new_tail;
	}

	void print()
	{
		for (int i = 0; i < (int)states.size(); ++i) {
			auto state = states[i].get();
			state->state_number = i;
		}
		for (int i = 0; i < (int)states.size(); ++i) {
			auto p = states[i].get();
			for (auto s : p->next) {
				std::cout << "from state #" << p->state_number
				          << " through: " << (s.first == '\0' ? 'E' : s.first)
				          << " to state #" << s.second->state_number
				          << '\n';
			}
			std::cout << "--------------\n\n";
		}
	}

private:
	State *head;
	State *tail;
	std::vector<std::unique_ptr<State>> states;
};

int find_close(const std::string& s, int idx)
{
	int open = 1;

	for (int i = idx + 1; i < (int)s.length(); ++i)
	{
		switch (s[i]) {
			case '(': ++open; break;
			case ')': --open; break;
		}

		if (open == 0)
			return i;
	}

	throw std::exception();
}

NFA construct(const std::string& s, int begin, int end)
{
	// TODO: optimize by saving the opening and closing position of each paren

	std::cout << "Constructing: \"" << s.substr(begin, end - begin) << "\"\n";

	NFA current;
	for (int i = begin; i < end; ++i)
	{
		std::cout << i << std::endl;
		if (s[i] == '|') {
			current.make_union(construct(s, i + 1, end));
			i = end;
		}
		else if (s[i] == '(') {
			int close = find_close(s, i);
			NFA tmp = construct(s, i + 1, close);
			if (close + 1 < end && s[close + 1] == '*') {
				tmp.make_kleen();
				i = close + 1;
			}
			else {
				i = close;
			}
			if (current.empty())
				current = std::move(tmp);
			else
				current.concat(std::move(tmp));
		}
		else if (i + 1 < end && s[i + 1] == '*') {
			NFA tmp(s[i]);
			tmp.make_kleen();
			current.concat(std::move(tmp));
			++i;
		}
		else {
			if (current.empty())
				current = NFA(s[i]);
			else
				current.concat(NFA(s[i]));
		}
	}

	return current;
}

int main()
{
	std::string exp = "a(b|c)*";
	auto nfa = construct(exp, 0, exp.length());
	nfa.print();
}
<commit_msg>overload operators for union, concat, kleene star<commit_after>#include <iostream>
#include <vector>
#include <memory>
#include <string>

class NFA
{
private:
	struct State
	{
		// TODO: variabl state_number is for debugging purpose
		// and should be removed later
		int state_number;
		std::vector<std::pair<char, State*>> next;
	};

public:
	NFA() : head(nullptr), tail(nullptr)
	{ }

	explicit NFA(char c)
	{
		// TODO: SHOULD I EMPLACE OR PUSH BACK ??
		states.emplace_back(std::make_unique<State>());
		states.emplace_back(std::make_unique<State>());

		head = states.front().get();
		tail = states.back().get();

		head->next.push_back(std::make_pair(c, tail));
	}

	bool empty()
	{
		return head == tail && head == nullptr;
	}

	NFA& operator+=(NFA&& nfa)
	{
		if (empty()) {
			*this = std::move(nfa);
		}
		else {
			tail->next.push_back(std::make_pair('\0', nfa.head));
			tail = nfa.tail;

			states.insert(states.end(),
						make_move_iterator(nfa.states.begin()),
						make_move_iterator(nfa.states.end()));
		}

		return *this;
	}

	NFA& operator|=(NFA&& nfa)
	{
		if (empty()) {
			*this = std::move(nfa);
		}
		else {
			states.emplace_back(std::make_unique<State>());
			auto new_head = states.back().get();
			states.emplace_back(std::make_unique<State>());
			auto new_tail = states.back().get();

			new_head->next.push_back(std::make_pair('\0', head));
			new_head->next.push_back(std::make_pair('\0', nfa.head));

			tail->next.push_back(std::make_pair('\0', new_tail));
			nfa.tail->next.push_back(std::make_pair('\0', new_tail));

			head = new_head;
			tail = new_tail;

			states.insert(states.end(),
						std::make_move_iterator(nfa.states.begin()),
						std::make_move_iterator(nfa.states.end()));
		}

		return *this;
	}

	friend NFA operator*(NFA&& nfa);

	void print()
	{
		for (int i = 0; i < (int)states.size(); ++i) {
			auto state = states[i].get();
			state->state_number = i;
		}
		for (int i = 0; i < (int)states.size(); ++i) {
			auto p = states[i].get();
			for (auto s : p->next) {
				std::cout << "from state #" << p->state_number
				          << " through: " << (s.first == '\0' ? 'E' : s.first)
				          << " to state #" << s.second->state_number
				          << '\n';
			}
			std::cout << "--------------\n\n";
		}
	}

private:
	State *head;
	State *tail;
	std::vector<std::unique_ptr<State>> states;
};

NFA operator*(NFA&& nfa)
{
	nfa.states.emplace_back(std::make_unique<NFA::State>());
	auto new_head = nfa.states.back().get();
	nfa.states.emplace_back(std::make_unique<NFA::State>());
	auto new_tail = nfa.states.back().get();

	nfa.tail->next.push_back(std::make_pair('\0', nfa.head));
	nfa.tail->next.push_back(std::make_pair('\0', new_tail));
	new_head->next.push_back(std::make_pair('\0', nfa.head));
	new_head->next.push_back(std::make_pair('\0', new_tail));

	nfa.head = new_head;
	nfa.tail = new_tail;

	return std::move(nfa);
}

int find_close(const std::string& s, int idx)
{
	int open = 1;

	for (int i = idx + 1; i < (int)s.length(); ++i)
	{
		switch (s[i]) {
			case '(': ++open; break;
			case ')': --open; break;
		}

		if (open == 0)
			return i;
	}

	throw std::exception();
}

NFA construct(const std::string& s, int begin, int end)
{
	// TODO: optimize by saving the opening and closing position of each paren

	std::cout << "Constructing: \"" << s.substr(begin, end - begin) << "\"\n";

	NFA current;
	for (int i = begin; i < end; ++i)
	{
		if (s[i] == '|') {
			current |= construct(s, i + 1, end);
			i = end;
		}
		else if (s[i] == '(') {
			int close = find_close(s, i);
			if (close + 1 < end && s[close + 1] == '*') {
				current += *construct(s, i + 1, close);
				i = close + 1;
			}
			else {
				current += construct(s, i + 1, close);
				i = close;
			}
		}
		else if (i + 1 < end && s[i + 1] == '*') {
			current += *NFA(s[i]);
			++i;
		}
		else {
			current += NFA(s[i]);
		}
	}

	return current;
}

int main()
{
	std::string exp = "a(b|c)*";
	auto nfa = construct(exp, 0, exp.length());
	nfa.print();
}
<|endoftext|>


<commit_before>82d0ec9e-2749-11e6-b898-e0f84713e7b8<commit_msg>Does anyone even read these anymore???<commit_after>82d97b66-2749-11e6-9ec6-e0f84713e7b8<|endoftext|>


<commit_before>dfcfc10f-2747-11e6-911d-e0f84713e7b8<commit_msg>more bug fix<commit_after>dfde2aa1-2747-11e6-ac2b-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/thread.hpp>
#include <mutex>
template<typename T>
struct CoroutineWrapper{
    T func_;
    CoroutineWrapper(T  && func):func_(std::move(func)){
    }
    void operator()(boost::asio::yield_context yield){
        try{
            return func_(yield);
        }
        catch(boost::system::system_error const & e){
            std::cerr << "CoroutineWrapper Exception: " << e.what() << "(" << e.code() << ")\n";
        }
    }
};
class Pipe : public std::enable_shared_from_this<Pipe>{
public:
    bool errorp{false};
    using socket = boost::asio::ip::tcp::socket;
    Pipe(socket && socket0, socket && socket1):socket_0(std::move(socket0)), socket_1(std::move(socket1)), strand_(socket_0.get_io_service()){
    }
    void start();
    socket socket_0, socket_1;
    boost::asio::strand strand_;
};
void Pipe::start(){
//    std::cerr << "start\n";
    auto self = shared_from_this();
    auto read_and_write = [self](boost::asio::yield_context yield, socket & socket_src, socket & socket_dst){
        std::vector<char> buf;
        buf.resize(4096);
        while(true){
            try{
                auto length = socket_src.async_read_some(boost::asio::buffer(buf), yield);
                boost::asio::async_write(socket_dst, boost::asio::buffer(buf.data(), length), yield);
            }catch(const boost::system::system_error &e){
//                std::cerr << "normal exit:" << e.what() << "\n";
                try{
                    socket_src.close();
                }catch(const boost::system::system_error & e){
//                    std::cerr << "failed to close src:" << e.what() << "\n";
                }
                try{
                    socket_dst.close();
                }catch(const boost::system::system_error& e){
//                    std::cerr << "failed to close dst:" << e.what() << "\n";
                }

                break;
            }

        }
    };
    boost::asio::spawn(strand_, [this, read_and_write](boost::asio::yield_context yield){
        read_and_write(yield, socket_0, socket_1);
    });
    boost::asio::spawn(strand_, [this, read_and_write](boost::asio::yield_context yield){
        read_and_write(yield, socket_1, socket_0);
    });
}
class Server
{
public:
    Server(boost::asio::io_service& io_service, std::string const & host,std::string const & port,std::string const & dst_host, std::string const & dst_port)
        : acceptor_(io_service), socket_(io_service), dst_host_(dst_host), dst_port_(dst_port)
    {
        try{
            boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), std::atoi(port.c_str()));
            acceptor_.open(endpoint.protocol());
            acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
            acceptor_.bind(endpoint);
            acceptor_.listen();
        }catch(std::exception const &e){
            std::cerr << "ERROR : Failed to bind address" << std::endl;
            std::cerr << e.what() << std::endl;
        }

        do_accept();
    }

    unsigned short get_port(void){
        return acceptor_.local_endpoint().port();
    }

private:
    void do_accept()
    {
        acceptor_.async_accept(socket_,
                               [this](boost::system::error_code ec)
        {
            if (!ec)
            {
                auto & io= socket_.get_io_service();
                auto func = [socket = std::move(socket_), dst_host=dst_host_, dst_port=dst_port_](boost::asio::yield_context yield) mutable{
                    boost::asio::ip::tcp::socket socket_dst(socket.get_io_service());
                    boost::asio::ip::tcp::resolver::query query_(dst_host, dst_port);
                    boost::asio::ip::tcp::resolver resolver_(socket_dst.get_io_service());
                    auto iter = resolver_.async_resolve(query_, yield);
                    boost::asio::async_connect(socket_dst, iter, boost::asio::ip::tcp::resolver::iterator{}, yield);
                    std::make_shared<Pipe>(std::move(socket), std::move(socket_dst))->start();
                };
                boost::asio::spawn(io, CoroutineWrapper<decltype(func)>(std::move(func)));
            }

            do_accept();
        });
    }

    boost::asio::ip::tcp::acceptor acceptor_;
    boost::asio::ip::tcp::socket socket_;
    std::string dst_host_;
    std::string dst_port_;
};

int main(int argc, char *argv[])
{
    try{
        if(argc < 5){
            std::cout << "Usage: " << argv[0] << " listen_host listen_port destination_host destination_port [threads]" << std::endl;
            return 1;
        }
        auto listen_host = argv[1];
        auto listen_port = argv[2];
        auto dst_host = argv[3];
        auto dst_port = argv[4];
        auto num_of_threads = 1;
        if(argc == 6){
            num_of_threads = std::atoi(argv[5]);
        }
        num_of_threads--;

        using thread_ptr = std::shared_ptr<boost::thread>;
        std::vector<thread_ptr> threads;

        boost::asio::io_service io_service_;
        Server s(io_service_, listen_host, listen_port, dst_host, dst_port);
        for(auto i = 0; i< num_of_threads;++i){
            thread_ptr thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_)));
            threads.push_back(thread);
        }
        for(auto i = 0;i<num_of_threads;++i){
            threads[i]->join();
        }
        io_service_.run();
        return 0;
    }catch(std::exception const &e){
        std::cerr << e.what() << std::endl;
        return 2;
    }
}

<commit_msg>use a standalone function async_connect to establish connection<commit_after>#include <iostream>
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/thread.hpp>
#include <mutex>
template<typename T>
struct CoroutineWrapper{
    T func_;
    CoroutineWrapper(T  && func):func_(std::move(func)){
    }
    void operator()(boost::asio::yield_context yield){
        try{
            return func_(yield);
        }
        catch(boost::system::system_error const & e){
            std::cerr << "CoroutineWrapper Exception: " << e.what() << "(" << e.code() << ")\n";
        }
    }
};
class Pipe : public std::enable_shared_from_this<Pipe>{
public:
    bool errorp{false};
    using socket = boost::asio::ip::tcp::socket;
    Pipe(socket && socket0, socket && socket1):socket_0(std::move(socket0)), socket_1(std::move(socket1)), strand_(socket_0.get_io_service()){
    }
    void start();
    socket socket_0, socket_1;
    boost::asio::strand strand_;
};
void Pipe::start(){
//    std::cerr << "start\n";
    auto self = shared_from_this();
    auto read_and_write = [self](boost::asio::yield_context yield, socket & socket_src, socket & socket_dst){
        std::vector<char> buf;
        buf.resize(4096);
        while(true){
            try{
                auto length = socket_src.async_read_some(boost::asio::buffer(buf), yield);
                boost::asio::async_write(socket_dst, boost::asio::buffer(buf.data(), length), yield);
            }catch(const boost::system::system_error &e){
//                std::cerr << "normal exit:" << e.what() << "\n";
                try{
                    socket_src.close();
                }catch(const boost::system::system_error & e){
//                    std::cerr << "failed to close src:" << e.what() << "\n";
                }
                try{
                    socket_dst.close();
                }catch(const boost::system::system_error& e){
//                    std::cerr << "failed to close dst:" << e.what() << "\n";
                }

                break;
            }

        }
    };
    boost::asio::spawn(strand_, [this, read_and_write](boost::asio::yield_context yield){
        read_and_write(yield, socket_0, socket_1);
    });
    boost::asio::spawn(strand_, [this, read_and_write](boost::asio::yield_context yield){
        read_and_write(yield, socket_1, socket_0);
    });
}

boost::asio::ip::tcp::socket async_connect(boost::asio::io_service &io, boost::asio::yield_context yield, std::string host, std::string port){
    boost::asio::ip::tcp::socket socket(io);
    boost::asio::ip::tcp::resolver::query query_(host, port);
    boost::asio::ip::tcp::resolver resolver_(io);
    auto iter = resolver_.async_resolve(query_, yield);
    boost::asio::async_connect(socket, iter, boost::asio::ip::tcp::resolver::iterator{}, yield);
    return socket;
}

class AcceptServer
{
public:
    AcceptServer(boost::asio::io_service& io_service, std::string const & host,std::string const & port,std::string const & dst_host, std::string const & dst_port)
        : acceptor_(io_service), socket_(io_service), dst_host_(dst_host), dst_port_(dst_port)
    {
        try{
            boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), std::atoi(port.c_str()));
            acceptor_.open(endpoint.protocol());
            acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
            acceptor_.bind(endpoint);
            acceptor_.listen();
        }catch(std::exception const &e){
            std::cerr << "ERROR : Failed to bind address" << std::endl;
            std::cerr << e.what() << std::endl;
        }

        do_accept();
    }

    unsigned short get_port(void){
        return acceptor_.local_endpoint().port();
    }

private:
    void do_accept()
    {
        acceptor_.async_accept(socket_,
                               [this](boost::system::error_code ec)
        {
            if (!ec)
            {
                auto & io= socket_.get_io_service();
                auto func = [socket = std::move(socket_), dst_host=dst_host_, dst_port=dst_port_](boost::asio::yield_context yield) mutable{
                    auto socket_dst = async_connect(socket.get_io_service(), yield, dst_host, dst_port);
                    std::make_shared<Pipe>(std::move(socket), std::move(socket_dst))->start();
                };
                boost::asio::spawn(io, CoroutineWrapper<decltype(func)>(std::move(func)));
            }

            do_accept();
        });
    }

    boost::asio::ip::tcp::acceptor acceptor_;
    boost::asio::ip::tcp::socket socket_;
    std::string dst_host_;
    std::string dst_port_;
};

int main(int argc, char *argv[])
{
    try{
        if(argc < 5){
            std::cout << "Usage: " << argv[0] << " listen_host listen_port destination_host destination_port [threads]" << std::endl;
            return 1;
        }
        auto listen_host = argv[1];
        auto listen_port = argv[2];
        auto dst_host = argv[3];
        auto dst_port = argv[4];
        auto num_of_threads = 1;
        if(argc == 6){
            num_of_threads = std::atoi(argv[5]);
        }
        num_of_threads--;

        using thread_ptr = std::shared_ptr<boost::thread>;
        std::vector<thread_ptr> threads;

        boost::asio::io_service io_service_;
        AcceptServer s(io_service_, listen_host, listen_port, dst_host, dst_port);
        for(auto i = 0; i< num_of_threads;++i){
            thread_ptr thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_)));
            threads.push_back(thread);
        }
        for(auto i = 0;i<num_of_threads;++i){
            threads[i]->join();
        }
        io_service_.run();
        return 0;
    }catch(std::exception const &e){
        std::cerr << e.what() << std::endl;
        return 2;
    }
}

<|endoftext|>


<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}
<commit_msg>commented systray<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QSystemTrayIcon>
#include <QMessageBox>
#include <QAction>
#include <QMenu>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    /*if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        QMessageBox::critical(0, QObject::tr("Systray"),
                                 QObject::tr("I couldn't detect any system tray "
                                             "on this system."));
        return 1;
    }

    QObject *root = 0;
    if (engine.rootObjects().size() > 0)
    {
        root = engine.rootObjects().at(0);

        QAction *minimizeAction = new QAction(QObject::tr("Mi&nimize"), root);
        root->connect(minimizeAction, SIGNAL(triggered()), root, SLOT(hide()));
        QAction *maximizeAction = new QAction(QObject::tr("Ma&ximize"), root);
        root->connect(maximizeAction, SIGNAL(triggered()), root, SLOT(showMaximized()));
        QAction *restoreAction = new QAction(QObject::tr("&Restore"), root);
        root->connect(restoreAction, SIGNAL(triggered()), root, SLOT(showNormal()));
        QAction *quitAction = new QAction(QObject::tr("&Quit"), root);
        root->connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

        QMenu *trayIconMenu = new QMenu();
        trayIconMenu->addAction(minimizeAction);
        trayIconMenu->addAction(maximizeAction);
        trayIconMenu->addAction(restoreAction);
        trayIconMenu->addSeparator();
        trayIconMenu->addAction(quitAction);

        QSystemTrayIcon *trayIcon = new QSystemTrayIcon(root);
        trayIcon->setContextMenu(trayIconMenu);
        trayIcon->setIcon(QIcon(":/img/icon.png"));
        trayIcon->show();
    }*/

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


<commit_before>c2a731ca-2747-11e6-af6f-e0f84713e7b8<commit_msg>I'm done<commit_after>c2b3d3e3-2747-11e6-bef0-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdio>
#include "Signal.hpp"

class Foo
{
    public:

	Foo() {}

    void bar(int x, int y)
    {
        printf("Foo::bar(%d, %d)\n", x, y);
    }
};

void foobar(int x, int y)
{
    printf("foobar(%d, %d)\n", x, y);
}

int main(void)
{
    Foo foo;
    Signal<int, int> s;

    // Connect a function
    s.connect(foobar);

    // Connect a class method
    s.connect(&foo, &Foo::bar);

    // Create and connect some lambda expression
    s.connect([&foo](int x, int y){
        printf("lambda::"); foo.bar(x, y);
    });

    // Emit the signal !
    s.emit(4, 2);

    return 0;
}
<commit_msg>remove constructor in Foo<commit_after>#include <cstdio>
#include "Signal.hpp"

class Foo
{
    public:

        void bar(int x, int y)
        {
            printf("Foo::bar(%d, %d)\n", x, y);
        }
};

void foobar(int x, int y)
{
    printf("foobar(%d, %d)\n", x, y);
}

int main(void)
{
    Foo foo;
    Signal<int, int> s;

    // Connect a function
    s.connect(foobar);

    // Connect a class method
    s.connect(&foo, &Foo::bar);

    // Create and connect some lambda expression
    s.connect([&foo](int x, int y){
        printf("lambda::"); foo.bar(x, y);
    });

    // Emit the signal !
    s.emit(4, 2);

    return 0;
}
<|endoftext|>


<commit_before>/**
 * \class main
 * @file main.cpp
 *
 * @par Licence
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include "FlagParser.hpp"
#include "DatabaseReader.hpp"
#include "GnuplotHandler.hpp"
#include "VectorOfCities.hpp"
#include "help.txt.hpp"

#include <locale.h>
#include <libintl.h>

#define _(STRING) gettext(STRING)

int main(int argc, char *argv[]) {
    // Part 1 - start - parse argv and get databaseFile
    FlagParser parser(argc, argv);
    parser.printFlags();
    auto flags = parser.getFlags();

    setlocale(LC_ALL, "");
    bindtextdomain("regionalizer", "/usr/share/locale");
    textdomain("regionalizer");

    if (!parser.hasKey("--help")) {
	std::cout << _("Help not found, so moving on...");
        std::cout << std::endl;
    } else {
	std::cout << _("Help found, so I am about to print help...");
	std::cout << std::endl;
        std::cout << ___help_txt;
	std::cout << _("Aborting....");
	std::cout << std::endl;
	return -1;
    }
    if (!flags["--list"].empty()) {
        std::cout << "Great! " << flags["--list"] << " is being processed";
	std::cout << std::endl;
    } else {
	std::cout << "No list specified!";
	std::cout << std::endl;
	std::cout << _("Aborting....");
	std::cout << std::endl;
	return -1;
    }

    std::string databaseFile{flags["--list"]};
    // Part 1 - end
    // Part 2 - start - create vector of Cities based on databaseFile
    auto vec = DatabaseReader::readCitiesFromFile(databaseFile);

    // Part 2 - end
    // Part 3 - start - calculate distance from one city to the farthest

    VectorOfCities::setDistanceToTheFarthestInTheWholeVector(vec);

    // Part 3 - end
    // Part 4 - start - by brute force check which city would be
    // the best capital. We have only one region.
    // This part is just for testing "happiness level" concept
    // "Happiness level" - value from 0 to 10.
    // 10 is the best, we have 10 when we are the capital, because the
    // distance to capital is equal to zero.
    // 0 is when the capital is the farthest city.
    // Formula: HL = 10 - ((distanceFrom(capital) / distanceToTheFarthest)*10)
    if (parser.hasKey("-N") && flags["-N"] == "1") {
        VectorOfCities::calculateHappinessLevelForOneRegionByBruteForce(vec);
    } else if (parser.hasKey("-N") && flags["-N"] == "2") {
	VectorOfCities::calculateHappinessLevelForTwoRegionsByBruteForce(vec);
    } else if (parser.hasKey("-N") && std::stoi(flags["-N"]) > 2) {
        auto capitals = VectorOfCities::regionalizeUsingRandom(vec,
                flags["-N"]);
	GnuplotHandler::plotHappinessIndex(vec, capitals);
    }
    // Part 4 - end
    // Part <last> - start - save to gnuplot.

    // Gnuploting temporary disabled
    /*
    if (!GnuplotHandler::isGnuplotInstalledOnHost()) {
        std::cout << "Gnuplot is not installed on host";
        std::cout << std::endl;
        std::cout << "Aborting...";
	return -1;
    }
    GnuplotHandler::saveDummyPlot();
    GnuplotHandler::plotPopulation(vec);
    GnuplotHandler::plotHappinessLevelWhenWeHaveOnlyOneRegion(vec);
    */
    return 0;
}
<commit_msg>Happiness index map for `one` and `two` regions<commit_after>/**
 * \class main
 * @file main.cpp
 *
 * @par Licence
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 */

#include "FlagParser.hpp"
#include "DatabaseReader.hpp"
#include "GnuplotHandler.hpp"
#include "VectorOfCities.hpp"
#include "help.txt.hpp"

#include <locale.h>
#include <libintl.h>

#define _(STRING) gettext(STRING)

int main(int argc, char *argv[]) {
    // Part 1 - start - parse argv and get databaseFile
    FlagParser parser(argc, argv);
    parser.printFlags();
    auto flags = parser.getFlags();

    setlocale(LC_ALL, "");
    bindtextdomain("regionalizer", "/usr/share/locale");
    textdomain("regionalizer");

    if (!parser.hasKey("--help")) {
	std::cout << _("Help not found, so moving on...");
        std::cout << std::endl;
    } else {
	std::cout << _("Help found, so I am about to print help...");
	std::cout << std::endl;
        std::cout << ___help_txt;
	std::cout << _("Aborting....");
	std::cout << std::endl;
	return -1;
    }
    if (!flags["--list"].empty()) {
        std::cout << "Great! " << flags["--list"] << " is being processed";
	std::cout << std::endl;
    } else {
	std::cout << "No list specified!";
	std::cout << std::endl;
	std::cout << _("Aborting....");
	std::cout << std::endl;
	return -1;
    }

    std::string databaseFile{flags["--list"]};
    // Part 1 - end
    // Part 2 - start - create vector of Cities based on databaseFile
    auto vec = DatabaseReader::readCitiesFromFile(databaseFile);

    // Part 2 - end
    // Part 3 - start - calculate distance from one city to the farthest

    VectorOfCities::setDistanceToTheFarthestInTheWholeVector(vec);

    // Part 3 - end
    // Part 4 - start - by brute force check which city would be
    // the best capital. We have only one region.
    // This part is just for testing "happiness level" concept
    // "Happiness level" - value from 0 to 10.
    // 10 is the best, we have 10 when we are the capital, because the
    // distance to capital is equal to zero.
    // 0 is when the capital is the farthest city.
    // Formula: HL = 10 - ((distanceFrom(capital) / distanceToTheFarthest)*10)
    if (parser.hasKey("-N") && flags["-N"] == "1") {
        auto capitals = VectorOfCities::
                calculateHappinessLevelForOneRegionByBruteForce(vec);
	GnuplotHandler::plotHappinessIndex(vec, capitals);
    } else if (parser.hasKey("-N") && flags["-N"] == "2") {
	auto capitals = VectorOfCities::
                calculateHappinessLevelForTwoRegionsByBruteForce(vec);
	GnuplotHandler::plotHappinessIndex(vec, capitals);
    } else if (parser.hasKey("-N") && std::stoi(flags["-N"]) > 2) {
        auto capitals = VectorOfCities::regionalizeUsingRandom(vec,
                flags["-N"]);
	GnuplotHandler::plotHappinessIndex(vec, capitals);
    }
    // Part 4 - end
    // Part <last> - start - save to gnuplot.

    // Gnuploting temporary disabled
    /*
    if (!GnuplotHandler::isGnuplotInstalledOnHost()) {
        std::cout << "Gnuplot is not installed on host";
        std::cout << std::endl;
        std::cout << "Aborting...";
	return -1;
    }
    GnuplotHandler::saveDummyPlot();
    GnuplotHandler::plotPopulation(vec);
    GnuplotHandler::plotHappinessLevelWhenWeHaveOnlyOneRegion(vec);
    */
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

inline uint16x8_t cv_vpacks_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

inline uint8x16_t cv_vpacks_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

inline int16x8_t cv_vpacks_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

inline int8x16_t cv_vpacks_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

inline uint16x8_t cv_vpack_u32(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

inline uint8x16_t cv_vpack_u16(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

inline int16x8_t cv_vpack_s32(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

inline int8x16_t cv_vpack_s16(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

template <typename ST>
void fill(ST* ptr, RNG& r)
{
	unsigned int cLoop = 16/sizeof(ST);
	for(unsigned int i = 0;i < cLoop;i++)
		ptr[i] = (r.next() & 0x7f);
}

template <typename ST, typename DT>
void debugPack(const ST* src0, const ST* src1, DT* dst)
{
	for(uint32_t i = 0;i < (16/sizeof(ST));i++)
	{
		dst[i*2  ] = (DT)(src0[i]);
		dst[i*2+1] = (DT)(src1[i]);
	}
}

template <typename ST, typename DT>
void dumpArray(const ST* src0, const ST* src1, const DT* dst)
{
	using namespace std;
	unsigned int srcLoop = 16/sizeof(ST);
	unsigned int dstLoop = 16/sizeof(DT);
	cout << "src0:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
	cout << "src1:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src1[i];
	}
	cout << endl;
	cout << "dst :";
	for(unsigned int i = 0;i < dstLoop;i++)
	{
		cout << '\t' << dst[i];
	}
	cout << endl;
}

template <typename ST, typename DT>
void verifyArray(ST* src0, ST* src1, DT* dst, RNG& r)
{
	fill(src0, r);
	fill(src1, r);
	debugPack((const ST*)src0, (const ST*)src1, (DT*)dst);
	dumpArray(src0, src1, dst);
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4], src1[4];
	uint16_t dst[8];
	verifyArray(src0, src1, dst, r);

	return 0;
}
<commit_msg>make vector function templated<commit_after>#include <iostream>
#include <arm_neon.h>
#include "rng.hpp"

template <typename ST, typename DT>
inline DT cv_vpacks_(ST v0, ST v1)
{
	DT a;
	return a;
}

template <typename ST, typename DT>
inline DT cv_vpack_(ST v0, ST v1)
{
	DT a;
	return a;
}

template <>
inline uint16x8_t cv_vpacks_(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vqmovn_u32(v0), vqmovn_u32(v1));
}

template <>
inline uint8x16_t cv_vpacks_(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vqmovn_u16(v0), vqmovn_u16(v1));
}

template <>
inline int16x8_t cv_vpacks_(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vqmovn_s32(v0), vqmovn_s32(v1));
}

template <>
inline int8x16_t cv_vpacks_(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vqmovn_s16(v0), vqmovn_s16(v1));
}

template <>
inline uint16x8_t cv_vpack_(uint32x4_t v0, uint32x4_t v1)
{
	return vcombine_u16(vmovn_u32(v0), vmovn_u32(v1));
}

template <>
inline uint8x16_t cv_vpack_(uint16x8_t v0, uint16x8_t v1)
{
	return vcombine_u8(vmovn_u16(v0), vmovn_u16(v1));
}

template <>
inline int16x8_t cv_vpack_(int32x4_t v0, int32x4_t v1)
{
	return vcombine_s16(vmovn_s32(v0), vmovn_s32(v1));
}

template <>
inline int8x16_t cv_vpack_(int16x8_t v0, int16x8_t v1)
{
	return vcombine_s8(vmovn_s16(v0), vmovn_s16(v1));
}

template <typename ST>
void fill(ST* ptr, RNG& r)
{
	unsigned int cLoop = 16/sizeof(ST);
	for(unsigned int i = 0;i < cLoop;i++)
		ptr[i] = (r.next() & 0x7f);
}

template <typename ST, typename DT>
void debugPack(const ST* src0, const ST* src1, DT* dst)
{
	for(uint32_t i = 0;i < (16/sizeof(ST));i++)
	{
		dst[i*2  ] = (DT)(src0[i]);
		dst[i*2+1] = (DT)(src1[i]);
	}
}

template <typename ST, typename DT>
void dumpArray(const ST* src0, const ST* src1, const DT* dst)
{
	using namespace std;
	unsigned int srcLoop = 16/sizeof(ST);
	unsigned int dstLoop = 16/sizeof(DT);
	cout << "src0:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src0[i];
	}
	cout << endl;
	cout << "src1:";
	for(unsigned int i = 0;i < srcLoop;i++)
	{
		cout << '\t' << src1[i];
	}
	cout << endl;
	cout << "dst :";
	for(unsigned int i = 0;i < dstLoop;i++)
	{
		cout << '\t' << dst[i];
	}
	cout << endl;
}

template <typename ST, typename DT>
void verifyArray(ST* src0, ST* src1, DT* dst, RNG& r)
{
	fill(src0, r);
	fill(src1, r);
	debugPack((const ST*)src0, (const ST*)src1, (DT*)dst);
	dumpArray(src0, src1, dst);
}

int main(int argc, char** argv)
{
	RNG r(0x123);
	uint32_t src0[4], src1[4];
	uint16_t dst[8];
	verifyArray(src0, src1, dst, r);

	return 0;
}
<|endoftext|>


<commit_before>7cc18f94-4b02-11e5-be12-28cfe9171a43<commit_msg>Initial commit.13<commit_after>7cce51d1-4b02-11e5-b45d-28cfe9171a43<|endoftext|>


<commit_before>817e9699-2749-11e6-9d56-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>81915633-2749-11e6-b074-e0f84713e7b8<|endoftext|>


<commit_before>#define CROW_ENABLE_SSL

#include "ext/crow/crow.h"

#include "src/CmdLineOptions.h"
#include "src/MicroCore.h"
#include "src/page.h"

#include "ext/member_checker.h"

#include <fstream>

using boost::filesystem::path;

using namespace std;

// needed for log system of momero
namespace epee {
    unsigned int g_test_dbg_lock_sleep = 0;
}

int main(int ac, const char* av[]) {

    // get command line options
    xmreg::CmdLineOptions opts {ac, av};

    auto help_opt          = opts.get_option<bool>("help");
    auto testnet_opt       = opts.get_option<bool>("testnet");
    auto enable_pusher_opt = opts.get_option<bool>("enable-pusher");

    // if help was chosen, display help text and finish
    if (*help_opt)
    {
        return EXIT_SUCCESS;
    }

    bool testnet       {*testnet_opt};
    bool enable_pusher {*enable_pusher_opt};

    auto port_opt           = opts.get_option<string>("port");
    auto bc_path_opt        = opts.get_option<string>("bc-path");
    auto custom_db_path_opt = opts.get_option<string>("custom-db-path");
    auto deamon_url_opt     = opts.get_option<string>("deamon-url");
    auto ssl_crt_file_opt   = opts.get_option<string>("ssl-crt-file");
    auto ssl_key_file_opt   = opts.get_option<string>("ssl-key-file");

    //cast port number in string to uint16
    uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);

    bool use_ssl {false};

    string ssl_crt_file;
    string ssl_key_file;

    // check if ssl enabled and files exist

    if (ssl_crt_file_opt and ssl_key_file_opt)
    {
        if (!boost::filesystem::exists(boost::filesystem::path(*ssl_crt_file_opt)))
        {
            cerr << "ssl_crt_file path: " << *ssl_crt_file_opt
                 << "does not exist!" << endl;

            return EXIT_FAILURE;
        }

        if (!boost::filesystem::exists(boost::filesystem::path(*ssl_key_file_opt)))
        {
            cerr << "ssl_key_file path: " << *ssl_key_file_opt
                 << "does not exist!" << endl;

            return EXIT_FAILURE;
        }

        ssl_crt_file = *ssl_crt_file_opt;
        ssl_key_file = *ssl_key_file_opt;

        use_ssl = true;
    }

    // get blockchain path
    path blockchain_path;

    if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path, testnet))
    {
        cerr << "Error getting blockchain path." << endl;
        return EXIT_FAILURE;
    }

    cout << blockchain_path << endl;

     // enable basic monero log output
    xmreg::enable_monero_log();

    // create instance of our MicroCore
    // and make pointer to the Blockchain
    xmreg::MicroCore mcore;
    cryptonote::Blockchain* core_storage;

    // initialize mcore and core_storage
    if (!xmreg::init_blockchain(blockchain_path.string(),
                               mcore, core_storage))
    {
        cerr << "Error accessing blockchain." << endl;
        return EXIT_FAILURE;
    }

    // check if we have path to lmdb2 (i.e., custom db)
    // and if it exists

    string custom_db_path_str;

    if (custom_db_path_opt)
    {
        if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))
        {
            custom_db_path_str = *custom_db_path_opt;
        }
        else
        {
            cerr << "Custom db path: " << *custom_db_path_opt
                 << "does not exist" << endl;

            return EXIT_FAILURE;
        }
    }
    else
    {
        // if not given assume it is located in ~./bitmonero/lmdb2 folder
        // or ~./bitmonero/testnet/lmdb2 for testnet network
        custom_db_path_str = blockchain_path.parent_path().string()
                             + string("/lmdb2");
    }

    custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);

    string deamon_url {*deamon_url_opt};

    if (testnet)
        deamon_url = "http:://127.0.0.1:28081";

    // create instance of page class which
    // contains logic for the website
    xmreg::page xmrblocks(&mcore,
                          core_storage,
                          deamon_url,
                          custom_db_path_str,
                          testnet,
                          enable_pusher);

    // crow instance
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")
    ([&](const crow::request& req) {
        return crow::response(xmrblocks.index2());
    });

    CROW_ROUTE(app, "/page/<uint>")
    ([&](size_t page_no) {
        return xmrblocks.index2(page_no);
    });

    CROW_ROUTE(app, "/block/<uint>")
    ([&](const crow::request& req, size_t block_height) {
        return crow::response(xmrblocks.show_block(block_height));
    });

    CROW_ROUTE(app, "/block/<string>")
    ([&](const crow::request& req, string block_hash) {
        return crow::response(xmrblocks.show_block(block_hash));
    });

    CROW_ROUTE(app, "/tx/<string>")
    ([&](const crow::request& req, string tx_hash) {
        return crow::response(xmrblocks.show_tx(tx_hash));
    });

    CROW_ROUTE(app, "/tx/<string>/<uint>")
    ([&](string tx_hash, uint with_ring_signatures) {
        return xmrblocks.show_tx(tx_hash, with_ring_signatures);
    });

    CROW_ROUTE(app, "/myoutputs").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("tx_hash"));
        string xmr_address = string(req.url_params.get("xmr_address"));
        string viewkey     = string(req.url_params.get("viewkey"));

        return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);
    });

    CROW_ROUTE(app, "/prove").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("txhash"));
        string tx_prv_key  = string(req.url_params.get("txprvkey"));
        string xmr_address = string(req.url_params.get("xmraddress"));

        return xmrblocks.show_prove(tx_hash, xmr_address, tx_prv_key);
    });

    CROW_ROUTE(app, "/rawtx")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawtx();
    });

    CROW_ROUTE(app, "/checkandpush").methods("POST"_method)
    ([&](const crow::request& req) {

        map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

        if (post_body.count("rawtxdata") == 0 || post_body.count("action") == 0)
        {
            return string("Raw tx data or action not provided");
        }

        string raw_tx_data = post_body["rawtxdata"];
        string action      = post_body["action"];

        if (action == "check")
            return xmrblocks.show_checkrawtx(raw_tx_data, action);
        else if (action == "push")
            return xmrblocks.show_pushrawtx(raw_tx_data, action);

    });

    CROW_ROUTE(app, "/rawkeyimgs")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawkeyimgs();
    });

    CROW_ROUTE(app, "/checkrawkeyimgs").methods("POST"_method)
    ([&](const crow::request& req) {

        map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

        if (post_body.count("rawkeyimgsdata") == 0)
        {
            return string("Raw key images data not given");
        }

        if (post_body.count("viewkey") == 0)
        {
            return string("Viewkey not provided. Cant decrypt key image file without it");
        }

        string raw_data = post_body["rawkeyimgsdata"];
        string viewkey  = post_body["viewkey"];

        return xmrblocks.show_checkrawkeyimgs(raw_data, viewkey);
    });

    CROW_ROUTE(app, "/rawoutputkeys")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawoutputkeys();
    });

    CROW_ROUTE(app, "/checkrawoutputkeys").methods("POST"_method)
            ([&](const crow::request& req) {

                map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

                if (post_body.count("rawoutputkeysdata") == 0)
                {
                    return string("Raw output keys data not given");
                }

                if (post_body.count("viewkey") == 0)
                {
                    return string("Viewkey not provided. Cant decrypt key image file without it");
                }

                string raw_data = post_body["rawoutputkeysdata"];
                string viewkey  = post_body["viewkey"];

                return xmrblocks.show_checkcheckrawoutput(raw_data, viewkey);
            });

    CROW_ROUTE(app, "/search").methods("GET"_method)
    ([&](const crow::request& req) {
        return xmrblocks.search(string(req.url_params.get("value")));
    });

    CROW_ROUTE(app, "/robots.txt")
    ([&]() {
        string text = "User-agent: *\n"
                      "Disallow: ";
        return text;
    });

    CROW_ROUTE(app, "/autorefresh")
    ([&]() {
        uint64_t page_no {0};
        bool refresh_page {true};
        return xmrblocks.index2(page_no, refresh_page);
    });

    // run the crow http server

    if (use_ssl)
    {
        cout << "Staring in ssl mode" << endl;
        app.port(app_port).ssl_file(ssl_crt_file, ssl_key_file).multithreaded().run();
    }
    else
    {
        cout << "Staring in non-ssl mode" << endl;
        app.port(app_port).multithreaded().run();
    }

    return EXIT_SUCCESS;
}
<commit_msg>avoid overwriting provided testnet daemon url<commit_after>#define CROW_ENABLE_SSL

#include "ext/crow/crow.h"

#include "src/CmdLineOptions.h"
#include "src/MicroCore.h"
#include "src/page.h"

#include "ext/member_checker.h"

#include <fstream>

using boost::filesystem::path;

using namespace std;

// needed for log system of momero
namespace epee {
    unsigned int g_test_dbg_lock_sleep = 0;
}

int main(int ac, const char* av[]) {

    // get command line options
    xmreg::CmdLineOptions opts {ac, av};

    auto help_opt          = opts.get_option<bool>("help");
    auto testnet_opt       = opts.get_option<bool>("testnet");
    auto enable_pusher_opt = opts.get_option<bool>("enable-pusher");

    // if help was chosen, display help text and finish
    if (*help_opt)
    {
        return EXIT_SUCCESS;
    }

    bool testnet       {*testnet_opt};
    bool enable_pusher {*enable_pusher_opt};

    auto port_opt           = opts.get_option<string>("port");
    auto bc_path_opt        = opts.get_option<string>("bc-path");
    auto custom_db_path_opt = opts.get_option<string>("custom-db-path");
    auto deamon_url_opt     = opts.get_option<string>("deamon-url");
    auto ssl_crt_file_opt   = opts.get_option<string>("ssl-crt-file");
    auto ssl_key_file_opt   = opts.get_option<string>("ssl-key-file");

    //cast port number in string to uint16
    uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);

    bool use_ssl {false};

    string ssl_crt_file;
    string ssl_key_file;

    // check if ssl enabled and files exist

    if (ssl_crt_file_opt and ssl_key_file_opt)
    {
        if (!boost::filesystem::exists(boost::filesystem::path(*ssl_crt_file_opt)))
        {
            cerr << "ssl_crt_file path: " << *ssl_crt_file_opt
                 << "does not exist!" << endl;

            return EXIT_FAILURE;
        }

        if (!boost::filesystem::exists(boost::filesystem::path(*ssl_key_file_opt)))
        {
            cerr << "ssl_key_file path: " << *ssl_key_file_opt
                 << "does not exist!" << endl;

            return EXIT_FAILURE;
        }

        ssl_crt_file = *ssl_crt_file_opt;
        ssl_key_file = *ssl_key_file_opt;

        use_ssl = true;
    }

    // get blockchain path
    path blockchain_path;

    if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path, testnet))
    {
        cerr << "Error getting blockchain path." << endl;
        return EXIT_FAILURE;
    }

    cout << blockchain_path << endl;

     // enable basic monero log output
    xmreg::enable_monero_log();

    // create instance of our MicroCore
    // and make pointer to the Blockchain
    xmreg::MicroCore mcore;
    cryptonote::Blockchain* core_storage;

    // initialize mcore and core_storage
    if (!xmreg::init_blockchain(blockchain_path.string(),
                               mcore, core_storage))
    {
        cerr << "Error accessing blockchain." << endl;
        return EXIT_FAILURE;
    }

    // check if we have path to lmdb2 (i.e., custom db)
    // and if it exists

    string custom_db_path_str;

    if (custom_db_path_opt)
    {
        if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))
        {
            custom_db_path_str = *custom_db_path_opt;
        }
        else
        {
            cerr << "Custom db path: " << *custom_db_path_opt
                 << "does not exist" << endl;

            return EXIT_FAILURE;
        }
    }
    else
    {
        // if not given assume it is located in ~./bitmonero/lmdb2 folder
        // or ~./bitmonero/testnet/lmdb2 for testnet network
        custom_db_path_str = blockchain_path.parent_path().string()
                             + string("/lmdb2");
    }

    custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);

    string deamon_url {*deamon_url_opt};

    if (testnet && deamon_url == "http:://127.0.0.1:18081")
        deamon_url = "http:://127.0.0.1:28081";

    // create instance of page class which
    // contains logic for the website
    xmreg::page xmrblocks(&mcore,
                          core_storage,
                          deamon_url,
                          custom_db_path_str,
                          testnet,
                          enable_pusher);

    // crow instance
    crow::SimpleApp app;

    CROW_ROUTE(app, "/")
    ([&](const crow::request& req) {
        return crow::response(xmrblocks.index2());
    });

    CROW_ROUTE(app, "/page/<uint>")
    ([&](size_t page_no) {
        return xmrblocks.index2(page_no);
    });

    CROW_ROUTE(app, "/block/<uint>")
    ([&](const crow::request& req, size_t block_height) {
        return crow::response(xmrblocks.show_block(block_height));
    });

    CROW_ROUTE(app, "/block/<string>")
    ([&](const crow::request& req, string block_hash) {
        return crow::response(xmrblocks.show_block(block_hash));
    });

    CROW_ROUTE(app, "/tx/<string>")
    ([&](const crow::request& req, string tx_hash) {
        return crow::response(xmrblocks.show_tx(tx_hash));
    });

    CROW_ROUTE(app, "/tx/<string>/<uint>")
    ([&](string tx_hash, uint with_ring_signatures) {
        return xmrblocks.show_tx(tx_hash, with_ring_signatures);
    });

    CROW_ROUTE(app, "/myoutputs").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("tx_hash"));
        string xmr_address = string(req.url_params.get("xmr_address"));
        string viewkey     = string(req.url_params.get("viewkey"));

        return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);
    });

    CROW_ROUTE(app, "/prove").methods("GET"_method)
    ([&](const crow::request& req) {

        string tx_hash     = string(req.url_params.get("txhash"));
        string tx_prv_key  = string(req.url_params.get("txprvkey"));
        string xmr_address = string(req.url_params.get("xmraddress"));

        return xmrblocks.show_prove(tx_hash, xmr_address, tx_prv_key);
    });

    CROW_ROUTE(app, "/rawtx")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawtx();
    });

    CROW_ROUTE(app, "/checkandpush").methods("POST"_method)
    ([&](const crow::request& req) {

        map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

        if (post_body.count("rawtxdata") == 0 || post_body.count("action") == 0)
        {
            return string("Raw tx data or action not provided");
        }

        string raw_tx_data = post_body["rawtxdata"];
        string action      = post_body["action"];

        if (action == "check")
            return xmrblocks.show_checkrawtx(raw_tx_data, action);
        else if (action == "push")
            return xmrblocks.show_pushrawtx(raw_tx_data, action);

    });

    CROW_ROUTE(app, "/rawkeyimgs")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawkeyimgs();
    });

    CROW_ROUTE(app, "/checkrawkeyimgs").methods("POST"_method)
    ([&](const crow::request& req) {

        map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

        if (post_body.count("rawkeyimgsdata") == 0)
        {
            return string("Raw key images data not given");
        }

        if (post_body.count("viewkey") == 0)
        {
            return string("Viewkey not provided. Cant decrypt key image file without it");
        }

        string raw_data = post_body["rawkeyimgsdata"];
        string viewkey  = post_body["viewkey"];

        return xmrblocks.show_checkrawkeyimgs(raw_data, viewkey);
    });

    CROW_ROUTE(app, "/rawoutputkeys")
    ([&](const crow::request& req) {
        return xmrblocks.show_rawoutputkeys();
    });

    CROW_ROUTE(app, "/checkrawoutputkeys").methods("POST"_method)
            ([&](const crow::request& req) {

                map<std::string, std::string> post_body = xmreg::parse_crow_post_data(req.body);

                if (post_body.count("rawoutputkeysdata") == 0)
                {
                    return string("Raw output keys data not given");
                }

                if (post_body.count("viewkey") == 0)
                {
                    return string("Viewkey not provided. Cant decrypt key image file without it");
                }

                string raw_data = post_body["rawoutputkeysdata"];
                string viewkey  = post_body["viewkey"];

                return xmrblocks.show_checkcheckrawoutput(raw_data, viewkey);
            });

    CROW_ROUTE(app, "/search").methods("GET"_method)
    ([&](const crow::request& req) {
        return xmrblocks.search(string(req.url_params.get("value")));
    });

    CROW_ROUTE(app, "/robots.txt")
    ([&]() {
        string text = "User-agent: *\n"
                      "Disallow: ";
        return text;
    });

    CROW_ROUTE(app, "/autorefresh")
    ([&]() {
        uint64_t page_no {0};
        bool refresh_page {true};
        return xmrblocks.index2(page_no, refresh_page);
    });

    // run the crow http server

    if (use_ssl)
    {
        cout << "Staring in ssl mode" << endl;
        app.port(app_port).ssl_file(ssl_crt_file, ssl_key_file).multithreaded().run();
    }
    else
    {
        cout << "Staring in non-ssl mode" << endl;
        app.port(app_port).multithreaded().run();
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
#include <iostream>

int main()
{
  std::cout << "Hello, world" << std::endl;
  return 0;
}
<commit_msg>basic main<commit_after>/*
 * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */
#include <iostream>

#include <boost/shared_ptr.hpp>

#include <alcommon/albroker.h>
#include <alcommon/albrokermanager.h>

#include "emotion.h"
#include "motion.h"
#include "tts.h"
#include "leds.h"

#ifdef FRAMEWORK_IS_REMOTE
# define ALCALL
#else
// when not remote, we're in a dll, so export the entry point
# ifdef _WIN32
#  define ALCALL __declspec(dllexport)
# else
#  define ALCALL
# endif
#endif

extern "C"
{
  ALCALL int _createModule(boost::shared_ptr<AL::ALBroker> broker)
  {
    // init broker with the main broker instance
    // from the parent executable
    AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
    AL::ALBrokerManager::getInstance()->addBroker(broker);
    // create module instances
    AL::ALModule::createModule<Emotion>(broker, "Emotion");
    AL::ALModule::createModule<EmotionalMotion>(broker, "EmotionalMotion");
    AL::ALModule::createModule<EmotionalTextToSpeech>(broker, "EmotionalTextToSpeech");
    AL::ALModule::createModule<EmotionalLeds>(broker, "EmotionalLeds");
    return 0;
  }

  ALCALL int _closeModule(  )
  {
    return 0;
  }
};

#ifdef FRAMEWORK_IS_REMOTE
int main()
{
  std::cout << "Hello, world" << std::endl;
  return 0;
}
#endif
<|endoftext|>


<commit_before>/** Copyright (C) 2017 European Spallation Source ERIC */

#include <benchmark/benchmark.h>
#include <multiblade/mbcaen/MBData.h>
#include <string>
#include <unistd.h>

/** @file
 *
 *  @brief Reading null data
 * File:
 */

MBData mbdata;
unsigned char databuffer[100000];

static void Setup(__attribute__((unused)) benchmark::State &state) {
  memset(databuffer, 0, sizeof(databuffer));
}
BENCHMARK(Setup);

static void ReceiveData(benchmark::State &state) {
  Setup(state);
  uint32_t items = 0;

  for (auto _ : state) {
    auto ret = mbdata.receive((char *)databuffer, state.range(0));
    items += ret;
  }
  state.SetComplexityN(state.range(0));
  state.SetBytesProcessed(state.iterations() * state.range(0));
  state.SetItemsProcessed(items);
};
BENCHMARK(ReceiveData)->RangeMultiplier(2)->Range(8, 80 << 10)->Complexity();

BENCHMARK_MAIN();
<commit_msg>fixing small things preventing compilation<commit_after>/** Copyright (C) 2017 European Spallation Source ERIC */

#include <benchmark/benchmark.h>
#include <multiblade/mbcaen/MBData.h>
#include <cstring>
#include <unistd.h>

/** @file
 *
 *  @brief Reading null data
 * File:
 */

MBData mbdata;
unsigned char databuffer[100000];

static void Setup(__attribute__((unused)) benchmark::State &state) {
  memset(databuffer, 0, sizeof(databuffer));
}
BENCHMARK(Setup);

static void ReceiveData(benchmark::State &state) {
  Setup(state);
  uint32_t items = 0;

  for (auto _ : state) {
    auto ret = mbdata.receive((char *)databuffer, state.range(0));
    items += ret;
  }
  state.SetComplexityN(state.range(0));
  state.SetBytesProcessed(state.iterations() * state.range(0));
  state.SetItemsProcessed(items);
}
BENCHMARK(ReceiveData)->RangeMultiplier(2)->Range(8, 80 << 10)->Complexity();

BENCHMARK_MAIN();
<|endoftext|>


<commit_before>#include <GL/glew.h>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>

#include <GLFW/glfw3.h>
#include <iostream>

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

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

  glfwDefaultWindowHints();

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glewInit() != GLEW_OK) {
    std::cerr << "Failed to initialize GLEW" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, setWindowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
  glMatrixMode(GL_PROJECTION);
  glLoadMatrixf(glm::value_ptr(m));

  GLuint VertexArrayID;
  glGenVertexArrays(1, &VertexArrayID);
  glBindVertexArray(VertexArrayID);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* */
    glColor4f(1, 0, 0, 1);
    glBegin(GL_TRIANGLES);
    glVertex3f( 0,  0.5, -5);
    glVertex3f( 0.5, -0.5, -5);
    glVertex3f(-0.5, -0.5, -5);
    glEnd();
    /* */

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}<commit_msg>Minor changes<commit_after>#define GLEW_STATIC // required for Windows, see http://stackoverflow.com/a/18477835
#include <GL/glew.h>

#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>

#include <GLFW/glfw3.h>
#include <iostream>

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

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

  glfwDefaultWindowHints();

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glewInit() != GLEW_OK) {
    std::cerr << "Failed to initialize GLEW" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, setWindowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
  glMatrixMode(GL_PROJECTION);
  glLoadMatrixf(glm::value_ptr(m));

  GLuint VertexArrayID;
  glGenVertexArrays(1, &VertexArrayID);
  glBindVertexArray(VertexArrayID);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* */
    glColor4f(1, 0, 0, 1);
    glBegin(GL_TRIANGLES);
    glVertex3f( 0,  0.5, -5);
    glVertex3f( 0.5, -0.5, -5);
    glVertex3f(-0.5, -0.5, -5);
    glEnd();
    /* */

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}<|endoftext|>


<commit_before>// proxy_util_w23.cpp : Main methods of the DLL.

#include "stdafx.h"
#include "proxy_util_w32.h"

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    winHttpDetectAutoProxyConfigUrl
 * Signature: (I)Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpDetectAutoProxyConfigUrl
(JNIEnv *env, jobject source, jint mode) {

	LPWSTR ppwszAutoConfigUrl = NULL;
	BOOL result = WinHttpDetectAutoProxyConfigUrl( mode, &ppwszAutoConfigUrl );
	if (ppwszAutoConfigUrl == NULL) {
		return NULL;
	}

	jstring retValue = env->NewString((jchar*)ppwszAutoConfigUrl,
									wcslen(ppwszAutoConfigUrl));

	GlobalFree( ppwszAutoConfigUrl );

	return retValue;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    winHttpGetDefaultProxyConfiguration
 * Signature: ()Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpGetDefaultProxyConfiguration
(JNIEnv *env, jobject source) {

	WINHTTP_PROXY_INFO proxyInfo;

    // Retrieve the default proxy configuration.
    BOOL result = WinHttpGetDefaultProxyConfiguration( &proxyInfo );
	if (result == FALSE) {
		// TODO what to do in case of error.
		DWORD errorCode = GetLastError();
	}

	int proxyTypeLen = 0;
	int proxyLen = 0;
	int proxyBypassLen = 0;

	LPWSTR proxyType = NULL;
	if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) {
		proxyType = L"PROXY ";
		proxyTypeLen = wcslen(proxyType);
	} else
	if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY) {
		proxyType = L"DIRECT ";
		proxyTypeLen = wcslen(proxyType);
	}
    if (proxyInfo.lpszProxy != NULL) {
		proxyLen += wcslen(proxyInfo.lpszProxy);
	}
    if (proxyInfo.lpszProxyBypass != NULL) {
		proxyBypassLen += wcslen(proxyInfo.lpszProxyBypass);
	}

	jstring retVal = proxyInfo.lpszProxy == NULL? NULL
		: env->NewString((jchar*)proxyInfo.lpszProxy, wcslen(proxyInfo.lpszProxy));

	if (proxyInfo.lpszProxy != NULL) {
        GlobalFree( proxyInfo.lpszProxy );
    }
    if (proxyInfo.lpszProxyBypass != NULL) {
        GlobalFree( proxyInfo.lpszProxyBypass );
    }
	return retVal;

	//int retValueLen = proxyTypeLen+proxyLen+1+proxyBypassLen+1;
	//int insertPos = 0;
	//LPWSTR combined = new WCHAR[retValueLen];
	//combined[retValueLen] = 0;

	//wcsncat_s(combined, retValueLen, proxyType, proxyTypeLen);
	//insertPos += proxyTypeLen;
	//retValueLen -= proxyTypeLen;

	//wcsncat_s(combined, retValueLen, proxyInfo.lpszProxy, proxyLen);
	//insertPos += proxyLen;
	//retValueLen -= proxyLen;

	//wcsncat_s(combined, retValueLen, TEXT("|"), 1);
	//insertPos += proxyLen;
	//retValueLen -= proxyLen;

	//wcsncat_s(combined, retValueLen, proxyInfo.lpszProxyBypass, proxyBypassLen);
	//insertPos += proxyBypassLen;
	//retValueLen -= proxyBypassLen;

 //   if (proxyInfo.lpszProxy != NULL) {
 //       GlobalFree( proxyInfo.lpszProxy );
 //   }
 //   if (proxyInfo.lpszProxyBypass != NULL) {
 //       GlobalFree( proxyInfo.lpszProxyBypass );
 //   }

	//jstring retVal = env->NewString((jchar*)combined, wcslen(combined));

	//return retVal;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    WinHttpGetIEProxyConfigForCurrentUser
 * Signature: ()Lcom/btr/proxy/search/desktop/win/WinIESettings;
 ****************************************************************************/

JNIEXPORT jobject JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpGetIEProxyConfigForCurrentUser
(JNIEnv *env, jobject source) {

	WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyInfo;

    // Retrieve the IE proxy configuration.
    BOOL result = WinHttpGetIEProxyConfigForCurrentUser( &ieProxyInfo );
	if (result == FALSE) {
		DWORD errorCode = GetLastError();
		return NULL;
	}

	jboolean autoDetect = ieProxyInfo.fAutoDetect;
	jstring autoConfigUrl = NULL;
	jstring proxy = NULL;
	jstring proxyBypass = NULL;

	if (ieProxyInfo.lpszAutoConfigUrl != NULL) {
		autoConfigUrl = env->NewString((jchar*)ieProxyInfo.lpszAutoConfigUrl, wcslen(ieProxyInfo.lpszAutoConfigUrl));
        GlobalFree( ieProxyInfo.lpszAutoConfigUrl );
    }
    if (ieProxyInfo.lpszProxy != NULL) {
		proxy = env->NewString((jchar*)ieProxyInfo.lpszProxy, wcslen(ieProxyInfo.lpszProxy));
		GlobalFree( ieProxyInfo.lpszProxy );
    }
    if (ieProxyInfo.lpszProxyBypass != NULL) {
		proxyBypass = env->NewString((jchar*)ieProxyInfo.lpszProxyBypass, wcslen(ieProxyInfo.lpszProxyBypass));
		GlobalFree( ieProxyInfo.lpszProxyBypass );
    }

	// Build result container object.
	jclass retValueClass = env->FindClass("com/btr/proxy/search/desktop/win/WinIESettings");
	if ( retValueClass == NULL ) {
		return NULL;
	}

	jmethodID jmid = env->GetMethodID(retValueClass, "<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
	if (jmid == NULL) {
		return NULL;
	}

	// WinIESettings(boolean autoDetect, String autoConfigUrl, String proxy, String proxyBypass)
	jobject retValue = env->NewObject(retValueClass, jmid, autoDetect, autoConfigUrl, proxy, proxyBypass);

	return retValue;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    readUserHomedir
 * Signature: ()Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_readUserHomedir
(JNIEnv *env, jobject source) {
	HKEY key;
	int result = RegOpenKeyEx(HKEY_CURRENT_USER,
#ifdef _WIN64
				"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
#else
				L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
#endif
				0, KEY_QUERY_VALUE, &key);
	if (0 != ERROR_SUCCESS) {
		LPWSTR errorMsg = L"ERROR: Key open failed";
		return env->NewString((jchar*)errorMsg, wcslen(errorMsg));
	}

	BYTE pvData[1000];
	DWORD dataSize = 1000;

#ifdef _WIN64
	result = RegQueryValueEx(key, "AppData", NULL, NULL, pvData, &dataSize);
#else
	result = RegQueryValueEx(key, L"AppData", NULL, NULL, pvData, &dataSize);
#endif
	RegCloseKey(key);
	if (result != ERROR_SUCCESS) {
		LPWSTR errorMsg = L"ERROR: Read value failed";
		return env->NewString((jchar*)errorMsg, wcslen(errorMsg));
	}

	jstring retValue = env->NewString((jchar*)pvData, (dataSize-1)/2);
	return retValue;
}

<commit_msg>Reverted class rename that affected dll.<commit_after>// proxy_util_w23.cpp : Main methods of the DLL.

#include "stdafx.h"
#include "proxy_util_w32.h"

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    winHttpDetectAutoProxyConfigUrl
 * Signature: (I)Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpDetectAutoProxyConfigUrl
(JNIEnv *env, jobject source, jint mode) {

	LPWSTR ppwszAutoConfigUrl = NULL;
	BOOL result = WinHttpDetectAutoProxyConfigUrl( mode, &ppwszAutoConfigUrl );
	if (ppwszAutoConfigUrl == NULL) {
		return NULL;
	}

	jstring retValue = env->NewString((jchar*)ppwszAutoConfigUrl,
									wcslen(ppwszAutoConfigUrl));

	GlobalFree( ppwszAutoConfigUrl );

	return retValue;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    winHttpGetDefaultProxyConfiguration
 * Signature: ()Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpGetDefaultProxyConfiguration
(JNIEnv *env, jobject source) {

	WINHTTP_PROXY_INFO proxyInfo;

    // Retrieve the default proxy configuration.
    BOOL result = WinHttpGetDefaultProxyConfiguration( &proxyInfo );
	if (result == FALSE) {
		// TODO what to do in case of error.
		DWORD errorCode = GetLastError();
	}

	int proxyTypeLen = 0;
	int proxyLen = 0;
	int proxyBypassLen = 0;

	LPWSTR proxyType = NULL;
	if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) {
		proxyType = L"PROXY ";
		proxyTypeLen = wcslen(proxyType);
	} else
	if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY) {
		proxyType = L"DIRECT ";
		proxyTypeLen = wcslen(proxyType);
	}
    if (proxyInfo.lpszProxy != NULL) {
		proxyLen += wcslen(proxyInfo.lpszProxy);
	}
    if (proxyInfo.lpszProxyBypass != NULL) {
		proxyBypassLen += wcslen(proxyInfo.lpszProxyBypass);
	}

	jstring retVal = proxyInfo.lpszProxy == NULL? NULL
		: env->NewString((jchar*)proxyInfo.lpszProxy, wcslen(proxyInfo.lpszProxy));

	if (proxyInfo.lpszProxy != NULL) {
        GlobalFree( proxyInfo.lpszProxy );
    }
    if (proxyInfo.lpszProxyBypass != NULL) {
        GlobalFree( proxyInfo.lpszProxyBypass );
    }
	return retVal;

	//int retValueLen = proxyTypeLen+proxyLen+1+proxyBypassLen+1;
	//int insertPos = 0;
	//LPWSTR combined = new WCHAR[retValueLen];
	//combined[retValueLen] = 0;

	//wcsncat_s(combined, retValueLen, proxyType, proxyTypeLen);
	//insertPos += proxyTypeLen;
	//retValueLen -= proxyTypeLen;

	//wcsncat_s(combined, retValueLen, proxyInfo.lpszProxy, proxyLen);
	//insertPos += proxyLen;
	//retValueLen -= proxyLen;

	//wcsncat_s(combined, retValueLen, TEXT("|"), 1);
	//insertPos += proxyLen;
	//retValueLen -= proxyLen;

	//wcsncat_s(combined, retValueLen, proxyInfo.lpszProxyBypass, proxyBypassLen);
	//insertPos += proxyBypassLen;
	//retValueLen -= proxyBypassLen;

 //   if (proxyInfo.lpszProxy != NULL) {
 //       GlobalFree( proxyInfo.lpszProxy );
 //   }
 //   if (proxyInfo.lpszProxyBypass != NULL) {
 //       GlobalFree( proxyInfo.lpszProxyBypass );
 //   }

	//jstring retVal = env->NewString((jchar*)combined, wcslen(combined));

	//return retVal;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    WinHttpGetIEProxyConfigForCurrentUser
 * Signature: ()Lcom/btr/proxy/search/desktop/win/Win32IESettings;
 ****************************************************************************/

JNIEXPORT jobject JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_winHttpGetIEProxyConfigForCurrentUser
(JNIEnv *env, jobject source) {

	WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyInfo;

    // Retrieve the IE proxy configuration.
    BOOL result = WinHttpGetIEProxyConfigForCurrentUser( &ieProxyInfo );
	if (result == FALSE) {
		DWORD errorCode = GetLastError();
		return NULL;
	}

	jboolean autoDetect = ieProxyInfo.fAutoDetect;
	jstring autoConfigUrl = NULL;
	jstring proxy = NULL;
	jstring proxyBypass = NULL;

	if (ieProxyInfo.lpszAutoConfigUrl != NULL) {
		autoConfigUrl = env->NewString((jchar*)ieProxyInfo.lpszAutoConfigUrl, wcslen(ieProxyInfo.lpszAutoConfigUrl));
        GlobalFree( ieProxyInfo.lpszAutoConfigUrl );
    }
    if (ieProxyInfo.lpszProxy != NULL) {
		proxy = env->NewString((jchar*)ieProxyInfo.lpszProxy, wcslen(ieProxyInfo.lpszProxy));
		GlobalFree( ieProxyInfo.lpszProxy );
    }
    if (ieProxyInfo.lpszProxyBypass != NULL) {
		proxyBypass = env->NewString((jchar*)ieProxyInfo.lpszProxyBypass, wcslen(ieProxyInfo.lpszProxyBypass));
		GlobalFree( ieProxyInfo.lpszProxyBypass );
    }

	// Build result container object.
	jclass retValueClass = env->FindClass("com/btr/proxy/search/desktop/win/Win32IESettings");
	if ( retValueClass == NULL ) {
		return NULL;
	}

	jmethodID jmid = env->GetMethodID(retValueClass, "<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
	if (jmid == NULL) {
		return NULL;
	}

	// Win32IESettings(boolean autoDetect, String autoConfigUrl, String proxy, String proxyBypass)
	jobject retValue = env->NewObject(retValueClass, jmid, autoDetect, autoConfigUrl, proxy, proxyBypass);

	return retValue;
}

/*****************************************************************************
 * Class:     com_btr_proxy_search_desktop_win_Win32ProxyUtils
 * Method:    readUserHomedir
 * Signature: ()Ljava/lang/String;
 ****************************************************************************/

JNIEXPORT jstring JNICALL Java_com_btr_proxy_search_desktop_win_Win32ProxyUtils_readUserHomedir
(JNIEnv *env, jobject source) {
	HKEY key;
	int result = RegOpenKeyEx(HKEY_CURRENT_USER,
#ifdef _WIN64
				"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
#else
				L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
#endif
				0, KEY_QUERY_VALUE, &key);
	if (0 != ERROR_SUCCESS) {
		LPWSTR errorMsg = L"ERROR: Key open failed";
		return env->NewString((jchar*)errorMsg, wcslen(errorMsg));
	}

	BYTE pvData[1000];
	DWORD dataSize = 1000;

#ifdef _WIN64
	result = RegQueryValueEx(key, "AppData", NULL, NULL, pvData, &dataSize);
#else
	result = RegQueryValueEx(key, L"AppData", NULL, NULL, pvData, &dataSize);
#endif
	RegCloseKey(key);
	if (result != ERROR_SUCCESS) {
		LPWSTR errorMsg = L"ERROR: Read value failed";
		return env->NewString((jchar*)errorMsg, wcslen(errorMsg));
	}

	jstring retValue = env->NewString((jchar*)pvData, (dataSize-1)/2);
	return retValue;
}

<|endoftext|>


<commit_before>af9caa17-4b02-11e5-b090-28cfe9171a43<commit_msg>my cat is cute<commit_after>afac7b80-4b02-11e5-a7e6-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"
#include "extraction.h"
#include "bond_angle.h"
//#include "dihedral_angle.h"

using namespace std;
/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond order, central angles, and torsional
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the biomolecule.
 */

int main(int argc, char* argv[])
{
    ofstream logfile;
    fstream bond_angle;

    //Check that inputfile was directed into the command line
    if (argc < 2)
    {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open())
    {
        cout << "Error: Unable to open the logfile.";
        return 3;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
    }

    //Extract the raw coordinates from the inputfile in the commandline
    Extraction molecule(argv[1]);

    //Clean the coords file
    molecule.trim_coords(2);

    //Open the file bond_angle.cpp and check that it opened
    bond_angle.open("bond_angle.cpp");
    if (!bond_angle.is_open()) {
        cout << "Error: Unable to open file bond_angle.";
        return 1;
    }
    //Close the file bond_angle.cpp
    bond_angle.close();
    cout << "Bond angle calculation complete.";
    return 0;

    //Open the file dihedral_angle.cpp and check that it opened
    //dihedral_angle.open("dihedral_angle.cpp");
    //if (!dihedral_angle.is_open()) {
        //cout << "Error: Unable to open file dihedral_angle.";
        //return 1;
    //}
    //Close the file dihedral_angle.cpp
    //dihedral_angle.close();
    //cout << "Dihedral angle calculation complete.";
    //return 0;
}
<commit_msg>dihedral_angle.h works now<commit_after>#include <iostream>
#include <string>
#include <fstream>

#include "main.h"
#include "extraction.h"
#include "bond_angle.h"
#include "dihedral_angle.h"

using namespace std;
/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond order, central angles, and torsional
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the biomolecule.
 */

int main(int argc, char* argv[])
{
    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;

    //Check that inputfile was directed into the command line
    if (argc < 2)
    {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open())
    {
        cout << "Error: Unable to open the logfile.";
        return 3;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool\n";
    }

    //Extract the raw coordinates from the inputfile in the commandline
    Extraction molecule(argv[1]);

    //Clean the coords file
    molecule.trim_coords(2);

    //Open the file bond_angle.cpp and check that it opened
    bond_angle.open("bond_angle.cpp");
    if (!bond_angle.is_open()) {
        cout << "Error: Unable to open file bond_angle.";
        return 1;
    }
    //Close the file bond_angle.cpp
    bond_angle.close();
    cout << "Bond angle calculation complete.";
    return 0;

    //Open the file dihedral_angle.cpp and check that it opened
    dihedral_angle.open("dihedral_angle.cpp");
    if (!dihedral_angle.is_open()) {
        cout << "Error: Unable to open file dihedral_angle.";
        return 1;
    }
    //Close the file dihedral_angle.cpp
    dihedral_angle.close();
    cout << "Dihedral angle calculation complete.";
    return 0;
}
<|endoftext|>


<commit_before>cf1a7db0-2747-11e6-b4e9-e0f84713e7b8<commit_msg>GOD DAMNED IT!<commit_after>cf386c94-2747-11e6-baa6-e0f84713e7b8<|endoftext|>