<commit_before><<<<<<< HEAD
#include <iostream>
#include "SDL.h"
#include "SDL_opengl.h"

bool gameRunning = true;

#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 720
//#define FULLSCREEN

    //window be rendered to
    SDL_Window* window = NULL;
    SDL_Surface* renderSurface = NULL;
    SDL_GLContext mainGLContext = NULL;
    SDL_Renderer* gRenderer = NULL;

    const float sh = SCREEN_HEIGHT;
    const float sw = SCREEN_WIDTH;

#include "gameHeader.h"

int main(int argc, char** argv){
    //runs startup procedures
    if(SDL_Init(SDL_INIT_VIDEO) < 0){
            std::cout << "SDL was not able to initialize! Error: " << SDL_GetError() << std::endl;
        }else{
            //Turn on double Buffering
            SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
            //create the window
            window = SDL_CreateWindow("Sword Swinger", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
                                      #ifdef FULLSCREEN
                                        | SDL_WINDOW_FULLSCREEN
                                      #endif // FULLSCREEN
                                      );
            if(window == NULL){
                std::cout << "The window failed to generate! Error: " << SDL_GetError() << std::endl;
            }else{
                //set opengl context
                mainGLContext = SDL_GL_CreateContext(window);
                if(mainGLContext == NULL){
                    std::cout << "The OpenGL context failed to initialize! Error: " << SDL_GetError() << std::endl;
                }else{
                    //get window surface
                    renderSurface = SDL_GetWindowSurface(window);
                    //set renderer
                    gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
                    if(gRenderer == NULL){
                        std::cout << "The variable 'gRenderer' was not able to initialize! Error: " << SDL_GetError() << std::endl;\
                    }
                    //background white
                    SDL_FillRect(renderSurface, NULL, SDL_MapRGB(renderSurface->format, 0xFF, 0xFF, 0xFF));

                    //update window
                    SDL_UpdateWindowSurface(window);

                    configRender();
                    gameLoop();
                }
            }

        }

    //closes the window and frees resources
    SDL_GL_DeleteContext(mainGLContext);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
=======
#include <stdio.h>
#include <SDL2/SDL.h>

int main(int argc,char **argv){
	puts("Hello, world!");
	return 0;
>>>>>>> origin/master
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include "SDL.h"
#include "SDL_opengl.h"

bool gameRunning = true;

#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 720
//#define FULLSCREEN

    //window be rendered to
    SDL_Window* window = NULL;
    SDL_Surface* renderSurface = NULL;
    SDL_GLContext mainGLContext = NULL;
    SDL_Renderer* gRenderer = NULL;

    const float sh = SCREEN_HEIGHT;
    const float sw = SCREEN_WIDTH;

int main(int argc, char** argv){
    //runs startup procedures
    if(SDL_Init(SDL_INIT_VIDEO) < 0){
            std::cout << "SDL was not able to initialize! Error: " << SDL_GetError() << std::endl;
        }else{
            //Turn on double Buffering
            SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
            //create the window
            window = SDL_CreateWindow("Sword Swinger", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
                                      #ifdef FULLSCREEN
                                        | SDL_WINDOW_FULLSCREEN
                                      #endif // FULLSCREEN
                                      );
            if(window == NULL){
                std::cout << "The window failed to generate! Error: " << SDL_GetError() << std::endl;
            }else{
                //set opengl context
                mainGLContext = SDL_GL_CreateContext(window);
                if(mainGLContext == NULL){
                    std::cout << "The OpenGL context failed to initialize! Error: " << SDL_GetError() << std::endl;
                }else{
                    //get window surface
                    renderSurface = SDL_GetWindowSurface(window);
                    //set renderer
                    gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
                    if(gRenderer == NULL){
                        std::cout << "The variable 'gRenderer' was not able to initialize! Error: " << SDL_GetError() << std::endl;\
                    }
                    //background white
                    SDL_FillRect(renderSurface, NULL, SDL_MapRGB(renderSurface->format, 0xFF, 0xFF, 0xFF));

                    //update window
                    SDL_UpdateWindowSurface(window);

                }
            }

        }

    //closes the window and frees resources
    SDL_GL_DeleteContext(mainGLContext);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before>#include "dsa/variant.h"
#include "gtest/gtest.h"

#include <msgpack.h>

using namespace dsa;

TEST(VariantTest, MsgpackEncoding) {
  Variant v(123);

  std::vector<uint8_t> *encoded_msg = v.to_msgpack();
  uint8_t encoded_buf[1024];
  std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);
  size_t encoded_buf_size = encoded_msg->size();

  Variant *v_dash = Variant::from_msgpack(reinterpret_cast<const uint8_t *>(encoded_buf), encoded_buf_size);

  EXPECT_TRUE(v_dash->is_int());
  EXPECT_EQ(123, v_dash->get_int());
}

<commit_msg>Add unittests<commit_after>#include "dsa/variant.h"
#include "gtest/gtest.h"

#include <msgpack.h>

using namespace dsa;
typedef std::unique_ptr<Variant> VariantPtr;

TEST(VariantTest, MsgpackEncoding) {

  {
    VariantPtr v = VariantPtr(Variant::create(1.23));

    std::vector<uint8_t> *encoded_msg = v->to_msgpack();
    uint8_t encoded_buf[1024];
    std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);
    size_t encoded_buf_size = encoded_msg->size();

    Variant *v_dash = Variant::from_msgpack(reinterpret_cast<const uint8_t *>(encoded_buf), encoded_buf_size);

    EXPECT_TRUE(v_dash->is_double());
    EXPECT_EQ(1.23, v_dash->get_double());
  }
  {
    VariantPtr v = VariantPtr(Variant::create(123));

    std::vector<uint8_t> *encoded_msg = v->to_msgpack();
    uint8_t encoded_buf[1024];
    std::copy(encoded_msg->begin(), encoded_msg->end(), encoded_buf);
    size_t encoded_buf_size = encoded_msg->size();

    Variant *v_dash = Variant::from_msgpack(reinterpret_cast<const uint8_t *>(encoded_buf), encoded_buf_size);

    EXPECT_TRUE(v_dash->is_int());
    EXPECT_EQ(123, v_dash->get_int());
  }
}

<|endoftext|>


<commit_before>#pragma once
//=========================================================================//
/*! @file
    @brief  Test TCP Protocol@n
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=========================================================================//
#include "udp.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Test TCP プロトコル・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class test_tcp {

		int		desc_;
		bool	onetime_;
		int		open_delay_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		test_tcp() : desc_(-1), onetime_(true), open_delay_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  サービス
		*/
		//-----------------------------------------------------------------//
		template <class ETH>
		void service(ETH& eth, bool server)
		{
			if(!onetime_) return;

			if(desc_ < 0) {
				if(open_delay_ > 0) {
					open_delay_--;
					return;
				}

				auto& ipv4 = eth.at_ipv4();
				auto& tcp  = ipv4.at_tcp();
				desc_ = tcp.open(ip_adrs(192,168,3,7), 3000, server);
				if(desc_ >= 0) {
					utils::format("Test TCP Open (%d): %s\n")
						% desc_ % (server ? "Server" : "Client");
				}
			} else {
				auto& ipv4 = eth.at_ipv4();
				auto& tcp  = ipv4.at_tcp();

				char tmp[256];
				int len = tcp.recv(desc_, tmp, sizeof(tmp));
				if(len > 0) {
					tmp[len] = 0;
					utils::format("Test TCP Recv (%d): '%s', %d\n") % desc_ % tmp % len;

					tcp.send(desc_, tmp, len);
					utils::format("Test TCP Send (%d): '%s', %d\n") % desc_ % tmp % len;

///					tcp.close(desc_);
///					utils::format("Test TCP Close (%d)\n") % desc_;
///					desc_ = -1;

					onetime_ = false;
					open_delay_ = 50;
				}
			}
		}
	};
}
<commit_msg>update test code management<commit_after>#pragma once
//=========================================================================//
/*! @file
    @brief  Test TCP Protocol@n
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=========================================================================//
#include "udp.hpp"

namespace net {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Test TCP プロトコル・クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class test_tcp {

		int		desc_;
		int		open_delay_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		test_tcp() : desc_(-1), open_delay_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  サービス
		*/
		//-----------------------------------------------------------------//
		template <class ETH>
		void service(ETH& eth, bool server)
		{
			if(desc_ < 0) {
				if(open_delay_ > 0) {
					open_delay_--;
					return;
				}

				auto& ipv4 = eth.at_ipv4();
				auto& tcp  = ipv4.at_tcp();
				desc_ = tcp.open(ip_adrs(192,168,3,7), 3000, server);
				if(desc_ >= 0) {
					utils::format("Test TCP Open (%d): %s\n")
						% desc_ % (server ? "Server" : "Client");
				}
			} else {
				auto& ipv4 = eth.at_ipv4();
				auto& tcp  = ipv4.at_tcp();

				char tmp[256];
				int len = tcp.recv(desc_, tmp, sizeof(tmp));
				if(len > 0) {
					tmp[len] = 0;
					utils::format("Test TCP Recv (%d): '%s', %d\n") % desc_ % tmp % len;

					tcp.send(desc_, tmp, len);
					utils::format("Test TCP Send (%d): '%s', %d\n") % desc_ % tmp % len;
				}
#if 0
				if(!tcp.connection(desc_)) {
					tcp.close(desc_);
					utils::format("Test TCP Close (%d)\n") % desc_;
					desc_ = -1;

					open_delay_ = 50;
				}
#endif
			}
		}
	};
}
<|endoftext|>


<commit_before>#include "DVBInterface.h"
#include "ChannelList.h"
#include "Util.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <thread>
#include <mutex>

extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <poll.h>
}

std::mutex newClientsMutex;
std::vector<int> newClients;

void httpThread(int fd) {
	pollfd p;
	p.fd = fd;
	p.events = POLLIN|POLLHUP;
	bool isGet = false, isHead = false, isBad = false, complete = false;
	while(!complete) {
		char buf[1024];
		if(poll(&p, 1, 10000)>0) {
			if(p.revents & POLLHUP) {
				close(fd);
				return;
			}
			ssize_t count = recv(fd, buf, 1024, 0);
			buf[count]=0;
			for(int i=0; i<count; i++) {
				if(buf[i]=='\r') // Get rid of DOS-isms
					memmove(buf+i, buf+i+1, (count--)-i);
			}
			Util::hexdump(reinterpret_cast<unsigned char*>(buf), count);

			char *tmp;
			complete = ((count>=2) && buf[count-2]=='\n' && buf[count-1]=='\n') || ((count == 1) && buf[0] == '\n');
			char *line = strtok_r(buf, "\n", &tmp);
			while(line) {
				Util::hexdump(reinterpret_cast<unsigned char*>(line), strlen(line));
				if(!strncasecmp(line, "HEAD ", 5))
					isHead = true;
				else if(!strncasecmp(line, "GET ", 4))
					isGet = true;
				else if(!isHead && !isGet) {
					isBad = true; complete = true;
					break;
				}
				line = strtok_r(nullptr, "\n", &tmp);
			}
		} else {
			close(fd);
			break;
		}
	}
	if(complete) {
		if(isGet || isHead) {
			send(fd, "HTTP/1.1 200 OK\r\n", 17, 0);
			send(fd, "Cache-Control: no-store, no-cache\r\n", 35, 0);
			send(fd, "Content-Type: video/mp2t\r\n", 26, 0);
			send(fd, "\r\n", 2, 0);
			if(isGet) {
				// Start sending the stream...
				std::lock_guard<std::mutex> guard(newClientsMutex);
				newClients.push_back(fd);
				std::cerr << "Client added" << std::endl;
			} else {
				close(fd);
			}
		} else {
			send(fd, "HTTP/1.1 400 Bad Request\r\n", 26, 0);
			send(fd, "Content-Type: text/plain\r\n", 26, 0);
			send(fd, "\r\n", 2, 0);
			send(fd, "Send HEAD or GET\r\n", 18, 0);
			close(fd);
		}
	}
}

int main(int argc, char **argv) {
	bool useIPv6 = argc>1 && !strcmp(argv[1], "-6");
	signal(SIGPIPE, SIG_IGN);

	DVBInterfaces cards = DVBInterfaces::all();
	if(!cards.size()) {
		std::cerr << "No DVB interfaces found" << std::endl;
		return 1;
	}

	ChannelList channels("channels.dvb");
	if(!channels.size()) {
		std::cerr << "No channel list - run \"scan >channels.dvb\"" << std::endl;
		return 2;
	}

	auto channel = channels.find("Das Erste HD");
	std::cerr << "Tuning..." << std::endl;
	cards[0].tune(channel.first);
	std::cerr << "Setting up channel..." << std::endl;
	cards[0].setup(*channel.second);
	std::cerr << "Accepting connections" << std::endl;

	int dvbFd = open("/dev/dvb/adapter0/dvr0", O_RDONLY|O_NONBLOCK);
	char dvbbuf[188];

	int socksize;
	int s;
	union {
		sockaddr addr;
		sockaddr_in addr_in;
		sockaddr_in6 addr_in6;
	};
	union {
		sockaddr dest;
		sockaddr_in dest_in;
		sockaddr_in6 dest_in6;
	};
	memset(&addr, 0, sizeof(addr_in));
	if(useIPv6) {
		addr_in6.sin6_family = AF_INET6;
		addr_in6.sin6_addr = in6addr_any;
		addr_in6.sin6_port = htons(8080);
		socksize = sizeof(addr_in6);
		s = socket(AF_INET6, SOCK_STREAM, 0);
	} else {
		addr_in.sin_family = AF_INET;
		addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
		addr_in.sin_port = htons(8080);
		socksize = sizeof(addr_in);
		s = socket(AF_INET, SOCK_STREAM, 0);
	}
	int b = bind(s, &addr, socksize);
	int l = listen(s, SOMAXCONN);

	pollfd p[128];
	p[0].fd = s;
	p[0].events = POLLIN;
	p[1].fd = dvbFd;
	p[1].events = POLLIN;
	int nfds = 2;

	while(true) {
		if(poll(p, nfds, 10000) > 0) {
			for(int i=2; i<nfds; i++) {
				if(p[i].revents & POLLHUP) {
					close(p[i].fd);
					memmove(&p[i], &p[i+1], sizeof(pollfd)*(nfds-i));
					nfds--; i--;
					std::cerr << "Client disconnected" << std::endl;
				}
			}
			if(p[0].revents & POLLIN) {
				socklen_t ss;
				int conn = accept(s, &dest, &ss);
				std::thread *http = new std::thread(&httpThread, conn);
			}
			if(p[1].revents & POLLIN) {
				size_t bytes = read(dvbFd, dvbbuf, 188);
				{
					std::lock_guard<std::mutex> guard(newClientsMutex);
					for(int fd: newClients) {
						p[nfds].fd = fd;
						p[nfds++].events = POLLOUT|POLLHUP;
					}
					newClients=std::vector<int>();
				}
				for(int i=2; i<nfds; i++)
					write(p[i].fd, dvbbuf, bytes);
			}
		}
	}
}
<commit_msg>Allow switching channels<commit_after>#include "DVBInterface.h"
#include "ChannelList.h"
#include "Util.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <thread>
#include <mutex>

extern "C" {
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <poll.h>
}

std::mutex newClientsMutex;
std::vector<int> newClients;
std::mutex newChannelMutex;
auto newChannel = std::make_pair<Transponder const *,Service const *>(nullptr, nullptr);

void httpThread(int fd) {
	pollfd p;
	p.fd = fd;
	p.events = POLLIN|POLLHUP;
	bool isGet = false, isHead = false, isBad = false, complete = false;
	std::string path;
	while(!complete) {
		char buf[1024];
		if(poll(&p, 1, 10000)>0) {
			if(p.revents & POLLHUP) {
				close(fd);
				return;
			}
			ssize_t count = recv(fd, buf, 1024, 0);
			buf[count]=0;
			for(int i=0; i<count; i++) {
				if(buf[i]=='\r') // Get rid of DOS-isms
					memmove(buf+i, buf+i+1, (count--)-i);
			}
			Util::hexdump(reinterpret_cast<unsigned char*>(buf), count);

			char *tmp;
			complete = ((count>=2) && buf[count-2]=='\n' && buf[count-1]=='\n') || ((count == 1) && buf[0] == '\n');
			char *line = strtok_r(buf, "\n", &tmp);
			while(line) {
				Util::hexdump(reinterpret_cast<unsigned char*>(line), strlen(line));
				bool curHead = !strncasecmp(line, "HEAD ", 5);
				bool curGet = !strncasecmp(line, "GET ", 4);
				if(curHead || curGet) {
					isHead = curHead;
					isGet = curGet;
					char *tmp1;
					char *s = strtok_r(line, " ", &tmp1);
					// Skip over "HEAD /" or "GET /" -- we've already seen that
					s = strtok_r(nullptr, " ", &tmp1);
					for(int i=1; i<strlen(s); i++) {
						if(i<strlen(s)-2 && s[i] == '%' &&
								((s[i+1] >= '0' && s[i+1] <= '9') || (s[i+1] >= 'a' && s[i+1] <= 'f') || (s[i+1] >= 'A' && s[i+1] <= 'F')) &&
								((s[i+2] >= '0' && s[i+2] <= '9') || (s[i+2] >= 'a' && s[i+2] <= 'f') || (s[i+2] >= 'A' && s[i+2] <= 'F'))) {
							char code[3] = {s[i+1], s[i+2], 0};
							path.push_back(strtoul(code, nullptr, 16));
							i+=2;
						} else if(s[i] == '+')
							path.push_back(' ');
						else
							path.push_back(s[i]);
					}
					s=strtok_r(nullptr, "", &tmp1);
					if(!s || !strncmp(s, "HTTP/0", 6)) { // HTTP before 1.0 -- no extras expected
						complete = true;
						break;
					}
				} else if(!isHead && !isGet) {
					isBad = true; complete = true;
					break;
				}
				line = strtok_r(nullptr, "\n", &tmp);
			}
		} else {
			close(fd);
			break;
		}
	}
	if(complete) {
		std::cerr << "Got request for " << path << std::endl;
		ChannelList channels("channels.dvb");
		auto channel = channels.find(path);
		if(!channel.first)
			std::cerr << "No such channel!" << std::endl;
		if(isGet || isHead) {
			send(fd, "HTTP/1.1 200 OK\r\n", 17, 0);
			send(fd, "Cache-Control: no-store, no-cache\r\n", 35, 0);
			send(fd, "Content-Type: video/mp2t\r\n", 26, 0);
			send(fd, "\r\n", 2, 0);
			if(isGet) {
				// FIXME don't allow switching the channel if we're already
				// streaming to someone else...
				{
					std::lock_guard<std::mutex> channelGuard(newChannelMutex);
					newChannel = channel;
				}
				// Start sending the stream...
				{
					std::lock_guard<std::mutex> guard(newClientsMutex);
					newClients.push_back(fd);
				}
				std::cerr << "Client added" << std::endl;
			} else {
				close(fd);
			}
		} else {
			send(fd, "HTTP/1.1 400 Bad Request\r\n", 26, 0);
			send(fd, "Content-Type: text/plain\r\n", 26, 0);
			send(fd, "\r\n", 2, 0);
			send(fd, "Send HEAD or GET\r\n", 18, 0);
			close(fd);
		}
	}
}

int main(int argc, char **argv) {
	bool useIPv6 = argc>1 && !strcmp(argv[1], "-6");
	signal(SIGPIPE, SIG_IGN);

	DVBInterfaces cards = DVBInterfaces::all();
	if(!cards.size()) {
		std::cerr << "No DVB interfaces found" << std::endl;
		return 1;
	}

	ChannelList channels("channels.dvb");
	if(!channels.size()) {
		std::cerr << "No channel list - run \"scan >channels.dvb\"" << std::endl;
		return 2;
	}

	auto channel = channels.find("Das Erste HD");
	std::cerr << "Tuning..." << std::endl;
	cards[0].tune(channel.first);
	std::cerr << "Setting up channel..." << std::endl;
	cards[0].setup(*channel.second);
	std::cerr << "Accepting connections" << std::endl;

	int dvbFd = open("/dev/dvb/adapter0/dvr0", O_RDONLY|O_NONBLOCK);
	char dvbbuf[188];

	int socksize;
	int s;
	union {
		sockaddr addr;
		sockaddr_in addr_in;
		sockaddr_in6 addr_in6;
	};
	union {
		sockaddr dest;
		sockaddr_in dest_in;
		sockaddr_in6 dest_in6;
	};
	memset(&addr, 0, sizeof(addr_in));
	if(useIPv6) {
		addr_in6.sin6_family = AF_INET6;
		addr_in6.sin6_addr = in6addr_any;
		addr_in6.sin6_port = htons(8080);
		socksize = sizeof(addr_in6);
		s = socket(AF_INET6, SOCK_STREAM, 0);
	} else {
		addr_in.sin_family = AF_INET;
		addr_in.sin_addr.s_addr = htonl(INADDR_ANY);
		addr_in.sin_port = htons(8080);
		socksize = sizeof(addr_in);
		s = socket(AF_INET, SOCK_STREAM, 0);
	}
	int b = bind(s, &addr, socksize);
	int l = listen(s, SOMAXCONN);

	pollfd p[128];
	p[0].fd = s;
	p[0].events = POLLIN;
	p[1].fd = dvbFd;
	p[1].events = POLLIN;
	int nfds = 2;

	while(true) {
		if(poll(p, nfds, 10000) > 0) {
			for(int i=2; i<nfds; i++) {
				if(p[i].revents & POLLHUP) {
					close(p[i].fd);
					memmove(&p[i], &p[i+1], sizeof(pollfd)*(nfds-i));
					nfds--; i--;
					std::cerr << "Client disconnected" << std::endl;
				}
			}
			if(p[0].revents & POLLIN) {
				socklen_t ss;
				int conn = accept(s, &dest, &ss);
				std::thread *http = new std::thread(&httpThread, conn);
			}
			{
				std::lock_guard<std::mutex> channelGuard(newChannelMutex);
				if(newChannel.first) {
					close(dvbFd);
					cards[0].tune(newChannel.first);
					cards[0].setup(*newChannel.second);
					newChannel=std::make_pair<Transponder const *, Service const *>(nullptr, nullptr);
					dvbFd = open("/dev/dvb/adapter0/dvr0", O_RDONLY|O_NONBLOCK);
					p[1].fd = dvbFd;
					continue;
				}
			}
			if(p[1].revents & POLLIN) {
				size_t bytes = read(dvbFd, dvbbuf, 188);
				if(bytes>0)
				{
					{
						std::lock_guard<std::mutex> guard(newClientsMutex);
						for(int fd: newClients) {
							p[nfds].fd = fd;
							p[nfds++].events = POLLOUT|POLLHUP;
						}
						newClients=std::vector<int>();
					}
					for(int i=2; i<nfds; i++)
						write(p[i].fd, dvbbuf, bytes);
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>#include "builders/buildings/roofs/FlatRoofBuilder.hpp"
#include "builders/buildings/facades/FlatFacadeBuilder.hpp"
#include "builders/misc/BarrierBuilder.hpp"
#include "clipper/clipper.hpp"
#include "entities/Way.hpp"
#include "utils/ElementUtils.hpp"
#include "utils/GeoUtils.hpp"

using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;

namespace {
    const double Scale = 1E7;
    const std::string HeightKey = "height";
    const std::string MinHeightKey = "min-height";
    const std::string OffsetKey = "offset";
    const std::string MeshNamePrefix = "barrier";
}

void BarrierBuilder::visitWay(const Way& way)
{
    Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);

    ClipperOffset offset;
    Path path;
    path.reserve(way.coordinates.size());

    for (const auto& coord : way.coordinates) {
        path.push_back(IntPoint(coord.longitude * Scale, coord.latitude * Scale));
    }

    offset.AddPath(path, JoinType::jtMiter, EndType::etOpenSquare);

    Paths solution;
    double offsetInMeters = style.getValue(OffsetKey, way.tags);
    double offsetInGrads = GeoUtils::getOffset(way.coordinates[0], offsetInMeters);
    offset.Execute(solution, offsetInGrads * Scale);

    // get polygon
    Polygon polygon(solution.size(), 0);
    std::vector<Vector2> vertices;
    vertices.reserve(solution[0].size());
    for (const auto& p : solution[0]) {
        vertices.push_back(Vector2(p.X / Scale, p.Y / Scale));
    }
    polygon.addContour(vertices);

    buildFromPolygon(way, style, polygon);
}

void BarrierBuilder::buildFromPolygon(const Way& way, const Style& style, Polygon& polygon)
{
    double height = style.getValue(HeightKey, way.tags);
    double minHeight = style.getValue(MinHeightKey, way.tags);
    double elevation = context_.eleProvider.getElevation(way.coordinates[0]) + minHeight;

    Mesh mesh(utymap::utils::getMeshName(MeshNamePrefix, way));
    MeshContext meshContext(mesh, style);

    // NOTE: Reuse building builders.

    FlatRoofBuilder roofBuilder(context_, meshContext);
    roofBuilder.setHeight(0);
    roofBuilder.setMinHeight(elevation + height);
    roofBuilder.build(polygon);

    FlatFacadeBuilder facadeBuilder(context_, meshContext);
    facadeBuilder.setHeight(height);
    facadeBuilder.setMinHeight(elevation);
    facadeBuilder.build(polygon);

    context_.meshCallback(mesh);
}<commit_msg>core: fix barrier mesh name<commit_after>#include "builders/buildings/roofs/FlatRoofBuilder.hpp"
#include "builders/buildings/facades/FlatFacadeBuilder.hpp"
#include "builders/misc/BarrierBuilder.hpp"
#include "clipper/clipper.hpp"
#include "entities/Way.hpp"
#include "utils/ElementUtils.hpp"
#include "utils/GeoUtils.hpp"

using namespace ClipperLib;
using namespace utymap::builders;
using namespace utymap::entities;
using namespace utymap::mapcss;
using namespace utymap::meshing;
using namespace utymap::utils;

namespace {
    const double Scale = 1E7;
    const std::string HeightKey = "height";
    const std::string MinHeightKey = "min-height";
    const std::string OffsetKey = "offset";
    const std::string MeshNamePrefix = "barrier:";
}

void BarrierBuilder::visitWay(const Way& way)
{
    Style style = context_.styleProvider.forElement(way, context_.quadKey.levelOfDetail);

    ClipperOffset offset;
    Path path;
    path.reserve(way.coordinates.size());

    for (const auto& coord : way.coordinates) {
        path.push_back(IntPoint(coord.longitude * Scale, coord.latitude * Scale));
    }

    offset.AddPath(path, JoinType::jtMiter, EndType::etOpenSquare);

    Paths solution;
    double offsetInMeters = style.getValue(OffsetKey, way.tags);
    double offsetInGrads = GeoUtils::getOffset(way.coordinates[0], offsetInMeters);
    offset.Execute(solution, offsetInGrads * Scale);

    // get polygon
    Polygon polygon(solution.size(), 0);
    std::vector<Vector2> vertices;
    vertices.reserve(solution[0].size());
    for (const auto& p : solution[0]) {
        vertices.push_back(Vector2(p.X / Scale, p.Y / Scale));
    }
    polygon.addContour(vertices);

    buildFromPolygon(way, style, polygon);
}

void BarrierBuilder::buildFromPolygon(const Way& way, const Style& style, Polygon& polygon)
{
    double height = style.getValue(HeightKey, way.tags);
    double minHeight = style.getValue(MinHeightKey, way.tags);
    double elevation = context_.eleProvider.getElevation(way.coordinates[0]) + minHeight;

    Mesh mesh(utymap::utils::getMeshName(MeshNamePrefix, way));
    MeshContext meshContext(mesh, style);

    // NOTE: Reuse building builders.

    FlatRoofBuilder roofBuilder(context_, meshContext);
    roofBuilder.setHeight(0);
    roofBuilder.setMinHeight(elevation + height);
    roofBuilder.build(polygon);

    FlatFacadeBuilder facadeBuilder(context_, meshContext);
    facadeBuilder.setHeight(height);
    facadeBuilder.setMinHeight(elevation);
    facadeBuilder.build(polygon);

    context_.meshCallback(mesh);
}<|endoftext|>


<commit_before>#include "Symbol.h"

#include <ee/StringHelper.h>
#include <ee/SpriteLoader.h>
#include <ee/SymbolFile.h>

#include <sprite2/SymType.h>
#include <gum/StringHelper.h>

namespace escale9
{

Symbol::Symbol()
{
	static int id = 0;
	m_name = ee::SymbolFile::Instance()->Tag(s2::SYM_SCALE9) + gum::StringHelper::ToString(id++);
}

void Symbol::LoadResources()
{
	ee::SpriteLoader spr_loader;
	gum::Scale9SymLoader loader(this, &spr_loader);
	loader.LoadJson(m_filepath);
}

}<commit_msg>[FIXED] scale9 cut edge<commit_after>#include "Symbol.h"

#include <ee/StringHelper.h>
#include <ee/SpriteLoader.h>
#include <ee/SymbolFile.h>
#include <ee/SettingData.h>
#include <ee/Config.h>

#include <sprite2/SymType.h>
#include <gum/StringHelper.h>

namespace escale9
{

Symbol::Symbol()
{
	static int id = 0;
	m_name = ee::SymbolFile::Instance()->Tag(s2::SYM_SCALE9) + gum::StringHelper::ToString(id++);
}

void Symbol::LoadResources()
{
	ee::SettingData& setting = ee::Config::Instance()->GetSettings();
	setting.open_image_edge_clip = false;

	ee::SpriteLoader spr_loader;
	gum::Scale9SymLoader loader(this, &spr_loader);
	loader.LoadJson(m_filepath);

	setting.open_image_edge_clip = true;
}

}<|endoftext|>


<commit_before>#include <fstream>
#include "type/type.h"
#include "ratimake/adjustit_connector.h"

#include <boost/program_options.hpp>

#include "type/message.h"
#include <utils/logger.h>
#include "utils/exception.h"
#include "config.h"
#include <boost/format.hpp>

namespace nt = navitia::type;
namespace po = boost::program_options;
namespace pt = boost::posix_time;

po::variables_map load_config(int argc, const char** argv){
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Affiche l'aide")
        ("date,d", po::value<std::string>(), "Date considéré comme maintenant")
        ("version,v", "Affiche la version")
        ("config-file", po::value<std::string>()->default_value(argv[0] + std::string(".ini")), "chemin vers le fichier de configuration")
        ("log4cplus-config-file", po::value<std::string>()->default_value("log4cplus.ini"), "chemin vers le fichier de configuration de log4cplus")
        ("connect-string", po::value<std::string>(), "parametres de connection à la base de données : DRIVER=FreeTDS;SERVER=;UID=;PWD=;DATABASE=;TDS_Version=8.0;Port=1433;ClientCharset=UTF-8")
        ("media-lang", po::value<std::string>()->default_value("FR"), "filename")
        ("media-media", po::value<std::string>()->default_value("INTERNET"), "filename")
        ("destination", po::value<std::string>(), "nom du fichier généré par ratimake");

    po::variables_map vm;

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

    if(vm.count("help")){
        std::cout << desc << "\n";
        return 0;
    }

    if(vm.count("config-file")){
        std::ifstream stream;
        stream.open(vm["config-file"].as<std::string>());
        if(!stream.is_open()){
            throw navitia::exception("loading config file failed");
        }else{
            po::store(po::parse_config_file(stream, desc), vm);
        }
    }
    po::notify(vm);

    return vm;
}

void generate(const po::variables_map& params, const pt::ptime& now){
    log4cplus::Logger logger = log4cplus::Logger::getInstance("log");
    navitia::ratimake::AtLoader loader;
    std::map<std::string, std::vector<navitia::type::Message>> messages;

    messages = loader.load(params, now);

    nt::MessageHolder holder;
    holder.messages = messages;
    holder.generation_date = pt::second_clock::universal_time();

    LOG4CPLUS_DEBUG(logger, boost::format("nb objects impactés: %s") % messages.size());
    holder.save(params["destination"].as<std::string>());
}

int main(int argc, char const* argv[]){
    init_logger();

    po::variables_map params;

    try{
        params = load_config(argc, argv);//@TODO: config
    }catch(const std::exception& e){
        std::cerr << e.what() << std::endl;
        return 1;
    }

    if(params.count("version")){
        std::cout << argv[0] << " V" << NAVITIA_VERSION << " " << NAVITIA_BUILD_TYPE << std::endl;
        return 0;
    }

    pt::ptime now;
    if(params.count("date")){
        now = pt::time_from_string(params["date"].as<std::string>());
    }else{
        now = pt::second_clock::local_time();
    }

    if(params.count("log4cplus-config-file")){
        init_logger(params["log4cplus-config-file"].as<std::string>());
    }
    log4cplus::Logger logger = log4cplus::Logger::getInstance("log");

    if(!params.count("connect-string") || params["connect-string"].as<std::string>().empty()){
        LOG4CPLUS_FATAL(logger, "chaine de connection à la base non défini");
        return 2;
    }

    try{
        generate(params, now);
    }catch(const std::exception& e){
        LOG4CPLUS_FATAL(logger, e.what());
        return 3;
    }

    return 0;
}
<commit_msg>help sur ratimake<commit_after>#include <fstream>
#include "type/type.h"
#include "ratimake/adjustit_connector.h"

#include <boost/program_options.hpp>

#include "type/message.h"
#include <utils/logger.h>
#include "utils/exception.h"
#include "config.h"
#include <boost/format.hpp>

namespace nt = navitia::type;
namespace po = boost::program_options;
namespace pt = boost::posix_time;

po::variables_map load_config(int argc, const char** argv){
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Affiche l'aide")
        ("date,d", po::value<std::string>(), "Date considéré comme maintenant")
        ("version,v", "Affiche la version")
        ("config-file", po::value<std::string>()->default_value(argv[0] + std::string(".ini")), "chemin vers le fichier de configuration")
        ("log4cplus-config-file", po::value<std::string>()->default_value("log4cplus.ini"), "chemin vers le fichier de configuration de log4cplus")
        ("connect-string", po::value<std::string>(), "parametres de connection à la base de données : DRIVER=FreeTDS;SERVER=;UID=;PWD=;DATABASE=;TDS_Version=8.0;Port=1433;ClientCharset=UTF-8")
        ("media-lang", po::value<std::string>()->default_value("FR"), "langue du media à charger")
        ("media-media", po::value<std::string>()->default_value("INTERNET"), "media à cahrger")
        ("destination", po::value<std::string>()->default_value("at.rt.lz4"), "nom du fichier généré par ratimake");

    po::variables_map vm;

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

    if(vm.count("help")){
        std::cout << desc << "\n";
        return 0;
    }

    if(vm.count("config-file")){
        std::ifstream stream;
        stream.open(vm["config-file"].as<std::string>());
        if(!stream.is_open()){
            throw navitia::exception("loading config file failed");
        }else{
            po::store(po::parse_config_file(stream, desc), vm);
        }
    }
    po::notify(vm);

    return vm;
}

void generate(const po::variables_map& params, const pt::ptime& now){
    log4cplus::Logger logger = log4cplus::Logger::getInstance("log");
    navitia::ratimake::AtLoader loader;
    std::map<std::string, std::vector<navitia::type::Message>> messages;

    messages = loader.load(params, now);

    nt::MessageHolder holder;
    holder.messages = messages;
    holder.generation_date = pt::second_clock::universal_time();

    LOG4CPLUS_DEBUG(logger, boost::format("nb objects impactés: %s") % messages.size());
    holder.save(params["destination"].as<std::string>());
}

int main(int argc, char const* argv[]){
    init_logger();

    po::variables_map params;

    try{
        params = load_config(argc, argv);//@TODO: config
    }catch(const std::exception& e){
        std::cerr << e.what() << std::endl;
        return 1;
    }

    if(params.count("version")){
        std::cout << argv[0] << " V" << NAVITIA_VERSION << " " << NAVITIA_BUILD_TYPE << std::endl;
        return 0;
    }

    pt::ptime now;
    if(params.count("date")){
        now = pt::time_from_string(params["date"].as<std::string>());
    }else{
        now = pt::second_clock::local_time();
    }

    if(params.count("log4cplus-config-file")){
        init_logger(params["log4cplus-config-file"].as<std::string>());
    }
    log4cplus::Logger logger = log4cplus::Logger::getInstance("log");

    if(!params.count("connect-string") || params["connect-string"].as<std::string>().empty()){
        LOG4CPLUS_FATAL(logger, "chaine de connection à la base non défini");
        return 2;
    }

    try{
        generate(params, now);
    }catch(const std::exception& e){
        LOG4CPLUS_FATAL(logger, e.what());
        return 3;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "Arduino.h"
#include "main.hpp"
#include "dht.h"
#include <ldr.hpp>
#include <MQSensor.hpp>

#ifdef RH_PLATFORM_NANO
# include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX
#endif

#define DHT11_PIN 5
#define LDR_PIN   4

// Sensores
dht DHTSensor;
ldr LDRSensor = ldr(LDR_PIN);

// Variáveis de Ambiente
uint16_t TemperatureHumidity[4];

void setup(){
    Serial.begin(115200);
    // Por enquanto
    Serial.println("DHT TEST PROGRAM ");
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHT_LIB_VERSION);
    Serial.println();
    Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");

    #ifdef RH_PLATFORM_MEGA
    Serial1.begin(115200);
    #endif
}

void loop(){
    dhtDebug(DHTSensor, DHT11_PIN);
    TemperatureHumidity[0] = DHTSensor.read11(DHT11_PIN);
    TemperatureHumidity[1] = DHTSensor.temperature;
    TemperatureHumidity[2] = DHTSensor.humidity;
    TemperatureHumidity[3] = LDRSensor.check();

    delay(2000);
} // loop
<commit_msg>Travis CI<commit_after>#include "Arduino.h"
#include "main.hpp"
#include "dht.h"
#include <ldr.hpp>
#include <../lib/MQ-Sensor/src/MQSensor.hpp>
#include <../lib/PrintManager/src/PrintManager.hpp>

#ifdef RH_PLATFORM_NANO
# include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX
#endif

#define DHT11_PIN 5
#define LDR_PIN   4

// Sensores
dht DHTSensor;
ldr LDRSensor          = ldr(LDR_PIN);
MQSensor Dummy         = MQSensor::NewMQSensor(1, MQ_SENSOR_DUMMY);
PrintManager BT_Serial = PrintManager(&Serial1); // Explicit ti pointer conversion

/* MONTAGEM
 * LDR/pot pino 4
 * DHT pino 5
 * VAZIO pino 1
 * BLUETOOTH Serial1
 *
 * //*/

// Variáveis de Ambiente
uint16_t TemperatureHumidity[10];

// Build ffffffffffffffffffffffffffffsadsedfeasrfwerawewtaerg
void setup(){
    Serial.begin(115200);
    // Por enquanto
    Serial.println("DHT TEST PROGRAM ");
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHT_LIB_VERSION);
    Serial.println();
    Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");

    // #ifdef RH_PLATFORM_MEGA
    Serial1.begin(115200);
    // #endif
}

void loop(){
    dhtDebug(DHTSensor, DHT11_PIN);
    TemperatureHumidity[0] = DHTSensor.read11(DHT11_PIN);
    TemperatureHumidity[1] = DHTSensor.temperature;
    TemperatureHumidity[2] = DHTSensor.humidity;
    TemperatureHumidity[3] = LDRSensor.check();

    BT_Serial.addValue("th", DHTSensor.temperature, DHTSensor.humidity);

    TemperatureHumidity[5] = Dummy.check();
    BT_Serial.addValue("M", TemperatureHumidity[5]);

    BT_Serial.sendData();

    delay(2000);
} // loop
<|endoftext|>


<commit_before>/* Copyright © 2001-2016, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "type/geographical_coord.h"
#include "utils/exception.h"
#include "isochrone.h"
#include "raptor.h"

#include <set>
#include <assert.h>
#include <vector>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometry.hpp>
#include <cmath>
#include <string>
#include <algorithm>
#include <boost/range/algorithm.hpp>

namespace navitia { namespace routing {

IsochroneException::~IsochroneException() noexcept = default;

type::GeographicalCoord project_in_direction(const type::GeographicalCoord& center,
                                             const double& direction,
                                             const double& radius){
    using navitia::type::GeographicalCoord;
    assert(radius > 0);
    double alpha = radius / GeographicalCoord::EARTH_RADIUS_IN_METERS;
    double direction_rad = fmod(direction, 360) * GeographicalCoord::N_DEG_TO_RAD;
    if (direction < 0) {
        direction_rad = 2 * M_PI - direction_rad;
    }
    double center_lat_deg = center.lat();
    double center_lon_deg = center.lon();
    type::GeographicalCoord center_right_interval = type::GeographicalCoord(center_lon_deg, center_lat_deg);
    double center_lat_rad = center_right_interval.lat() * GeographicalCoord::N_DEG_TO_RAD;
    double center_lon_rad = center_right_interval.lon() * GeographicalCoord::N_DEG_TO_RAD;
    double lat;
    double lon;
    // To avoid rounding error we use ° instread of rad.
    if (fabs(center_right_interval.lat()) == 90) {
        lon = direction_rad - M_PI;
        lat = M_PI_2 - alpha;
    } else {
        double delta_lat;
        double delta_lon;
        if (fmod(direction, 180) == 0) {
            delta_lat = pow(-1, fmod(direction / 180, 2)) * alpha;
            lat = center_lat_rad + delta_lat;
            lon = center_lon_rad;
        } else {
            // asin and acos give results in rad.
            double projection = asin(sin(alpha) * sin(direction_rad));
            delta_lat = acos(cos(alpha) / cos(projection));
            if (direction_rad > M_PI_2 && direction_rad < 3 * M_PI_2) {
                delta_lat = -1 * delta_lat;
            }
            lat = center_lat_rad + delta_lat;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
            if (lat == M_PI_2) {
                delta_lon = (direction == 90 ? 1 : - 1) * alpha;
#pragma GCC diagnostic pop
            } else {
                double b = (cos(alpha) - sin(lat) * sin(center_lat_rad)) / (cos(lat) * cos(center_lat_rad));
                if (fabs(b) > 1) {
                    b = (std::signbit(b) ? fmod(b - 1, 2) + 1 : fmod(b + 1, 2) - 1);
                }
                delta_lon = acos(b);
                if (direction_rad > M_PI) {
                    delta_lon = -1 * delta_lon;
                }
            }
            lon = center_lon_rad + delta_lon;
        }
    }
    // Lon and lat are in °
    double lon_deg = lon * N_RAD_TO_DEG;
    double lat_deg = lat * N_RAD_TO_DEG;
    return type::GeographicalCoord(lon_deg, lat_deg);
}

static type::GeographicalCoord build_sym (const type::GeographicalCoord& point,
                                          const type::GeographicalCoord& center,
                                          const unsigned int& i) {
    if (i % 180 == 0) {
        return type::GeographicalCoord(2*center.lon() - point.lon(), point.lat());
    } else {
        return type::GeographicalCoord(point.lon(), 2*center.lat() - point.lat());
    }
}

type::Polygon circle(const type::GeographicalCoord& center,
                     const double& radius) {
    type::Polygon points;
    auto& points_out = points.outer();
    points_out.reserve(180);
    for (unsigned int i = 0; i <= 90; i += 2) {
        points_out.push_back(project_in_direction(center, i, radius));
    }
    for (unsigned int j = 90; j <= 270; j += 90) {
        for (unsigned int k = 1; k <= 45; k++) {
            type::GeographicalCoord point;
            point = points_out[j / 2 - k];
            points_out.push_back(build_sym(point, center, j));
        }
    }
    points_out.push_back(project_in_direction(center, 0, radius));
    return points;
}

static type::MultiPolygon merge_poly(const type::MultiPolygon& multi_poly,
                                     const type::Polygon& poly) {
    type::MultiPolygon poly_union;
    try {
        boost::geometry::union_(poly, multi_poly, poly_union);
    } catch (const boost::geometry::exception& e) {
        //We don't merge the polygons
        log4cplus::Logger logger = log4cplus::Logger::getInstance("logger");
        LOG4CPLUS_WARN(logger, "impossible to merge polygon: " << e.what());
    }
    return poly_union;
}

struct InfoCircle {
    type::GeographicalCoord center;
    double distance;
    int duration_left;
    InfoCircle(const type::GeographicalCoord& center,
               const double& distance,
               const int& duration_left): center(center),
        distance(distance),
        duration_left(duration_left) {}
};

static bool within_info_circle(const InfoCircle& circle,
                              const std::vector<InfoCircle>& multi_poly,
                              const double speed) {
    auto begin = multi_poly.begin();
    const auto end = multi_poly.end();
    double circle_radius = circle.duration_left * speed;
    double coslat = cos(circle.center.lat() * type::GeographicalCoord::N_DEG_TO_RAD);
    return any_of(begin, end, [=](const InfoCircle& it) {
        double it_radius = it.duration_left * speed;
        return sqrt(circle.center.approx_sqr_distance(it.center, coslat)) + circle_radius < it_radius;
    });
}

static std::vector<InfoCircle> delete_useless_circle(std::vector<InfoCircle> circles,
                                                     const double speed) {
    std::vector<InfoCircle> useful_circles;
    boost::sort(circles,
                [](const InfoCircle& a, const InfoCircle& b) {return a.duration_left > b.duration_left;});
    auto it = circles.begin();
    const auto end = circles.end();
    for (; it != end; ++it) {
        if (!within_info_circle(*it, useful_circles, speed)) {
            useful_circles.push_back(std::move(*it));
        }
    }
    return useful_circles;
}

template<typename T>
static bool in_bound(const T & begin, const T & end, bool clockwise) {
    return (clockwise && begin < end) ||
            (!clockwise && begin > end);
}

type::MultiPolygon build_single_isochrone(RAPTOR& raptor,
                                          const std::vector<type::StopPoint*>& stop_points,
                                          const bool clockwise,
                                          const type::GeographicalCoord& coord_origin,
                                          const DateTime& bound,
                                          const map_stop_point_duration& origin,
                                          const double& speed,
                                          const int& duration) {
    std::vector<InfoCircle> circles_classed;
    type::MultiPolygon circles;
    InfoCircle to_add = InfoCircle(coord_origin, 0, duration);
    circles_classed.push_back(to_add);
    const auto& data_departure = raptor.data.pt_data->stop_points;
    for (auto it = origin.begin(); it != origin.end(); ++it){
        if (it->second.total_seconds() < duration) {
            int duration_left = duration - int(it->second.total_seconds());
            if (duration_left * speed < MIN_RADIUS) {continue;}
            const auto& center = data_departure[it->first.val]->coord;
            InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);
            circles_classed.push_back(to_add);
        }
    }
    for(const type::StopPoint* sp: stop_points) {
        SpIdx sp_idx(*sp);
        const auto best_lbl = raptor.best_labels_pts[sp_idx];
        if (in_bound(best_lbl, bound, clockwise)) {
            uint duration_left = abs(int(best_lbl) - int(bound));
            if (duration_left * speed < MIN_RADIUS) {continue;}
            const auto& center = sp->coord;
            InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);
            circles_classed.push_back(to_add);
        }
    }
    std::vector<InfoCircle> circles_check = delete_useless_circle(std::move(circles_classed), speed);

    for (const auto& c: circles_check) {
        type::Polygon circle_to_add = circle(c.center, c.duration_left * speed);
        circles = merge_poly(circles, circle_to_add);
    }
    return circles;
}

type::MultiPolygon build_isochrones(RAPTOR& raptor,
                                    const bool clockwise,
                                    const type::GeographicalCoord& coord_origin,
                                    const DateTime& bound_max,
                                    const DateTime& bound_min,
                                    const map_stop_point_duration& origin,
                                    const double& speed,
                                    const int& max_duration,
                                    const int& min_duration) {
    type::MultiPolygon isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,
                                                          clockwise, coord_origin, bound_max, origin,
                                                          speed, max_duration);
    if (min_duration > 0) {
       type::MultiPolygon output;
       type::MultiPolygon min_isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,
                                                                 clockwise, coord_origin, bound_min, origin,
                                                                 speed, min_duration);
       boost::geometry::difference(isochrone, min_isochrone, output);
       isochrone = output;
    }
    return isochrone;
}

}} //namespace navitia::routing
<commit_msg>Correction<commit_after>/* Copyright © 2001-2016, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/

#include "type/geographical_coord.h"
#include "utils/exception.h"
#include "isochrone.h"
#include "raptor.h"

#include <set>
#include <assert.h>
#include <vector>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometry.hpp>
#include <cmath>
#include <string>
#include <algorithm>
#include <boost/range/algorithm.hpp>

namespace navitia { namespace routing {

IsochroneException::~IsochroneException() noexcept = default;

type::GeographicalCoord project_in_direction(const type::GeographicalCoord& center,
                                             const double& direction,
                                             const double& radius){
    using navitia::type::GeographicalCoord;
    assert(radius > 0);
    double alpha = radius / GeographicalCoord::EARTH_RADIUS_IN_METERS;
    double direction_rad = fmod(direction, 360) * GeographicalCoord::N_DEG_TO_RAD;
    if (direction < 0) {
        direction_rad = 2 * M_PI - direction_rad;
    }
    double center_lat_deg = center.lat();
    double center_lon_deg = center.lon();
    type::GeographicalCoord center_right_interval = type::GeographicalCoord(center_lon_deg, center_lat_deg);
    double center_lat_rad = center_right_interval.lat() * GeographicalCoord::N_DEG_TO_RAD;
    double center_lon_rad = center_right_interval.lon() * GeographicalCoord::N_DEG_TO_RAD;
    double lat;
    double lon;
    // To avoid rounding error we use ° instread of rad.
    if (fabs(center_right_interval.lat()) == 90) {
        lon = direction_rad - M_PI;
        lat = M_PI_2 - alpha;
    } else {
        double delta_lat;
        double delta_lon;
        if (fmod(direction, 180) == 0) {
            delta_lat = pow(-1, fmod(direction / 180, 2)) * alpha;
            lat = center_lat_rad + delta_lat;
            lon = center_lon_rad;
        } else {
            // asin and acos give results in rad.
            double projection = asin(sin(alpha) * sin(direction_rad));
            delta_lat = acos(cos(alpha) / cos(projection));
            if (direction_rad > M_PI_2 && direction_rad < 3 * M_PI_2) {
                delta_lat = -1 * delta_lat;
            }
            lat = center_lat_rad + delta_lat;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
            if (lat == M_PI_2) {
                delta_lon = (direction == 90 ? 1 : - 1) * alpha;
#pragma GCC diagnostic pop
            } else {
                double b = (cos(alpha) - sin(lat) * sin(center_lat_rad)) / (cos(lat) * cos(center_lat_rad));
                if (fabs(b) > 1) {
                    b = (std::signbit(b) ? fmod(b - 1, 2) + 1 : fmod(b + 1, 2) - 1);
                }
                delta_lon = acos(b);
                if (direction_rad > M_PI) {
                    delta_lon = -1 * delta_lon;
                }
            }
            lon = center_lon_rad + delta_lon;
        }
    }
    // Lon and lat are in °
    double lon_deg = lon * N_RAD_TO_DEG;
    double lat_deg = lat * N_RAD_TO_DEG;
    return type::GeographicalCoord(lon_deg, lat_deg);
}

static type::GeographicalCoord build_sym (const type::GeographicalCoord& point,
                                          const type::GeographicalCoord& center,
                                          const unsigned int& i) {
    if (i % 180 == 0) {
        return type::GeographicalCoord(2*center.lon() - point.lon(), point.lat());
    } else {
        return type::GeographicalCoord(point.lon(), 2*center.lat() - point.lat());
    }
}

type::Polygon circle(const type::GeographicalCoord& center,
                     const double& radius) {
    type::Polygon points;
    auto& points_out = points.outer();
    points_out.reserve(180);
    for (unsigned int i = 0; i <= 90; i += 2) {
        points_out.push_back(project_in_direction(center, i, radius));
    }
    for (unsigned int j = 90; j <= 270; j += 90) {
        for (unsigned int k = 1; k <= 45; k++) {
            type::GeographicalCoord point;
            point = points_out[j / 2 - k];
            points_out.push_back(build_sym(point, center, j));
        }
    }
    points_out.push_back(project_in_direction(center, 0, radius));
    return points;
}

static type::MultiPolygon merge_poly(const type::MultiPolygon& multi_poly,
                                     const type::Polygon& poly) {
    type::MultiPolygon poly_union;
    try {
        boost::geometry::union_(poly, multi_poly, poly_union);
    } catch (const boost::geometry::exception& e) {
        //We don't merge the polygons
        log4cplus::Logger logger = log4cplus::Logger::getInstance("logger");
        LOG4CPLUS_WARN(logger, "impossible to merge polygon: " << e.what());
    }
    return poly_union;
}

struct InfoCircle {
    type::GeographicalCoord center;
    double distance;
    int duration_left;
    InfoCircle(const type::GeographicalCoord& center,
               const double& distance,
               const int& duration_left): center(center),
        distance(distance),
        duration_left(duration_left) {}
};

static bool within_info_circle(const InfoCircle& circle,
                              const std::vector<InfoCircle>& multi_poly,
                              const double speed) {
    auto begin = multi_poly.begin();
    const auto end = multi_poly.end();
    double circle_radius = circle.duration_left * speed;
    double coslat = cos(circle.center.lat() * type::GeographicalCoord::N_DEG_TO_RAD);
    return any_of(begin, end, [&](const InfoCircle& it) {
        double it_radius = it.duration_left * speed;
        return sqrt(circle.center.approx_sqr_distance(it.center, coslat)) + circle_radius < it_radius;
    });
}

static std::vector<InfoCircle> delete_useless_circle(std::vector<InfoCircle> circles,
                                                     const double speed) {
    std::vector<InfoCircle> useful_circles;
    boost::sort(circles,
                [](const InfoCircle& a, const InfoCircle& b) {return a.duration_left > b.duration_left;});
    for (auto& circle: circles) {
        if (!within_info_circle(circle, useful_circles, speed)) {
            useful_circles.push_back(std::move(circle));
        }
    }
    return useful_circles;
}

template<typename T>
static bool in_bound(const T & begin, const T & end, bool clockwise) {
    return (clockwise && begin < end) ||
            (!clockwise && begin > end);
}

type::MultiPolygon build_single_isochrone(RAPTOR& raptor,
                                          const std::vector<type::StopPoint*>& stop_points,
                                          const bool clockwise,
                                          const type::GeographicalCoord& coord_origin,
                                          const DateTime& bound,
                                          const map_stop_point_duration& origin,
                                          const double& speed,
                                          const int& duration) {
    std::vector<InfoCircle> circles_classed;
    type::MultiPolygon circles;
    InfoCircle to_add = InfoCircle(coord_origin, 0, duration);
    circles_classed.push_back(to_add);
    const auto& data_departure = raptor.data.pt_data->stop_points;
    for (auto it = origin.begin(); it != origin.end(); ++it){
        if (it->second.total_seconds() < duration) {
            int duration_left = duration - int(it->second.total_seconds());
            if (duration_left * speed < MIN_RADIUS) {continue;}
            const auto& center = data_departure[it->first.val]->coord;
            InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);
            circles_classed.push_back(to_add);
        }
    }
    for(const type::StopPoint* sp: stop_points) {
        SpIdx sp_idx(*sp);
        const auto best_lbl = raptor.best_labels_pts[sp_idx];
        if (in_bound(best_lbl, bound, clockwise)) {
            uint duration_left = abs(int(best_lbl) - int(bound));
            if (duration_left * speed < MIN_RADIUS) {continue;}
            const auto& center = sp->coord;
            InfoCircle to_add = InfoCircle(center, center.distance_to(coord_origin), duration_left);
            circles_classed.push_back(to_add);
        }
    }
    std::vector<InfoCircle> circles_check = delete_useless_circle(std::move(circles_classed), speed);

    for (const auto& c: circles_check) {
        type::Polygon circle_to_add = circle(c.center, c.duration_left * speed);
        circles = merge_poly(circles, circle_to_add);
    }
    return circles;
}

type::MultiPolygon build_isochrones(RAPTOR& raptor,
                                    const bool clockwise,
                                    const type::GeographicalCoord& coord_origin,
                                    const DateTime& bound_max,
                                    const DateTime& bound_min,
                                    const map_stop_point_duration& origin,
                                    const double& speed,
                                    const int& max_duration,
                                    const int& min_duration) {
    type::MultiPolygon isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,
                                                          clockwise, coord_origin, bound_max, origin,
                                                          speed, max_duration);
    if (min_duration > 0) {
       type::MultiPolygon output;
       type::MultiPolygon min_isochrone = build_single_isochrone(raptor, raptor.data.pt_data->stop_points,
                                                                 clockwise, coord_origin, bound_min, origin,
                                                                 speed, min_duration);
       boost::geometry::difference(isochrone, min_isochrone, output);
       isochrone = output;
    }
    return isochrone;
}

}} //namespace navitia::routing
<|endoftext|>


<commit_before>/*
Copyright 2016 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "OpenGLFunctions.h"
#include "OpenGLTexture.h"
#include "aeongames/ResourceCache.h"
#include "Uniform.h"
#include <cstring>

namespace AeonGames
{
    static_assert ( sizeof ( std::shared_ptr<Texture> ) <= ( sizeof ( float ) * 4 ), "Size of shared pointer is bigger than a vec4" );
    Uniform::Uniform ( const std::string& aName, float aX ) :
        mName ( aName ),
        mType ( GL_FLOAT )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [2] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC2 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC3 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = aZ;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ, float aW ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC4 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = aZ;
        ( reinterpret_cast<float*> ( mData ) ) [3] = aW;
    }
    Uniform::Uniform ( const std::string & aName, const std::string & aFilename ) :
        mName ( aName ),
        mType ( GL_SAMPLER_2D )
    {
        * ( new ( mData ) std::shared_ptr<Texture> ( Get<OpenGLTexture> ( aFilename ) ) );
    }
    Uniform::~Uniform()
    {
        switch ( mType )
        {
        case GL_SAMPLER_2D:
            reinterpret_cast<std::shared_ptr<Texture>*> ( mData )->~shared_ptr();
            break;
        default:
            break;
        }
    }
    void Uniform::SetOffset ( const uint32_t aOffset )
    {
        mOffset = aOffset;
    }
    uint32_t Uniform::Offset() const
    {
        return mOffset;
    }
    const std::string Uniform::GetDeclaration() const
    {
        std::string declaration;
        switch ( mType )
        {
        case GL_FLOAT:
            declaration = "float " + mName + ";\n";
            break;
        case GL_FLOAT_VEC2:
            declaration = "vec2 " + mName + ";\n";
            break;
        case GL_FLOAT_VEC3:
            declaration = "vec3 " + mName + ";\n";
            break;
        case GL_FLOAT_VEC4:
            declaration = "vec4 " + mName + ";\n";
            break;
        case GL_SAMPLER_2D:
            declaration = "sampler2D " + mName + ";\n";
            break;
        }
        return declaration;
    }
    const std::string & Uniform::GetName() const
    {
        return mName;
    }
    void Uniform::CopyTo ( uint8_t * aMemory ) const
    {
        switch ( mType )
        {
        case GL_FLOAT:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) );
            break;
        case GL_FLOAT_VEC2:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 2 );
            break;
        case GL_FLOAT_VEC3:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 3 );
            break;
        case GL_FLOAT_VEC4:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 4 );
            break;
        case GL_SAMPLER_2D:
            * ( reinterpret_cast<uint64_t*> ( aMemory + mOffset ) ) =
                reinterpret_cast<const std::shared_ptr<Texture>*> ( mData )->get()->GetHandle();
            break;
        }
    }
}
<commit_msg>Removed unecesary dereference in Uniform.cpp.<commit_after>/*
Copyright 2016 Rodrigo Jose Hernandez Cordoba

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "OpenGLFunctions.h"
#include "OpenGLTexture.h"
#include "aeongames/ResourceCache.h"
#include "Uniform.h"
#include <cstring>

namespace AeonGames
{
    static_assert ( sizeof ( std::shared_ptr<Texture> ) <= ( sizeof ( float ) * 4 ), "Size of shared pointer is bigger than a vec4" );
    Uniform::Uniform ( const std::string& aName, float aX ) :
        mName ( aName ),
        mType ( GL_FLOAT )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [2] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC2 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = 0;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC3 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = aZ;
        ( reinterpret_cast<float*> ( mData ) ) [3] = 0;
    }
    Uniform::Uniform ( const std::string& aName, float aX, float aY, float aZ, float aW ) :
        mName ( aName ),
        mType ( GL_FLOAT_VEC4 )
    {
        ( reinterpret_cast<float*> ( mData ) ) [0] = aX;
        ( reinterpret_cast<float*> ( mData ) ) [1] = aY;
        ( reinterpret_cast<float*> ( mData ) ) [2] = aZ;
        ( reinterpret_cast<float*> ( mData ) ) [3] = aW;
    }
    Uniform::Uniform ( const std::string & aName, const std::string & aFilename ) :
        mName ( aName ),
        mType ( GL_SAMPLER_2D )
    {
        new ( mData ) std::shared_ptr<Texture> ( Get<OpenGLTexture> ( aFilename ) );
    }
    Uniform::~Uniform()
    {
        switch ( mType )
        {
        case GL_SAMPLER_2D:
            reinterpret_cast<std::shared_ptr<Texture>*> ( mData )->~shared_ptr();
            break;
        default:
            break;
        }
    }
    void Uniform::SetOffset ( const uint32_t aOffset )
    {
        mOffset = aOffset;
    }
    uint32_t Uniform::Offset() const
    {
        return mOffset;
    }
    const std::string Uniform::GetDeclaration() const
    {
        std::string declaration;
        switch ( mType )
        {
        case GL_FLOAT:
            declaration = "float " + mName + ";\n";
            break;
        case GL_FLOAT_VEC2:
            declaration = "vec2 " + mName + ";\n";
            break;
        case GL_FLOAT_VEC3:
            declaration = "vec3 " + mName + ";\n";
            break;
        case GL_FLOAT_VEC4:
            declaration = "vec4 " + mName + ";\n";
            break;
        case GL_SAMPLER_2D:
            declaration = "sampler2D " + mName + ";\n";
            break;
        }
        return declaration;
    }
    const std::string & Uniform::GetName() const
    {
        return mName;
    }
    void Uniform::CopyTo ( uint8_t * aMemory ) const
    {
        switch ( mType )
        {
        case GL_FLOAT:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) );
            break;
        case GL_FLOAT_VEC2:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 2 );
            break;
        case GL_FLOAT_VEC3:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 3 );
            break;
        case GL_FLOAT_VEC4:
            memcpy ( ( aMemory + mOffset ), mData, sizeof ( float ) * 4 );
            break;
        case GL_SAMPLER_2D:
            ( * ( reinterpret_cast<uint64_t*> ( aMemory + mOffset ) ) ) =
                reinterpret_cast<const std::shared_ptr<Texture>*> ( mData )->get()->GetHandle();
            break;
        }
    }
}
<|endoftext|>


<commit_before>/* 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 <gflags/gflags.h>
#include <glog/logging.h>

#include "basebox_api.h"
#include "netlink/nbi_impl.hpp"
#include "netlink/tap_manager.hpp"
#include "of-dpa/controller.hpp"

static volatile sig_atomic_t got_SIGINT = 0;
ApiServer grpcConnector;

static bool validate_port(const char *flagname, gflags::int32 value) {
  if (value > 0 && value < 32768) // value is ok
    return true;
  return false;
}

DEFINE_int32(port, 6654, "Listening port");

int main(int argc, char **argv) {
  if (!gflags::RegisterFlagValidator(&FLAGS_port, &validate_port)) {
    std::cerr << "Failed to register port validator" << std::endl;
    exit(1);
  }

  gflags::SetUsageMessage("");
  gflags::SetVersionString(PACKAGE_VERSION);

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  rofl::openflow::cofhello_elem_versionbitmap versionbitmap;
  versionbitmap.add_ofp_version(rofl::openflow13::OFP_VERSION);
  LOG(INFO) << "using OpenFlow version-bitmap:" << std::endl << versionbitmap;

  basebox::nbi_impl *nbi = new basebox::nbi_impl();
  std::unique_ptr<basebox::controller> box(
      new basebox::controller(nbi, versionbitmap));

  rofl::csockaddr baddr(AF_INET, std::string("0.0.0.0"), FLAGS_port);
  box->dpt_sock_listen(baddr);

  grpcConnector.runGRPCServer();

  delete nbi;

  LOG(INFO) << "bye";
  return EXIT_SUCCESS;
}
<commit_msg>removed additional files<commit_after><|endoftext|>


<commit_before><commit_msg>Fix uninitialized flag<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2013 Matthew Harvey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of wxComboBox and wxTextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.

// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.

/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.

// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or at least provide an easy process for installing updates
// via NSIS. It appears that the default configuration of CPack/NSIS is
// such that updates will not overwrite existing files. Some manual NSIS
// scripting may be required to enable this. Also take into account that
// the user may have to restart their computer in the event that they have
// files open while the installer (or "updater") is running (although I
// \e think that the default configuration under CPack does this
// automatically).

// TODO HIGH PRIORITY Create a decent icon for the application. We want this
// in both .ico form (for Windows executable icon) and .xpm
// form (for icon for Frame). Note, when I exported my
// "token icon" using GIMP to .ico format, and later used this
// to create a double-clickable icon in Windows, only the text
// on the icon appeared, and the background image became
// transparent for some reason. Furthermore, when set as the
// large in-windows icon in the CPack/NSIS installer, the icon
// wasn't showing at all. Once decent icon is created, also make sure it is
// pulled into the wxBitmap in SetupWizard.

// TODO HIGH PRIORITY Create a better name for the application.

// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.

// TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when
// compiled in Release mode.

// TODO MEDIUM PRIORITY Give user the option to export to CSV.

// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.

// TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some
// machines, tab traversal is not working properly in SetupWizard, and you
// can't traverse out of a wxComboBox using tab, for some reason.

#include "app.hpp"
#include <wx/app.h>

wxIMPLEMENT_APP(phatbooks::App);
<commit_msg>Added some more TODOs.<commit_after>/*
 * Copyright 2013 Matthew Harvey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO HIGH PRIORITY Under KDE (at least on Mageia) the way I have set
// up the widths of wxComboBox and wxTextCtrl and wxButton (in various
// controls in which these feature), where they are
// supposed to be the same height, they actually turn out to be slightly
// different heights. However even if I manually set them all to the same
// hard-coded height number, they still seem to come out different heights
// on KDE. It doesn't make a lot of sense.

// TODO MEDIUM PRIORITY Tooltips aren't showing on Windows.

/// TODO MEDIUM PRIORITY The database file should perhaps have a checksum to
// guard against its contents changing other than via the application.

// TODO HIGH PRIORITY Facilitate automatic checking for updates from user's
// machine, or at least provide an easy process for installing updates
// via NSIS. It appears that the default configuration of CPack/NSIS is
// such that updates will not overwrite existing files. Some manual NSIS
// scripting may be required to enable this. Also take into account that
// the user may have to restart their computer in the event that they have
// files open while the installer (or "updater") is running (although I
// \e think that the default configuration under CPack does this
// automatically).

// TODO HIGH PRIORITY Create a decent icon for the application. We want this
// in both .ico form (for Windows executable icon) and .xpm
// form (for icon for Frame). Note, when I exported my
// "token icon" using GIMP to .ico format, and later used this
// to create a double-clickable icon in Windows, only the text
// on the icon appeared, and the background image became
// transparent for some reason. Furthermore, when set as the
// large in-windows icon in the CPack/NSIS installer, the icon
// wasn't showing at all. Once decent icon is created, also make sure it is
// pulled into the wxBitmap in SetupWizard.

// TODO HIGH PRIORITY Create a better name for the application.

// TODO HIGH PRIORITY Make the GUI display acceptably on smaller screen
// i.e. laptop.

// TODO MEDIUM PRIORITY Startup time under Windows is really slow, even when
// compiled in Release mode.

// TODO MEDIUM PRIORITY Give user the option to export to CSV.

// TODO LOW PRIORITY Allow export/import to/from .qif (?) format.

// TODO HIGH PRIORITY On Windows, at least on Windows 7, at least on some
// machines, tab traversal is not working properly in SetupWizard, and you
// can't traverse out of a wxComboBox using tab, for some reason.

// TODO MEDIUM PRIORITY Allow window borders to be dragged around, especially
// for DraftJournalListCtrl. This make it easier for users on laptops.

#include "app.hpp"
#include <wx/app.h>

wxIMPLEMENT_APP(phatbooks::App);
<|endoftext|>


<commit_before>// Problem 5 from Project Euler
// http://projecteuler.net/problem=5

#include <iostream>
#include <math.h>
#include <limits>

int main()
{
  bool is_multiple;

  while (!is_multiple)
    {
      for (unsigned int n = 0; n < std::numeric_limits<unsigned int>::max(); n += 80)
        {
          is_multiple = true;

          if (n == 0)
            {
              continue;
            }

          for (unsigned int i = 2; i <= 20; i++)
            {
              if (n % i != 0)
                {
                  is_multiple = false;
                  break;
                }
            }
          if (is_multiple)
            {
              std::cout << "The answer is " << n << std::endl;
              exit(0);
            }
        }
    }
}
<commit_msg>Removed unnecessary include<commit_after>// Problem 5 from Project Euler
// http://projecteuler.net/problem=5

#include <iostream>
#include <limits>

int main()
{
  bool is_multiple;

  while (!is_multiple)
    {
      for (unsigned int n = 0; n < std::numeric_limits<unsigned int>::max(); n += 80)
        {
          is_multiple = true;

          if (n == 0)
            {
              continue;
            }

          for (unsigned int i = 2; i <= 20; i++)
            {
              if (n % i != 0)
                {
                  is_multiple = false;
                  break;
                }
            }
          if (is_multiple)
            {
              std::cout << "The answer is " << n << std::endl;
              exit(0);
            }
        }
    }
}
<|endoftext|>