<commit_before>/*
 * ZSUMMER License
 * -----------
 *
 * ZSUMMER is licensed under the terms of the MIT license reproduced below.
 * This means that ZSUMMER is free software and can be used for both academic
 * and commercial purposes at absolutely no cost.
 *
 *
 * ===============================================================================
 *
 * Copyright (C) 2010-2013 YaweiZhang <yawei_zhang@foxmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * ===============================================================================
 *
 * (end of COPYRIGHT)
 */

//! zsummerĲԿͻģ
//! mainļ

#include "../../utility/utility.h"
#include "../../depends/thread4z/thread.h"
#include "../../depends/log4z/log4z.h"
#include "../../network/SocketInterface.h"
#include "../../depends/protocol4z/protocol4z.h"
#include <iostream>
#include <queue>
#include <iomanip>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
using namespace std;

//! ϢС
#define _MSG_BUF_LEN	(8*1024)

//! Ϣ
struct Packet
{
	unsigned short _len;
	unsigned int   _senddelay;
	char		   _body[_MSG_BUF_LEN];
};

int g_msgdelay[10] = {0};
int g_senddelay[10] = {0};
enum MSG_DELAY
{
	MD_1MS, // < 1 ms
	MD_5MS, // < 5 ms
	MD_10MS,
	MD_100MS,
	MD_1000MS,
	MD_ERRORMS,// error dalay time
};

//! ϲSocekt ClientĶηװ
class CClient :public zsummer::network::ITcpSocketCallback
{
public:
	CClient()
	{
		m_socket = NULL;
		m_establish = 0;
		memset(&m_recving, 0, sizeof(m_recving));
		m_curRecvLen = 0;
		memset(&m_sending, 0, sizeof(m_sending));
		m_curSendLen = 0;
		m_text.resize(1000, 'a');
	}
	~CClient()
	{

	}
	void OnTimer()
	{
		if (m_establish)
		{
			SendOnce();
		}
	}
	virtual bool OnRecv(unsigned int nRecvedLen)
	{
		m_curRecvLen += nRecvedLen;
		int needRecv = zsummer::protocol4z::CheckBuffIntegrity(m_recving._body, m_curRecvLen, _MSG_BUF_LEN);
		if ( needRecv == -1)
		{
			LOGE("killed socket: CheckBuffIntegrity error ");
			m_socket->Close();
			return false;
		}
		if (needRecv > 0)
		{
			m_socket->DoRecv(m_recving._body+m_curRecvLen, needRecv);
			return true;
		}

		//!  Ϣ
		zsummer::protocol4z::ReadStream rs(m_recving._body, m_curRecvLen);
		try
		{
			MessageEntry(rs);
		}
		catch (std::runtime_error e)
		{
			LOGE("MessageEntry catch one exception: "<< e.what() );
			m_socket->Close();
			return false;
		}
		//! հ
		memset(&m_recving, 0, sizeof(m_recving));
		m_curRecvLen = 0;
		m_socket->DoRecv(m_recving._body, 2);
		return true;
	}
	virtual bool OnConnect(bool bConnected)
	{
		if (bConnected)
		{
			m_establish = 1;
			OnRecv(0);
			LOGI("establish connect");
		}
		else
		{
			LOGI("connect false!");
		}
		return true;
	}
	virtual bool OnSend(unsigned int nSentLen)
	{
		m_curSendLen += nSentLen;
		if (m_curSendLen < m_sending._len)
		{
			m_socket->DoSend(&m_sending._body[m_curSendLen], m_sending._len - m_curSendLen);
		}
		else if (m_curSendLen == m_sending._len)
		{
			unsigned int senduse = zsummer::utility::GetTimeMillisecond();
			senduse = senduse - m_sending._senddelay;
			if (senduse <=1)
			{
				g_senddelay[MD_1MS]++;
			}
			else if (senduse <= 5)
			{
				g_senddelay[MD_5MS]++;
			}
			else if (senduse <= 10)
			{
				g_senddelay[MD_10MS]++;
			}
			else if (senduse <= 100)
			{
				g_senddelay[MD_100MS]++;
			}
			else if (senduse <= 1000)
			{
				g_senddelay[MD_1000MS]++;
			}
			else
			{
				g_senddelay[MD_ERRORMS]++;
			}
			LOGD("send one msg, used time=" << senduse);

			m_curSendLen = 0;
			if (m_sendque.empty())
			{
				m_sending._len = 0;
			}
			else
			{
				Packet *p = m_sendque.front();
				m_sendque.pop();
				memcpy((char*)&m_sending, p, sizeof(m_sending));
				delete p;
				m_socket->DoSend(m_sending._body, p->_len);
			}
		}
		return true;
	}
	virtual bool OnClose()
	{
		LOGI("Client Closed!");
		return true;
	}
	void MessageEntry(zsummer::protocol4z::ReadStream & rs)
	{
		//Э쳣ᱻϲ㲶񲢹ر
		unsigned short protocolID = 0;
		rs >> protocolID;
		switch (protocolID)
		{
		case 1:
			{
				unsigned int localTick = 0;
				std::string text;
				rs >> localTick >> text;

				unsigned int curTick = zsummer::utility::GetTimeMillisecond();
				curTick = curTick - localTick;
				if (curTick <= 1)
				{
					g_msgdelay[MD_1MS]++;
				}
				else if (curTick <= 5)
				{
					g_msgdelay[MD_5MS]++;
				}
				else if (curTick <= 10)
				{
					g_msgdelay[MD_10MS]++;
				}
				else if (curTick <= 100)
				{
					g_msgdelay[MD_100MS]++;
				}
				else if (curTick <= 1000)
				{
					g_msgdelay[MD_1000MS]++;
				}
				else
				{
					g_msgdelay[MD_ERRORMS]++;
				}
//				LOGD("recv one msg, used time=" << curTick - localTick);

			}
			break;
		default:
			{
				LOGI("unknown protocol id = " << protocolID);
			}
			break;
		}
	}
	void SendOnce()
	{

		Packet *p=NULL;
		if (m_sending._len != 0)
		{
			p = new Packet;
		}
		else
		{
			p = &m_sending;
		}
		p->_senddelay = zsummer::utility::GetTimeMillisecond();
		zsummer::protocol4z::WriteStream ws(p->_body, _MSG_BUF_LEN);
		ws << (unsigned short) 1; //protocol id
		ws << p->_senddelay; // local tick count
		ws << m_text; // append text, fill the length protocol.
		p->_len = ws.GetWriteLen();
		if (p == &m_sending)
		{
			m_socket->DoSend(p->_body, p->_len);
		}
		else
		{
			m_sendque.push(p);
		}
	}
	zsummer::network::ITcpSocket * m_socket;
	unsigned char m_establish;

	//!
	Packet m_recving;
	unsigned short m_curRecvLen;
	//! д
	std::queue<Packet *> m_sendque;

	//! ǰд
	Packet m_sending;
	unsigned short m_curSendLen;
	std::string m_text;
};

class CZSummer : public zsummer::network::IIOServerCallback
{
public:
	CZSummer()
	{
		m_ios = NULL;
		m_accept = NULL;
		m_clientMax = 0;
	}
	~CZSummer()
	{
		if (m_ios)
		{
			zsummer::network::DestroyIOServer(m_ios);
			m_ios = NULL;
		}

	}
	bool Run(std::string ip, unsigned short port, int clients)
	{
		m_ip = ip;
		m_port = port;
		m_clientMax = clients;

		m_ios =zsummer::network::CreateIOServer();
		if (!m_ios)
		{
			return false;
		}
		if (!m_ios->Initialize(this))
		{
			return false;
		}
		while(true)
		{
			m_ios->RunOnce();
		}
		return true;
	}

	virtual bool OnPost(void *pUser)
	{
		return true;
	}
	//! IIOServer's Timerr. per 1 seconds trigger. Don't spend too much time in here.
	virtual bool OnTimer()
	{
		//ÿ200ӳconnect
		int clientCount=m_clients.size();
		if (clientCount < m_clientMax)
		{
			int n=0;
			while (clientCount++ < m_clientMax && n++ < 200)
			{
				CClient * p = new CClient;
				p->m_socket = zsummer::network::CreateTcpSocket();
				p->m_socket->Initialize(m_ios, p);
				p->m_socket->DoConnect(m_ip.c_str(), m_port);
				m_clients.push_back(p);
			}
		}
		//socketʱ
		else
		{
			for (int i=0; i<m_clients.size(); i++)
			{
				m_clients[i]->OnTimer();
			}
		}

		//ͳ
		{
			static unsigned int count = 0;
			if (count%3 == 0)
			{
				LOGI("\nMSG TIME DELAY : MD<1MS=" << g_msgdelay[MD_1MS]
				<< " MD<5MS=" << g_msgdelay[MD_5MS]
				<< " MD<10MS=" << g_msgdelay[MD_10MS]
				<< " MD<100MS=" << g_msgdelay[MD_100MS]
				<< " MD<1000MS=" << g_msgdelay[MD_1000MS]
				<< " MD<ERRORMS=" << g_msgdelay[MD_ERRORMS]
				<< "\n"
				<< "SEND TIME DELAY : MD<1MS=" << g_msgdelay[MD_1MS]
				<< " MD<5MS=" << g_senddelay[MD_5MS]
				<< " MD<10MS=" << g_senddelay[MD_10MS]
				<< " MD<100MS=" << g_senddelay[MD_100MS]
				<< " MD<1000MS=" << g_senddelay[MD_1000MS]
				<< " MD<ERRORMS=" << g_senddelay[MD_ERRORMS]
				);
			}
			count++;
		}
		return true;
	}

private:
	zsummer::network::IIOServer * m_ios;
	zsummer::network::ITcpAccept * m_accept;
	std::string m_ip;
	unsigned short m_port;
	int m_clientMax;
	std::vector<CClient*> m_clients;
};

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

#ifndef _WIN32
	//! linuxҪεһЩź
	signal( SIGHUP, SIG_IGN );
	signal( SIGALRM, SIG_IGN );
	signal( SIGPIPE, SIG_IGN );
	signal( SIGXCPU, SIG_IGN );
	signal( SIGXFSZ, SIG_IGN );
	signal( SIGPROF, SIG_IGN );
	signal( SIGVTALRM, SIG_IGN );
	signal( SIGQUIT, SIG_IGN );
	signal( SIGCHLD, SIG_IGN);
#endif
	//! ־
	zsummer::log4z::ILog4zManager::GetInstance()->Config("config.cfg");
	zsummer::log4z::ILog4zManager::GetInstance()->Start();
	//! ip:port:count   ֱӦIP PORTҪӵsocket.
	char buf[100];
	zsummer::utility::SleepMillisecond(500);// ʾ־.
	cout <<"please entry: \"ip:port:link_count\",  like  127.0.0.1:80:100"<<endl;
	cin >> buf;
	char *pRet = strtok(buf, ":");
	std::string ip = pRet?pRet:"";
	pRet = strtok(NULL, ":");
	unsigned short port = pRet?(unsigned short)atoi(pRet):0;
	pRet = strtok(NULL, ":");
	int linkcount = pRet?atoi(pRet):0;
	if (port == 0 || linkcount <=0)
	{
		LOGF("user entry string error. string=" << buf );
		return 0;
	}

	CZSummer summer;
	summer.Run(ip, port, linkcount);

	return 0;
}

<commit_msg>input ip port count<commit_after>/*
 * ZSUMMER License
 * -----------
 *
 * ZSUMMER is licensed under the terms of the MIT license reproduced below.
 * This means that ZSUMMER is free software and can be used for both academic
 * and commercial purposes at absolutely no cost.
 *
 *
 * ===============================================================================
 *
 * Copyright (C) 2010-2013 YaweiZhang <yawei_zhang@foxmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * ===============================================================================
 *
 * (end of COPYRIGHT)
 */

//! zsummerĲԿͻģ
//! mainļ

#include "../../utility/utility.h"
#include "../../depends/thread4z/thread.h"
#include "../../depends/log4z/log4z.h"
#include "../../network/SocketInterface.h"
#include "../../depends/protocol4z/protocol4z.h"
#include <iostream>
#include <queue>
#include <iomanip>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
using namespace std;

//! ϢС
#define _MSG_BUF_LEN	(8*1024)

//! Ϣ
struct Packet
{
	unsigned short _len;
	unsigned int   _senddelay;
	char		   _body[_MSG_BUF_LEN];
};

int g_msgdelay[10] = {0};
int g_senddelay[10] = {0};
enum MSG_DELAY
{
	MD_1MS, // < 1 ms
	MD_5MS, // < 5 ms
	MD_10MS,
	MD_100MS,
	MD_1000MS,
	MD_ERRORMS,// error dalay time
};

//! ϲSocekt ClientĶηװ
class CClient :public zsummer::network::ITcpSocketCallback
{
public:
	CClient()
	{
		m_socket = NULL;
		m_establish = 0;
		memset(&m_recving, 0, sizeof(m_recving));
		m_curRecvLen = 0;
		memset(&m_sending, 0, sizeof(m_sending));
		m_curSendLen = 0;
		m_text.resize(1000, 'a');
	}
	~CClient()
	{

	}
	void OnTimer()
	{
		if (m_establish)
		{
			SendOnce();
		}
	}
	virtual bool OnRecv(unsigned int nRecvedLen)
	{
		m_curRecvLen += nRecvedLen;
		int needRecv = zsummer::protocol4z::CheckBuffIntegrity(m_recving._body, m_curRecvLen, _MSG_BUF_LEN);
		if ( needRecv == -1)
		{
			LOGE("killed socket: CheckBuffIntegrity error ");
			m_socket->Close();
			return false;
		}
		if (needRecv > 0)
		{
			m_socket->DoRecv(m_recving._body+m_curRecvLen, needRecv);
			return true;
		}

		//!  Ϣ
		zsummer::protocol4z::ReadStream rs(m_recving._body, m_curRecvLen);
		try
		{
			MessageEntry(rs);
		}
		catch (std::runtime_error e)
		{
			LOGE("MessageEntry catch one exception: "<< e.what() );
			m_socket->Close();
			return false;
		}
		//! հ
		memset(&m_recving, 0, sizeof(m_recving));
		m_curRecvLen = 0;
		m_socket->DoRecv(m_recving._body, 2);
		return true;
	}
	virtual bool OnConnect(bool bConnected)
	{
		if (bConnected)
		{
			m_establish = 1;
			OnRecv(0);
			LOGI("establish connect");
		}
		else
		{
			LOGI("connect false!");
		}
		return true;
	}
	virtual bool OnSend(unsigned int nSentLen)
	{
		m_curSendLen += nSentLen;
		if (m_curSendLen < m_sending._len)
		{
			m_socket->DoSend(&m_sending._body[m_curSendLen], m_sending._len - m_curSendLen);
		}
		else if (m_curSendLen == m_sending._len)
		{
			unsigned int senduse = zsummer::utility::GetTimeMillisecond();
			senduse = senduse - m_sending._senddelay;
			if (senduse <=1)
			{
				g_senddelay[MD_1MS]++;
			}
			else if (senduse <= 5)
			{
				g_senddelay[MD_5MS]++;
			}
			else if (senduse <= 10)
			{
				g_senddelay[MD_10MS]++;
			}
			else if (senduse <= 100)
			{
				g_senddelay[MD_100MS]++;
			}
			else if (senduse <= 1000)
			{
				g_senddelay[MD_1000MS]++;
			}
			else
			{
				g_senddelay[MD_ERRORMS]++;
			}
			//LOGD("send one msg, used time=" << senduse);

			m_curSendLen = 0;
			if (m_sendque.empty())
			{
				m_sending._len = 0;
			}
			else
			{
				Packet *p = m_sendque.front();
				m_sendque.pop();
				memcpy((char*)&m_sending, p, sizeof(m_sending));
				delete p;
				m_socket->DoSend(m_sending._body, p->_len);
			}
		}
		return true;
	}
	virtual bool OnClose()
	{
		LOGI("Client Closed!");
		return true;
	}
	void MessageEntry(zsummer::protocol4z::ReadStream & rs)
	{
		//Э쳣ᱻϲ㲶񲢹ر
		unsigned short protocolID = 0;
		rs >> protocolID;
		switch (protocolID)
		{
		case 1:
			{
				unsigned int localTick = 0;
				std::string text;
				rs >> localTick >> text;

				unsigned int curTick = zsummer::utility::GetTimeMillisecond();
				curTick = curTick - localTick;
				if (curTick <= 1)
				{
					g_msgdelay[MD_1MS]++;
				}
				else if (curTick <= 5)
				{
					g_msgdelay[MD_5MS]++;
				}
				else if (curTick <= 10)
				{
					g_msgdelay[MD_10MS]++;
				}
				else if (curTick <= 100)
				{
					g_msgdelay[MD_100MS]++;
				}
				else if (curTick <= 1000)
				{
					g_msgdelay[MD_1000MS]++;
				}
				else
				{
					g_msgdelay[MD_ERRORMS]++;
				}
//				LOGD("recv one msg, used time=" << curTick - localTick);

			}
			break;
		default:
			{
				LOGI("unknown protocol id = " << protocolID);
			}
			break;
		}
	}
	void SendOnce()
	{

		Packet *p=NULL;
		if (m_sending._len != 0)
		{
			p = new Packet;
		}
		else
		{
			p = &m_sending;
		}
		p->_senddelay = zsummer::utility::GetTimeMillisecond();
		zsummer::protocol4z::WriteStream ws(p->_body, _MSG_BUF_LEN);
		ws << (unsigned short) 1; //protocol id
		ws << p->_senddelay; // local tick count
		ws << m_text; // append text, fill the length protocol.
		p->_len = ws.GetWriteLen();
		if (p == &m_sending)
		{
			m_socket->DoSend(p->_body, p->_len);
		}
		else
		{
			m_sendque.push(p);
		}
	}
	zsummer::network::ITcpSocket * m_socket;
	unsigned char m_establish;

	//!
	Packet m_recving;
	unsigned short m_curRecvLen;
	//! д
	std::queue<Packet *> m_sendque;

	//! ǰд
	Packet m_sending;
	unsigned short m_curSendLen;
	std::string m_text;
};

class CZSummer : public zsummer::network::IIOServerCallback
{
public:
	CZSummer()
	{
		m_ios = NULL;
		m_accept = NULL;
		m_clientMax = 0;
	}
	~CZSummer()
	{
		if (m_ios)
		{
			zsummer::network::DestroyIOServer(m_ios);
			m_ios = NULL;
		}

	}
	bool Run(std::string ip, unsigned short port, int clients)
	{
		m_ip = ip;
		m_port = port;
		m_clientMax = clients;

		m_ios =zsummer::network::CreateIOServer();
		if (!m_ios)
		{
			return false;
		}
		if (!m_ios->Initialize(this))
		{
			return false;
		}
		while(true)
		{
			m_ios->RunOnce();
		}
		return true;
	}

	virtual bool OnPost(void *pUser)
	{
		return true;
	}
	//! IIOServer's Timerr. per 1 seconds trigger. Don't spend too much time in here.
	virtual bool OnTimer()
	{
		//ÿ200ӳconnect
		int clientCount=m_clients.size();
		if (clientCount < m_clientMax)
		{
			int n=0;
			while (clientCount++ < m_clientMax && n++ < 200)
			{
				CClient * p = new CClient;
				p->m_socket = zsummer::network::CreateTcpSocket();
				p->m_socket->Initialize(m_ios, p);
				p->m_socket->DoConnect(m_ip.c_str(), m_port);
				m_clients.push_back(p);
			}
		}
		//socketʱ
		else
		{
			for (int i=0; i<m_clients.size(); i++)
			{
				m_clients[i]->OnTimer();
			}
		}

		//ͳ
		{
			static unsigned int count = 0;
			if (count%3 == 0)
			{
				LOGI("\nMSG TIME DELAY : MD<1MS=" << g_msgdelay[MD_1MS]
				<< " MD<5MS=" << g_msgdelay[MD_5MS]
				<< " MD<10MS=" << g_msgdelay[MD_10MS]
				<< " MD<100MS=" << g_msgdelay[MD_100MS]
				<< " MD<1000MS=" << g_msgdelay[MD_1000MS]
				<< " MD<ERRORMS=" << g_msgdelay[MD_ERRORMS]
				<< "\n"
				<< "SEND TIME DELAY : MD<1MS=" << g_msgdelay[MD_1MS]
				<< " MD<5MS=" << g_senddelay[MD_5MS]
				<< " MD<10MS=" << g_senddelay[MD_10MS]
				<< " MD<100MS=" << g_senddelay[MD_100MS]
				<< " MD<1000MS=" << g_senddelay[MD_1000MS]
				<< " MD<ERRORMS=" << g_senddelay[MD_ERRORMS]
				);
			}
			count++;
		}
		return true;
	}

private:
	zsummer::network::IIOServer * m_ios;
	zsummer::network::ITcpAccept * m_accept;
	std::string m_ip;
	unsigned short m_port;
	int m_clientMax;
	std::vector<CClient*> m_clients;
};

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

#ifndef _WIN32
	//! linuxҪεһЩź
	signal( SIGHUP, SIG_IGN );
	signal( SIGALRM, SIG_IGN );
	signal( SIGPIPE, SIG_IGN );
	signal( SIGXCPU, SIG_IGN );
	signal( SIGXFSZ, SIG_IGN );
	signal( SIGPROF, SIG_IGN );
	signal( SIGVTALRM, SIG_IGN );
	signal( SIGQUIT, SIG_IGN );
	signal( SIGCHLD, SIG_IGN);
#endif
	//! ־
	zsummer::log4z::ILog4zManager::GetInstance()->Config("config.cfg");
	zsummer::log4z::ILog4zManager::GetInstance()->Start();
	//! ip:port:count   ֱӦIP PORTҪӵsocket.
	char buf[100];
	zsummer::utility::SleepMillisecond(500);// ʾ־.
	cout <<"please entry ip" <<endl;
	std::string ip;
	cin >> ip;
	unsigned short port =0;
	cout << "please entry port" << endl;
	cin >> port;
	cout << "please entry create link count" << endl;
	unsigned short count = 0;
	cin >> count;
	if (port == 0 || count <=0)
	{
		LOGF("user entry is error. ip=" << ip << ", port=" << port << ", count=" << count);
		return 0;
	}
	else
	{
		LOGI("user entry is ip=" << ip << ", port=" << port << ", count=" << count);
	}

	CZSummer summer;
	summer.Run(ip, port, count);

	return 0;
}

<|endoftext|>


<commit_before>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "select_ev.h"
#ifndef _WINDOWS_
# include <winsock2.h>
#endif
#include <string.h>
#include <algorithm>
#include "socket.h"
#include "win_select_poll.h"

struct win_fd_set {
  u_int fd_count;
  int fd_array[1];
};

struct SelectEntry {
  int fd;
  Socket* s;
};

#define WINFD_SET(fd, set) do {\
  u_int __i;\
  for (__i = 0; __i < ((win_fd_set*)(set))->fd_count; ++__i) {\
    if ((fd) == ((win_fd_set*)(set))->fd_array[__i])\
      break;\
  }\
  if (__i == ((win_fd_set*)(set))->fd_count) {\
    ((win_fd_set*)(set))->fd_array[__i] = (fd);\
    ++((win_fd_set*)(set))->fd_count;\
  }\
} while (0)
#define WINFD_ZERO    FD_ZERO
#define WINFD_CLR     FD_CLR
#define WINFD_ISSET   FD_ISSET
#define WINFD_COPY(dest, src) do {\
  (dest)->fd_count = (src)->fd_count;\
  memcpy((dest)->fd_array, (src)->fd_array, (src)->fd_count * sizeof(int));\
} while (0)

SelectPoll::SelectPoll(void)
  : max_fd_(kNetTypeInval)
  , has_removed_(false)
  , fd_count_(FD_SETSIZE)
  , rset_in_(NULL)
  , wset_in_(NULL)
  , rset_out_(NULL)
  , wset_out_(NULL)
{
}

SelectPoll::~SelectPoll(void)
{
}

bool
SelectPoll::Init(void)
{
  fd_count_ = FD_SETSIZE;
  size_t set_size = sizeof(win_fd_set) + (fd_count_ - 1) * sizeof(int);

  rset_in_ = (win_fd_set*)malloc(set_size);
  if (NULL == rset_in_)
    return false;

  do {
    wset_in_ = (win_fd_set*)malloc(set_size);
    if (NULL == wset_in_)
      break;

    rset_out_ = (win_fd_set*)malloc(set_size);
    if (NULL == rset_out_)
      break;
    wset_out_ = (win_fd_set*)malloc(set_size);
    if (NULL == wset_out_)
      break;

    WINFD_ZERO(rset_in_);
    WINFD_ZERO(wset_in_);

    return true;
  } while (0);

  if (NULL != rset_out_) {
    free(rset_out_);
    rset_out_ = NULL;
  }
  if (NULL != wset_in_) {
    free(wset_in_);
    wset_in_ = NULL;
  }
  if (NULL != rset_in_) {
    free(rset_in_);
    rset_in_ = NULL;
  }

  return false;
}

void
SelectPoll::Destroy(void)
{
  if (NULL != rset_in_) {
    free(rset_in_);
    rset_in_ = NULL;
  }
  if (NULL != wset_in_) {
    free(wset_in_);
    wset_in_ = NULL;
  }

  if (NULL != rset_out_) {
    free(rset_out_);
    rset_out_ = NULL;
  }
  if (NULL != wset_out_) {
    free(wset_out_);
    wset_out_ = NULL;
  }
}

bool
SelectPoll::Regrow(void)
{
  int new_fd_count = (0 != fd_count_ ? 2 * fd_count_ : FD_SETSIZE);
  size_t set_size = sizeof(win_fd_set) + (new_fd_count - 1) * sizeof(int);

  rset_in_ = (win_fd_set*)realloc(rset_in_, set_size);
  if (NULL == rset_in_)
    return false;

  do {
    wset_in_ = (win_fd_set*)realloc(wset_in_, set_size);
    if (NULL == wset_in_)
      break;

    rset_out_ = (win_fd_set*)realloc(rset_out_, set_size);
    if (NULL == rset_out_)
      break;
    wset_out_ = (win_fd_set*)realloc(wset_out_, set_size);
    if (NULL == wset_out_)
      break;

    fd_count_ = new_fd_count;
    return true;
  } while (0);

  return false;
}

bool
SelectPoll::Insert(int fd, Socket* s)
{
  if (entry_list_.size() + 1 > (size_t)fd_count_) {
    if (!Regrow())
      return false;
  }

  SelectEntry entry = {fd, s};
  entry_list_.push_back(entry);

  if (fd > max_fd_)
    max_fd_ = fd;

  return true;
}

void
SelectPoll::Remove(int fd)
{
  std::vector<SelectEntry>::iterator it;
  for (it = entry_list_.begin(); it != entry_list_.end(); ++it) {
    if (fd == it->fd)
      break;
  }

  if (it == entry_list_.end())
    return;
  it->fd = kNetTypeInval;
  has_removed_ = true;

  WINFD_CLR(fd, rset_in_);
  WINFD_CLR(fd, wset_in_);

  WINFD_CLR(fd, rset_out_);
  WINFD_CLR(fd, wset_out_);

  if (fd == max_fd_) {
    max_fd_ = kNetTypeInval;
    for (it = entry_list_.begin(); it != entry_list_.end(); ++it) {
      if (it->fd > max_fd_)
        max_fd_ = it->fd;
    }
  }
}

bool
SelectPoll::AddEvent(int fd, int ev)
{
  if (ev & kEventTypeRead)
    WINFD_SET(fd, rset_in_);

  if (ev & kEventTypeWrite)
    WINFD_SET(fd, wset_in_);

  return true;
}

bool
SelectPoll::DelEvent(int fd, int ev)
{
  if (ev & kEventTypeRead)
    WINFD_CLR(fd, rset_in_);

  if (ev & kEventTypeWrite)
    WINFD_CLR(fd, wset_in_);

  return true;
}

static inline bool
HasSetRemoved(const SelectEntry& entry)
{
  return (kNetTypeInval == entry.fd);
}

bool
SelectPoll::Dispatch(EventDispatcher* dispatcher, int millitm)
{
  if (NULL == dispatcher)
    return false;

  struct timeval tv;
  if (-1 == millitm) {
    tv.tv_sec = 0;
    tv.tv_usec = 500;
  }
  else {
    tv.tv_sec = millitm / 1000;
    tv.tv_usec = (millitm % 1000) * 1000;
  }

  WINFD_COPY(rset_out_, rset_in_);
  WINFD_COPY(wset_out_, wset_in_);

  int ret = select(max_fd_ + 1,
      (struct fd_set*)rset_out_,
      (struct fd_set*)wset_out_, NULL, &tv);
  if (kNetTypeError == ret || 0 == ret)
    return false;

  int size = (int)entry_list_.size();
  SelectEntry* entry;
  for (int i = 0; i < size; ++i) {
    entry = &entry_list_[i];

    if (kNetTypeInval == entry->fd)
      continue;
    if (WINFD_ISSET(entry->fd, rset_out_)) {
      //! TODO:
      //! dispatcher reader
    }

    if (kNetTypeInval == entry->fd)
      continue;
    if (WINFD_ISSET(entry->fd, wset_out_)) {
      //! TODO:
      //! dispatcher writer
    }
  }

  if (has_removed_) {
    entry_list_.erase(std::remove_if(entry_list_.begin(),
          entry_list_.end(), HasSetRemoved), entry_list_.end());
    has_removed_ = false;
  }

  return true;
}
<commit_msg>improved select poll module in windows platform<commit_after>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "select_ev.h"
#ifndef _WINDOWS_
# include <winsock2.h>
#endif
#include <string.h>
#include <algorithm>
#include "socket.h"
#include "win_select_poll.h"

struct win_fd_set {
  u_int fd_count;
  int fd_array[1];
};

struct SelectEntry {
  int fd;
  Socket* s;
};

#define WINFD_SET(fd, set) do {\
  u_int __i;\
  for (__i = 0; __i < ((win_fd_set*)(set))->fd_count; ++__i) {\
    if ((fd) == ((win_fd_set*)(set))->fd_array[__i])\
      break;\
  }\
  if (__i == ((win_fd_set*)(set))->fd_count) {\
    ((win_fd_set*)(set))->fd_array[__i] = (fd);\
    ++((win_fd_set*)(set))->fd_count;\
  }\
} while (0)
#define WINFD_ZERO    FD_ZERO
#define WINFD_CLR     FD_CLR
#define WINFD_ISSET   FD_ISSET
#define WINFD_COPY(dest, src) do {\
  (dest)->fd_count = (src)->fd_count;\
  memcpy((dest)->fd_array, (src)->fd_array, (src)->fd_count * sizeof(int));\
} while (0)

SelectPoll::SelectPoll(void)
  : max_fd_(kNetTypeInval)
  , has_removed_(false)
  , fd_count_(FD_SETSIZE)
  , rset_in_(NULL)
  , wset_in_(NULL)
  , rset_out_(NULL)
  , wset_out_(NULL)
{
}

SelectPoll::~SelectPoll(void)
{
}

bool
SelectPoll::Init(void)
{
  fd_count_ = FD_SETSIZE;
  size_t set_size = sizeof(win_fd_set) + (fd_count_ - 1) * sizeof(int);

  rset_in_ = (win_fd_set*)malloc(set_size);
  if (NULL == rset_in_)
    return false;

  do {
    wset_in_ = (win_fd_set*)malloc(set_size);
    if (NULL == wset_in_)
      break;

    rset_out_ = (win_fd_set*)malloc(set_size);
    if (NULL == rset_out_)
      break;
    wset_out_ = (win_fd_set*)malloc(set_size);
    if (NULL == wset_out_)
      break;

    WINFD_ZERO(rset_in_);
    WINFD_ZERO(wset_in_);

    return true;
  } while (0);

  if (NULL != rset_out_) {
    free(rset_out_);
    rset_out_ = NULL;
  }
  if (NULL != wset_in_) {
    free(wset_in_);
    wset_in_ = NULL;
  }
  if (NULL != rset_in_) {
    free(rset_in_);
    rset_in_ = NULL;
  }

  return false;
}

void
SelectPoll::Destroy(void)
{
  if (NULL != rset_in_) {
    free(rset_in_);
    rset_in_ = NULL;
  }
  if (NULL != wset_in_) {
    free(wset_in_);
    wset_in_ = NULL;
  }

  if (NULL != rset_out_) {
    free(rset_out_);
    rset_out_ = NULL;
  }
  if (NULL != wset_out_) {
    free(wset_out_);
    wset_out_ = NULL;
  }
}

bool
SelectPoll::Regrow(void)
{
  int new_fd_count = (0 != fd_count_ ? 2 * fd_count_ : FD_SETSIZE);
  size_t set_size = sizeof(win_fd_set) + (new_fd_count - 1) * sizeof(int);

  rset_in_ = (win_fd_set*)realloc(rset_in_, set_size);
  if (NULL == rset_in_)
    return false;

  do {
    wset_in_ = (win_fd_set*)realloc(wset_in_, set_size);
    if (NULL == wset_in_)
      break;

    rset_out_ = (win_fd_set*)realloc(rset_out_, set_size);
    if (NULL == rset_out_)
      break;
    wset_out_ = (win_fd_set*)realloc(wset_out_, set_size);
    if (NULL == wset_out_)
      break;

    fd_count_ = new_fd_count;
    return true;
  } while (0);

  return false;
}

bool
SelectPoll::Insert(int fd, Socket* s)
{
  if (entry_list_.size() + 1 > (size_t)fd_count_) {
    if (!Regrow())
      return false;
  }

  SelectEntry entry = {fd, s};
  entry_list_.push_back(entry);

  if (fd > max_fd_)
    max_fd_ = fd;

  return true;
}

void
SelectPoll::Remove(int fd)
{
  std::vector<SelectEntry>::iterator it;
  for (it = entry_list_.begin(); it != entry_list_.end(); ++it) {
    if (fd == it->fd)
      break;
  }

  if (it == entry_list_.end())
    return;
  it->fd = kNetTypeInval;
  has_removed_ = true;

  WINFD_CLR(fd, rset_in_);
  WINFD_CLR(fd, wset_in_);

  WINFD_CLR(fd, rset_out_);
  WINFD_CLR(fd, wset_out_);

  if (fd == max_fd_) {
    max_fd_ = kNetTypeInval;
    for (it = entry_list_.begin(); it != entry_list_.end(); ++it) {
      if (it->fd > max_fd_)
        max_fd_ = it->fd;
    }
  }
}

bool
SelectPoll::AddEvent(int fd, int ev)
{
  if (ev & kEventTypeRead)
    WINFD_SET(fd, rset_in_);

  if (ev & kEventTypeWrite)
    WINFD_SET(fd, wset_in_);

  return true;
}

bool
SelectPoll::DelEvent(int fd, int ev)
{
  if (ev & kEventTypeRead)
    WINFD_CLR(fd, rset_in_);

  if (ev & kEventTypeWrite)
    WINFD_CLR(fd, wset_in_);

  return true;
}

static inline bool
HasSetRemoved(const SelectEntry& entry)
{
  return (kNetTypeInval == entry.fd);
}

bool
SelectPoll::Dispatch(EventDispatcher* dispatcher, int millitm)
{
  if (NULL == dispatcher)
    return false;

  struct timeval tv;
  if (-1 == millitm) {
    tv.tv_sec = 0;
    tv.tv_usec = 500;
  }
  else {
    tv.tv_sec = millitm / 1000;
    tv.tv_usec = (millitm % 1000) * 1000;
  }

  WINFD_COPY(rset_out_, rset_in_);
  WINFD_COPY(wset_out_, wset_in_);

  int ret = select(max_fd_ + 1,
      (struct fd_set*)rset_out_,
      (struct fd_set*)wset_out_, NULL, &tv);
  if (kNetTypeError == ret || 0 == ret)
    return false;

  int size = (int)entry_list_.size();
  SelectEntry* entry;
  for (int i = 0; i < size; ++i) {
    entry = &entry_list_[i];

    if (kNetTypeInval == entry->fd)
      continue;
    if (WINFD_ISSET(entry->fd, rset_out_))
      dispatcher->DispatchReader(entry->s);

    if (kNetTypeInval == entry->fd)
      continue;
    if (WINFD_ISSET(entry->fd, wset_out_))
      dispatcher->DispatchWriter(entry->s);
  }

  if (has_removed_) {
    entry_list_.erase(std::remove_if(entry_list_.begin(),
          entry_list_.end(), HasSetRemoved), entry_list_.end());
    has_removed_ = false;
  }

  return true;
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// 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 "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::DefaultDevice;

static void test_evals()
{
  Tensor<float, 2> input(3, 3);
  Tensor<float, 1> kernel(2);

  input.setRandom();
  kernel.setRandom();

  Tensor<float, 2> result(2,3);
  result.setZero();
  Eigen::array<Tensor<float, 2>::Index, 1> dims3({0});

  typedef TensorEvaluator<decltype(input.convolve(kernel, dims3)), DefaultDevice> Evaluator;
  Evaluator eval(input.convolve(kernel, dims3), DefaultDevice());
  eval.evalTo(result.data());
  EIGEN_STATIC_ASSERT(Evaluator::NumDims==2ul, YOU_MADE_A_PROGRAMMING_MISTAKE);
  VERIFY_IS_EQUAL(eval.dimensions()[0], 2);
  VERIFY_IS_EQUAL(eval.dimensions()[1], 3);

  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0) + input(1,0)*kernel(1));  // index 0
  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0) + input(1,1)*kernel(1));  // index 2
  VERIFY_IS_APPROX(result(0,2), input(0,2)*kernel(0) + input(1,2)*kernel(1));  // index 4
  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0) + input(2,0)*kernel(1));  // index 1
  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0) + input(2,1)*kernel(1));  // index 3
  VERIFY_IS_APPROX(result(1,2), input(1,2)*kernel(0) + input(2,2)*kernel(1));  // index 5
}

static void test_expr()
{
  Tensor<float, 2> input(3, 3);
  Tensor<float, 2> kernel(2, 2);
  input.setRandom();
  kernel.setRandom();

  Tensor<float, 2> result(2,2);
  Eigen::array<ptrdiff_t, 2> dims({0, 1});
  result = input.convolve(kernel, dims);

  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0,0) + input(0,1)*kernel(0,1) +
                                input(1,0)*kernel(1,0) + input(1,1)*kernel(1,1));
  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0,0) + input(0,2)*kernel(0,1) +
                                input(1,1)*kernel(1,0) + input(1,2)*kernel(1,1));
  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0,0) + input(1,1)*kernel(0,1) +
                                input(2,0)*kernel(1,0) + input(2,1)*kernel(1,1));
  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0,0) + input(1,2)*kernel(0,1) +
                                input(2,1)*kernel(1,0) + input(2,2)*kernel(1,1));
}

static void test_modes() {
  Tensor<float, 1> input(3);
  Tensor<float, 1> kernel(3);
  input(0) = 1.0f;
  input(1) = 2.0f;
  input(2) = 3.0f;
  kernel(0) = 0.5f;
  kernel(1) = 1.0f;
  kernel(2) = 0.0f;

  const Eigen::array<ptrdiff_t, 1> dims{{0}};
  Eigen::array<std::pair<ptrdiff_t, ptrdiff_t>, 1> padding;

  // Emulate VALID mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(0, 0);
  Tensor<float, 1> valid(1);
  valid = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(valid.dimension(0), 1);
  VERIFY_IS_APPROX(valid(0), 2.5f);

  // Emulate SAME mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(1, 1);
  Tensor<float, 1> same(3);
  same = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(same.dimension(0), 3);
  VERIFY_IS_APPROX(same(0), 1.0f);
  VERIFY_IS_APPROX(same(1), 2.5f);
  VERIFY_IS_APPROX(same(2), 4.0f);

  // Emulate FULL mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(2, 2);
  Tensor<float, 1> full(5);
  full = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(full.dimension(0), 5);
  VERIFY_IS_APPROX(full(0), 0.0f);
  VERIFY_IS_APPROX(full(1), 1.0f);
  VERIFY_IS_APPROX(full(2), 2.5f);
  VERIFY_IS_APPROX(full(3), 4.0f);
  VERIFY_IS_APPROX(full(4), 1.5f);
}

static void test_strides() {
  Tensor<float, 1> input(13);
  Tensor<float, 1> kernel(3);
  input.setRandom();
  kernel.setRandom();

  const Eigen::array<ptrdiff_t, 1> dims{{0}};
  const Eigen::array<ptrdiff_t, 1> stride_of_3{{3}};
  const Eigen::array<ptrdiff_t, 1> stride_of_2{{2}};

  Tensor<float, 1> result;
  result = input.stride(stride_of_3).convolve(kernel, dims).stride(stride_of_2);

  VERIFY_IS_EQUAL(result.dimension(0), 2);
  VERIFY_IS_APPROX(result(0), (input(0)*kernel(0) + input(3)*kernel(1) +
                               input(6)*kernel(2)));
  VERIFY_IS_APPROX(result(1), (input(6)*kernel(0) + input(9)*kernel(1) +
                               input(12)*kernel(2)));
}

void test_cxx11_tensor_convolution()
{
  CALL_SUBTEST(test_evals());
  CALL_SUBTEST(test_expr());
  CALL_SUBTEST(test_modes());
  CALL_SUBTEST(test_strides());
}
<commit_msg>Fixed clang compilation warning<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// 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 "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::DefaultDevice;

static void test_evals()
{
  Tensor<float, 2> input(3, 3);
  Tensor<float, 1> kernel(2);

  input.setRandom();
  kernel.setRandom();

  Tensor<float, 2> result(2,3);
  result.setZero();
  Eigen::array<Tensor<float, 2>::Index, 1> dims3{{0}};

  typedef TensorEvaluator<decltype(input.convolve(kernel, dims3)), DefaultDevice> Evaluator;
  Evaluator eval(input.convolve(kernel, dims3), DefaultDevice());
  eval.evalTo(result.data());
  EIGEN_STATIC_ASSERT(Evaluator::NumDims==2ul, YOU_MADE_A_PROGRAMMING_MISTAKE);
  VERIFY_IS_EQUAL(eval.dimensions()[0], 2);
  VERIFY_IS_EQUAL(eval.dimensions()[1], 3);

  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0) + input(1,0)*kernel(1));  // index 0
  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0) + input(1,1)*kernel(1));  // index 2
  VERIFY_IS_APPROX(result(0,2), input(0,2)*kernel(0) + input(1,2)*kernel(1));  // index 4
  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0) + input(2,0)*kernel(1));  // index 1
  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0) + input(2,1)*kernel(1));  // index 3
  VERIFY_IS_APPROX(result(1,2), input(1,2)*kernel(0) + input(2,2)*kernel(1));  // index 5
}

static void test_expr()
{
  Tensor<float, 2> input(3, 3);
  Tensor<float, 2> kernel(2, 2);
  input.setRandom();
  kernel.setRandom();

  Tensor<float, 2> result(2,2);
  Eigen::array<ptrdiff_t, 2> dims{{0, 1}};
  result = input.convolve(kernel, dims);

  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0,0) + input(0,1)*kernel(0,1) +
                                input(1,0)*kernel(1,0) + input(1,1)*kernel(1,1));
  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0,0) + input(0,2)*kernel(0,1) +
                                input(1,1)*kernel(1,0) + input(1,2)*kernel(1,1));
  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0,0) + input(1,1)*kernel(0,1) +
                                input(2,0)*kernel(1,0) + input(2,1)*kernel(1,1));
  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0,0) + input(1,2)*kernel(0,1) +
                                input(2,1)*kernel(1,0) + input(2,2)*kernel(1,1));
}

static void test_modes() {
  Tensor<float, 1> input(3);
  Tensor<float, 1> kernel(3);
  input(0) = 1.0f;
  input(1) = 2.0f;
  input(2) = 3.0f;
  kernel(0) = 0.5f;
  kernel(1) = 1.0f;
  kernel(2) = 0.0f;

  const Eigen::array<ptrdiff_t, 1> dims{{0}};
  Eigen::array<std::pair<ptrdiff_t, ptrdiff_t>, 1> padding;

  // Emulate VALID mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(0, 0);
  Tensor<float, 1> valid(1);
  valid = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(valid.dimension(0), 1);
  VERIFY_IS_APPROX(valid(0), 2.5f);

  // Emulate SAME mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(1, 1);
  Tensor<float, 1> same(3);
  same = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(same.dimension(0), 3);
  VERIFY_IS_APPROX(same(0), 1.0f);
  VERIFY_IS_APPROX(same(1), 2.5f);
  VERIFY_IS_APPROX(same(2), 4.0f);

  // Emulate FULL mode (as defined in
  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).
  padding[0] = std::make_pair(2, 2);
  Tensor<float, 1> full(5);
  full = input.pad(padding).convolve(kernel, dims);
  VERIFY_IS_EQUAL(full.dimension(0), 5);
  VERIFY_IS_APPROX(full(0), 0.0f);
  VERIFY_IS_APPROX(full(1), 1.0f);
  VERIFY_IS_APPROX(full(2), 2.5f);
  VERIFY_IS_APPROX(full(3), 4.0f);
  VERIFY_IS_APPROX(full(4), 1.5f);
}

static void test_strides() {
  Tensor<float, 1> input(13);
  Tensor<float, 1> kernel(3);
  input.setRandom();
  kernel.setRandom();

  const Eigen::array<ptrdiff_t, 1> dims{{0}};
  const Eigen::array<ptrdiff_t, 1> stride_of_3{{3}};
  const Eigen::array<ptrdiff_t, 1> stride_of_2{{2}};

  Tensor<float, 1> result;
  result = input.stride(stride_of_3).convolve(kernel, dims).stride(stride_of_2);

  VERIFY_IS_EQUAL(result.dimension(0), 2);
  VERIFY_IS_APPROX(result(0), (input(0)*kernel(0) + input(3)*kernel(1) +
                               input(6)*kernel(2)));
  VERIFY_IS_APPROX(result(1), (input(6)*kernel(0) + input(9)*kernel(1) +
                               input(12)*kernel(2)));
}

void test_cxx11_tensor_convolution()
{
  CALL_SUBTEST(test_evals());
  CALL_SUBTEST(test_expr());
  CALL_SUBTEST(test_modes());
  CALL_SUBTEST(test_strides());
}
<|endoftext|>


<commit_before>#include "com/mapswithme/maps/promo/CityGallery.hpp"

#include "com/mapswithme/maps/Framework.hpp"

#include "partners_api/promo_api.hpp"

#include <utility>

using namespace std::placeholders;

namespace
{
jclass g_galleryClass = nullptr;
jclass g_itemClass = nullptr;
jclass g_authorClass = nullptr;
jclass g_categoryClass = nullptr;
jmethodID g_galleryConstructor = nullptr;
jmethodID g_itemConstructor = nullptr;
jmethodID g_authorConstructor = nullptr;
jmethodID g_categoryConstructor = nullptr;
jclass g_promoClass = nullptr;
jfieldID g_promoInstanceField = nullptr;
jobject g_promoInstance = nullptr;
jmethodID g_onGalleryReceived = nullptr;
jmethodID g_onErrorReceived = nullptr;
uint64_t g_lastRequestId = 0;

void PrepareClassRefs(JNIEnv * env)
{
  if (g_galleryClass != nullptr)
    return;

  g_galleryClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/discovery/PromoCityGallery");
  g_galleryConstructor =
      jni::GetConstructorID(env, g_galleryClass,
                            "([Lcom/mapswithme/maps/discovery/PromoCityGallery$Item;"
                            "Ljava/lang/String;)V");
  g_itemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/discovery/PromoCityGallery$Item");
  g_itemConstructor =
      jni::GetConstructorID(env, g_itemClass,
                            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;"
                            "Ljava/lang/String;Ljava/lang/String;"
                            "Lcom/mapswithme/maps/discovery/PromoCityGallery$Author;"
                            "Lcom/mapswithme/maps/discovery/PromoCityGallery$LuxCategory;)V");
  g_authorClass =
      jni::GetGlobalClassRef(env, "com/mapswithme/maps/discovery/PromoCityGallery$Author");
  g_authorConstructor =
      jni::GetConstructorID(env, g_authorClass, "(Ljava/lang/String;Ljava/lang/String;)V");
  g_categoryClass =
      jni::GetGlobalClassRef(env, "com/mapswithme/maps/discovery/PromoCityGallery$LuxCategory");
  g_categoryConstructor =
      jni::GetConstructorID(env, g_authorClass, "(Ljava/lang/String;Ljava/lang/String;)V");
  g_promoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/Promo");

  g_promoInstanceField =
      jni::GetStaticFieldID(env, g_promoClass, "INSTANCE", "Lcom/mapswithme/maps/promo/Promo;");
  g_promoInstance = env->GetStaticObjectField(g_promoClass, g_promoInstanceField);
  g_onGalleryReceived = jni::GetMethodID(env, g_promoInstance, "onCityGalleryReceived",
                                         "(Lcom/mapswithme/maps/promo/PromoCityGallery;)V");
  g_onErrorReceived = jni::GetMethodID(env, g_promoInstance, "onErrorReceived", "()V");
}

void OnSuccess(uint64_t requestId, promo::CityGallery const & gallery)
{
  if (g_lastRequestId != requestId)
    return;

  JNIEnv * env = jni::GetEnv();
  jni::TScopedLocalRef cityGallery(env, promo::MakeCityGallery(env, gallery));
  env->CallVoidMethod(g_promoInstance, g_onGalleryReceived, cityGallery.get());

  jni::HandleJavaException(env);
}

void OnError(uint64_t requestId)
{
  if (g_lastRequestId != requestId)
    return;

  JNIEnv * env = jni::GetEnv();
  env->CallVoidMethod(g_promoInstance, g_onErrorReceived);

  jni::HandleJavaException(env);
}
}  // namespace

namespace promo
{
jobject MakeCityGallery(JNIEnv * env, promo::CityGallery const & gallery)
{
  PrepareClassRefs(env);

  auto const itemBuilder = [](JNIEnv * env, promo::CityGallery::Item const & item)
  {
    jni::TScopedLocalRef name(env, jni::ToJavaString(env, item.m_name));
    jni::TScopedLocalRef url(env, jni::ToJavaString(env, item.m_url));
    jni::TScopedLocalRef imageUrl(env, jni::ToJavaString(env, item.m_imageUrl));
    jni::TScopedLocalRef access(env, jni::ToJavaString(env, item.m_access));
    jni::TScopedLocalRef tier(env, jni::ToJavaString(env, item.m_tier));
    jni::TScopedLocalRef authorId(env, jni::ToJavaString(env, item.m_author.m_id));
    jni::TScopedLocalRef authorName(env, jni::ToJavaString(env, item.m_author.m_name));
    jni::TScopedLocalRef luxCategoryName(env, jni::ToJavaString(env, item.m_luxCategory.m_name));
    jni::TScopedLocalRef luxCategoryColor(env, jni::ToJavaString(env, item.m_luxCategory.m_color));

    jni::TScopedLocalRef author(
        env, env->NewObject(g_authorClass, g_authorConstructor, authorId.get(), authorName.get()));
    jni::TScopedLocalRef luxCategory(
        env, env->NewObject(g_categoryClass, g_categoryConstructor, luxCategoryName.get(),
                            luxCategoryColor.get()));

    return env->NewObject(g_itemClass, g_itemConstructor, name.get(), url.get(), imageUrl.get(),
                          access.get(), tier.get(), author.get(), luxCategory.get());
  };

  jni::TScopedLocalRef items(env, jni::ToJavaArray(env, g_itemClass, gallery.m_items, itemBuilder));
  jni::TScopedLocalRef moreUrl(env, jni::ToJavaString(env, gallery.m_moreUrl));

  return env->NewObject(g_galleryClass, g_galleryConstructor, items.get(), moreUrl.get());
}
}

extern "C" {
JNIEXPORT void JNICALL
Java_com_mapswithme_maps_promo_Promo_nativeRequestCityGallery(JNIEnv * env, jclass,
                                                              jobject policy, jstring id)
{
  PrepareClassRefs(env);
  ++g_lastRequestId;
  g_framework->GetPromoCityGallery(env, policy, id, std::bind(OnSuccess, g_lastRequestId, _1),
                                   std::bind(OnError, g_lastRequestId));
}
}  // extern "C"
<commit_msg>[promo][jni] crash fix<commit_after>#include "com/mapswithme/maps/promo/CityGallery.hpp"

#include "com/mapswithme/maps/Framework.hpp"

#include "partners_api/promo_api.hpp"

#include <utility>

using namespace std::placeholders;

namespace
{
jclass g_galleryClass = nullptr;
jclass g_itemClass = nullptr;
jclass g_authorClass = nullptr;
jclass g_categoryClass = nullptr;
jmethodID g_galleryConstructor = nullptr;
jmethodID g_itemConstructor = nullptr;
jmethodID g_authorConstructor = nullptr;
jmethodID g_categoryConstructor = nullptr;
jclass g_promoClass = nullptr;
jfieldID g_promoInstanceField = nullptr;
jmethodID g_onGalleryReceived = nullptr;
jmethodID g_onErrorReceived = nullptr;
uint64_t g_lastRequestId = 0;

void PrepareClassRefs(JNIEnv * env)
{
  if (g_galleryClass != nullptr)
    return;

  g_galleryClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/PromoCityGallery");
  g_galleryConstructor =
      jni::GetConstructorID(env, g_galleryClass,
                            "([Lcom/mapswithme/maps/promo/PromoCityGallery$Item;"
                            "Ljava/lang/String;)V");
  g_itemClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/PromoCityGallery$Item");
  g_itemConstructor =
      jni::GetConstructorID(env, g_itemClass,
                            "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;"
                            "Ljava/lang/String;Ljava/lang/String;"
                            "Lcom/mapswithme/maps/promo/PromoCityGallery$Author;"
                            "Lcom/mapswithme/maps/promo/PromoCityGallery$LuxCategory;)V");
  g_authorClass =
      jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/PromoCityGallery$Author");
  g_authorConstructor =
      jni::GetConstructorID(env, g_authorClass, "(Ljava/lang/String;Ljava/lang/String;)V");
  g_categoryClass =
      jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/PromoCityGallery$LuxCategory");
  g_categoryConstructor =
      jni::GetConstructorID(env, g_authorClass, "(Ljava/lang/String;Ljava/lang/String;)V");

  g_promoClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/promo/Promo");
  g_promoInstanceField =
      jni::GetStaticFieldID(env, g_promoClass, "INSTANCE", "Lcom/mapswithme/maps/promo/Promo;");
  jobject promoInstance = env->GetStaticObjectField(g_promoClass, g_promoInstanceField);
  g_onGalleryReceived = jni::GetMethodID(env, promoInstance, "onCityGalleryReceived",
                                         "(Lcom/mapswithme/maps/promo/PromoCityGallery;)V");
  g_onErrorReceived = jni::GetMethodID(env, promoInstance, "onErrorReceived", "()V");
}

void OnSuccess(uint64_t requestId, promo::CityGallery const & gallery)
{
  if (g_lastRequestId != requestId)
    return;

  JNIEnv * env = jni::GetEnv();
  jni::TScopedLocalRef cityGallery(env, promo::MakeCityGallery(env, gallery));
  jobject promoInstance = env->GetStaticObjectField(g_promoClass, g_promoInstanceField);
  env->CallVoidMethod(promoInstance, g_onGalleryReceived, cityGallery.get());

  jni::HandleJavaException(env);
}

void OnError(uint64_t requestId)
{
  if (g_lastRequestId != requestId)
    return;

  JNIEnv * env = jni::GetEnv();
  jobject promoInstance = env->GetStaticObjectField(g_promoClass, g_promoInstanceField);
  env->CallVoidMethod(promoInstance, g_onErrorReceived);

  jni::HandleJavaException(env);
}
}  // namespace

namespace promo
{
jobject MakeCityGallery(JNIEnv * env, promo::CityGallery const & gallery)
{
  PrepareClassRefs(env);

  auto const itemBuilder = [](JNIEnv * env, promo::CityGallery::Item const & item)
  {
    jni::TScopedLocalRef name(env, jni::ToJavaString(env, item.m_name));
    jni::TScopedLocalRef url(env, jni::ToJavaString(env, item.m_url));
    jni::TScopedLocalRef imageUrl(env, jni::ToJavaString(env, item.m_imageUrl));
    jni::TScopedLocalRef access(env, jni::ToJavaString(env, item.m_access));
    jni::TScopedLocalRef tier(env, jni::ToJavaString(env, item.m_tier));
    jni::TScopedLocalRef authorId(env, jni::ToJavaString(env, item.m_author.m_id));
    jni::TScopedLocalRef authorName(env, jni::ToJavaString(env, item.m_author.m_name));
    jni::TScopedLocalRef luxCategoryName(env, jni::ToJavaString(env, item.m_luxCategory.m_name));
    jni::TScopedLocalRef luxCategoryColor(env, jni::ToJavaString(env, item.m_luxCategory.m_color));

    jni::TScopedLocalRef author(
        env, env->NewObject(g_authorClass, g_authorConstructor, authorId.get(), authorName.get()));
    jni::TScopedLocalRef luxCategory(
        env, env->NewObject(g_categoryClass, g_categoryConstructor, luxCategoryName.get(),
                            luxCategoryColor.get()));

    return env->NewObject(g_itemClass, g_itemConstructor, name.get(), url.get(), imageUrl.get(),
                          access.get(), tier.get(), author.get(), luxCategory.get());
  };

  jni::TScopedLocalObjectArrayRef items(env, jni::ToJavaArray(env, g_itemClass, gallery.m_items,
                                        itemBuilder));
  jni::TScopedLocalRef moreUrl(env, jni::ToJavaString(env, gallery.m_moreUrl));

  return env->NewObject(g_galleryClass, g_galleryConstructor, items.get(), moreUrl.get());
}
}

extern "C" {
JNIEXPORT void JNICALL
Java_com_mapswithme_maps_promo_Promo_nativeRequestCityGallery(JNIEnv * env, jclass,
                                                              jobject policy, jstring id)
{
  PrepareClassRefs(env);
  ++g_lastRequestId;
  g_framework->GetPromoCityGallery(env, policy, id, std::bind(OnSuccess, g_lastRequestId, _1),
                                   std::bind(OnError, g_lastRequestId));
}
}  // extern "C"
<|endoftext|>


<commit_before>#include "depthviewwindow.h"
#include "ui_depthviewwindow.h"
#include <QKeyEvent>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <settingswindow.h>

DepthViewWindow::DepthViewWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::DepthViewWindow){
    ui->setupUi(this);
    fileFilters << "*.jps" << "*.pns";
    ui->imageWidget->addActions(ui->menubar->actions());
    ui->imageWidget->setContextMenuPolicy(Qt::ActionsContextMenu);

    this->loadSettings();
}

DepthViewWindow::~DepthViewWindow(){
    settings.setValue("lastrun", QDate::currentDate().toString());
    delete ui;
}

bool DepthViewWindow::loadImage(QString filename){
    QFileInfo info(filename);
    if(info.exists() && (info.suffix() == "jps" || info.suffix() == "pns")){
        QDir::setCurrent(info.path());
        currentFile = info.fileName();
        ui->imageWidget->loadStereoImage(currentFile);
        this->setWindowTitle(currentFile);
        ui->imageWidget->repaint();
        return true;
    }
    else{
        return false;
    }
}
bool DepthViewWindow::showLoadImageDialog(){
    QString filename = QFileDialog::getOpenFileName(this,tr("Open Image"), "", tr("Stereo Image Files (*.jps *.pns)"));
    return loadImage(filename);
}

void DepthViewWindow::on_actionAbout_Qt_triggered(){
    QMessageBox::aboutQt(this);
}

void DepthViewWindow::on_actionExit_triggered(){
    this->close();
}

void DepthViewWindow::on_actionOpen_triggered(){
    this->showLoadImageDialog();
}

void DepthViewWindow::on_actionFull_Color_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 1;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionHalf_Color_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 0.5;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionGreyscale_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 0;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionShow_MenuBar_toggled(bool val){
    ui->menubar->setVisible(val);
}

void DepthViewWindow::on_actionFullscreen_toggled(bool val){
    if(val){
        setWindowState(windowState() | Qt::WindowFullScreen);
        ui->actionShow_MenuBar->setChecked(false);
    }
    else{
        setWindowState(windowState() & ~Qt::WindowFullScreen);
        ui->actionShow_MenuBar->setChecked(true);
    }
}

void DepthViewWindow::on_actionNext_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    int index = entryList.indexOf(currentFile)+1;
    if(index < 0){
        index = entryList.count()-1;
    }
    else if(index >= entryList.count()){
        index = 0;
    }
    loadImage(entryList[index]);
    return;
}

void DepthViewWindow::on_actionPrevious_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    int index = entryList.indexOf(currentFile)-1;
    if(index < 0){
        index = entryList.count()-1;
    }
    else if(index >= entryList.count()){
        index = 0;
    }
    loadImage(entryList[index]);
    return;
}

void DepthViewWindow::mousePressEvent(QMouseEvent *e){
    if(e->buttons() == Qt::XButton2)
        this->on_actionNext_triggered();
    if(e->buttons() == Qt::XButton1)
        this->on_actionPrevious_triggered();
}
void DepthViewWindow::mouseDoubleClickEvent(QMouseEvent *e){
    if(e->button() == Qt::LeftButton)
        ui->actionFullscreen->toggle();
}

void DepthViewWindow::on_actionSave_As_triggered(){
    QString filename = QFileDialog::getSaveFileName(this,tr("Save Image"), "", tr("Stereo Image Files (*.jps *.pns);;Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)"));
    QImage out;
    if(filename.contains(".jps") || filename.contains(".pns")){
        SideBySideRender renderer;
        bool tempmirrorL = SideBySideRender::mirrorL;
        bool tempmirrorR = SideBySideRender::mirrorR;
        SideBySideRender::mirrorL = false;
        SideBySideRender::mirrorR = false;
        out = renderer.draw(ui->imageWidget->imgL,ui->imageWidget->imgR,0,0);
        SideBySideRender::mirrorL = tempmirrorL;
        SideBySideRender::mirrorR = tempmirrorR;
        if(filename.contains(".jps")){
            if(!out.isNull()){
                out.save(filename, "JPG");
            }
        }
        if(filename.contains(".pns")){
            if(!out.isNull()){
                out.save(filename, "PNG");
            }
        }
    }
    else{
        out = ui->imageWidget->renderer->draw(ui->imageWidget->imgL,ui->imageWidget->imgR,0,0);
        if(!out.isNull()){
            out.save(filename);
        }
    }
}

void DepthViewWindow::on_actionNo_Mirror_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = false;
    SideBySideRender::mirrorR = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Left_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = true;
    SideBySideRender::mirrorR = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Right_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = false;
    SideBySideRender::mirrorR = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Both_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = true;
    SideBySideRender::mirrorR = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionFit_triggered(){
    ui->imageWidget->setZoom(0);
}

void DepthViewWindow::on_actionzoom100_triggered(){
    ui->imageWidget->setZoom(1);
}

void DepthViewWindow::on_actionzoom50_triggered(){
    ui->imageWidget->setZoom(0.5);
}

void DepthViewWindow::on_actionzoom200_triggered(){
    ui->imageWidget->setZoom(2);
}

void DepthViewWindow::on_actionHorizontal_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new InterlacedRender(this);
    InterlacedRender::horizontal = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionVertical_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new InterlacedRender(this);
    InterlacedRender::horizontal = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionOptions_triggered(){
    SettingsWindow settingsdialog(&settings, this);
    if(settingsdialog.exec() == QDialog::Accepted){
        this->loadSettings();
    }
}

void DepthViewWindow::on_actionAbout_triggered(){
    QMessageBox::about(this, "About DepthView",
                       ""
                       "
DepthView " + version::getVersionString() + " r" + version::svn_revision + "
"
                       "
DepthView is a basic application for viewing stereo 3D image files.
"
                       "
DepthView website: sourceforge.net/projects/depthview/
"
                       "
Please report any bugs at: sourceforge.net/p/depthview/discussion/
");
}

void DepthViewWindow::loadSettings(){
    if(settings.contains("defaultrender")){
        QString renderer = settings.value("defaultrender").toString();
        if(renderer == "Anglaph, Full Color"){
            this->on_actionFull_Color_triggered();
        }
        else if(renderer == "Anglaph, Half Color"){
            this->on_actionHalf_Color_triggered();
        }
        else if(renderer == "Anglaph, Greyscale"){
            this->on_actionGreyscale_triggered();
        }
        else if(renderer == "Side by Side, No Mirror"){
            this->on_actionNo_Mirror_triggered();
        }
        else if(renderer == "Side by Side, Mirror Left"){
            this->on_actionMirror_Left_triggered();
        }
        else if(renderer == "Side by Side, Mirror Right"){
            this->on_actionMirror_Right_triggered();
        }
        else if(renderer == "Side by Side, Mirror Both"){
            this->on_actionMirror_Both_triggered();
        }
        else if(renderer == "Interlaced, Horizontal"){
            this->on_actionHorizontal_triggered();
        }
        else if(renderer == "Interlaced, Vertical"){
            this->on_actionVertical_triggered();
        }
        else if(renderer == "Checkerboard"){
            this->on_actionCheckerboard_triggered();
        }
        else if(renderer == "Mono, Left"){
            this->on_actionLeft_Image_triggered();
        }
        else if(renderer == "Mono, Right"){
            this->on_actionRight_Image_triggered();
        }
        else{
            this->on_actionFull_Color_triggered();
        }
    }
    if(settings.contains("startfullscreen")){
        ui->actionFullscreen->setChecked(settings.value("startfullscreen").toBool());
    }
    else{
        ui->actionFullscreen->setChecked(false);
    }
    if(settings.contains("smoothzoom")){
        ui->actionSmooth_Zoom->setChecked(settings.value("smoothzoom").toBool());
    }
    else{
        ui->actionSmooth_Zoom->setChecked(false);
    }
    if(settings.contains("startupdirectory")){
        if(currentFile == ""){
            QDir::setCurrent(settings.value("startupdirectory").toString());
        }
    }
}

void DepthViewWindow::on_actionCheckerboard_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new CheckerBoardRender(this);
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionLeft_Image_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SingleRender();
    SingleRender::left = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionRight_Image_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SingleRender();
    SingleRender::left = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionFirst_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    loadImage(entryList[0]);
}

void DepthViewWindow::on_actionLast_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    loadImage(entryList[entryList.count()-1]);
}

void DepthViewWindow::on_actionZoomIn_triggered(){
    ui->imageWidget->zoomIn();
}

void DepthViewWindow::on_actionZoomOut_triggered(){
    ui->imageWidget->zoomOut();
}

void DepthViewWindow::on_actionSmooth_Zoom_toggled(bool val){
    if(val){
        StereoRender::scaleMode = Qt::SmoothTransformation;
    }
    else{
        StereoRender::scaleMode = Qt::FastTransformation;
    }
}
<commit_msg>Fix case sensitivity for file extensions.<commit_after>#include "depthviewwindow.h"
#include "ui_depthviewwindow.h"
#include <QKeyEvent>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <settingswindow.h>

DepthViewWindow::DepthViewWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::DepthViewWindow){
    ui->setupUi(this);
    fileFilters << "*.jps" << "*.pns";
    ui->imageWidget->addActions(ui->menubar->actions());
    ui->imageWidget->setContextMenuPolicy(Qt::ActionsContextMenu);

    this->loadSettings();
}

DepthViewWindow::~DepthViewWindow(){
    settings.setValue("lastrun", QDate::currentDate().toString());
    delete ui;
}

bool DepthViewWindow::loadImage(QString filename){
    QFileInfo info(filename);
    if(info.exists() && (info.suffix().toLower() == "jps" || info.suffix().toLower() == "pns")){
        QDir::setCurrent(info.path());
        currentFile = info.fileName();
        ui->imageWidget->loadStereoImage(currentFile);
        this->setWindowTitle(currentFile);
        ui->imageWidget->repaint();
        return true;
    }
    else{
        return false;
    }
}
bool DepthViewWindow::showLoadImageDialog(){
    QString filename = QFileDialog::getOpenFileName(this,tr("Open Image"), "", tr("Stereo Image Files (*.jps *.pns)"));
    return loadImage(filename);
}

void DepthViewWindow::on_actionAbout_Qt_triggered(){
    QMessageBox::aboutQt(this);
}

void DepthViewWindow::on_actionExit_triggered(){
    this->close();
}

void DepthViewWindow::on_actionOpen_triggered(){
    this->showLoadImageDialog();
}

void DepthViewWindow::on_actionFull_Color_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 1;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionHalf_Color_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 0.5;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionGreyscale_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new StereoRender();
    StereoRender::colormult = 0;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionShow_MenuBar_toggled(bool val){
    ui->menubar->setVisible(val);
}

void DepthViewWindow::on_actionFullscreen_toggled(bool val){
    if(val){
        setWindowState(windowState() | Qt::WindowFullScreen);
        ui->actionShow_MenuBar->setChecked(false);
    }
    else{
        setWindowState(windowState() & ~Qt::WindowFullScreen);
        ui->actionShow_MenuBar->setChecked(true);
    }
}

void DepthViewWindow::on_actionNext_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    int index = entryList.indexOf(currentFile)+1;
    if(index < 0){
        index = entryList.count()-1;
    }
    else if(index >= entryList.count()){
        index = 0;
    }
    loadImage(entryList[index]);
    return;
}

void DepthViewWindow::on_actionPrevious_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    int index = entryList.indexOf(currentFile)-1;
    if(index < 0){
        index = entryList.count()-1;
    }
    else if(index >= entryList.count()){
        index = 0;
    }
    loadImage(entryList[index]);
    return;
}

void DepthViewWindow::mousePressEvent(QMouseEvent *e){
    if(e->buttons() == Qt::XButton2)
        this->on_actionNext_triggered();
    if(e->buttons() == Qt::XButton1)
        this->on_actionPrevious_triggered();
}
void DepthViewWindow::mouseDoubleClickEvent(QMouseEvent *e){
    if(e->button() == Qt::LeftButton)
        ui->actionFullscreen->toggle();
}

void DepthViewWindow::on_actionSave_As_triggered(){
    QString filename = QFileDialog::getSaveFileName(this,tr("Save Image"), "", tr("Stereo Image Files (*.jps *.pns);;Image Files (*.bmp *.jpg *.jpeg *.png *.ppm *.tiff *.xbm *.xpm)"));
    QImage out;
    if(filename.contains(".jps", Qt::CaseInsensitive) || filename.contains(".pns", Qt::CaseInsensitive)){
        SideBySideRender renderer;
        bool tempmirrorL = SideBySideRender::mirrorL;
        bool tempmirrorR = SideBySideRender::mirrorR;
        SideBySideRender::mirrorL = false;
        SideBySideRender::mirrorR = false;
        out = renderer.draw(ui->imageWidget->imgL,ui->imageWidget->imgR,0,0);
        SideBySideRender::mirrorL = tempmirrorL;
        SideBySideRender::mirrorR = tempmirrorR;
        if(filename.contains(".jps", Qt::CaseInsensitive)){
            if(!out.isNull()){
                out.save(filename, "JPG");
            }
        }
        if(filename.contains(".pns", Qt::CaseInsensitive)){
            if(!out.isNull()){
                out.save(filename, "PNG");
            }
        }
    }
    else{
        out = ui->imageWidget->renderer->draw(ui->imageWidget->imgL,ui->imageWidget->imgR,0,0);
        if(!out.isNull()){
            out.save(filename);
        }
    }
}

void DepthViewWindow::on_actionNo_Mirror_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = false;
    SideBySideRender::mirrorR = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Left_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = true;
    SideBySideRender::mirrorR = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Right_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = false;
    SideBySideRender::mirrorR = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionMirror_Both_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SideBySideRender();
    SideBySideRender::mirrorL = true;
    SideBySideRender::mirrorR = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionFit_triggered(){
    ui->imageWidget->setZoom(0);
}

void DepthViewWindow::on_actionzoom100_triggered(){
    ui->imageWidget->setZoom(1);
}

void DepthViewWindow::on_actionzoom50_triggered(){
    ui->imageWidget->setZoom(0.5);
}

void DepthViewWindow::on_actionzoom200_triggered(){
    ui->imageWidget->setZoom(2);
}

void DepthViewWindow::on_actionHorizontal_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new InterlacedRender(this);
    InterlacedRender::horizontal = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionVertical_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new InterlacedRender(this);
    InterlacedRender::horizontal = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionOptions_triggered(){
    SettingsWindow settingsdialog(&settings, this);
    if(settingsdialog.exec() == QDialog::Accepted){
        this->loadSettings();
    }
}

void DepthViewWindow::on_actionAbout_triggered(){
    QMessageBox::about(this, "About DepthView",
                       ""
                       "
DepthView " + version::getVersionString() + " r" + version::svn_revision + "
"
                       "
DepthView is a basic application for viewing stereo 3D image files.
"
                       "
DepthView website: sourceforge.net/projects/depthview/
"
                       "
Please report any bugs at: sourceforge.net/p/depthview/discussion/
");
}

void DepthViewWindow::loadSettings(){
    if(settings.contains("defaultrender")){
        QString renderer = settings.value("defaultrender").toString();
        if(renderer == "Anglaph, Full Color"){
            this->on_actionFull_Color_triggered();
        }
        else if(renderer == "Anglaph, Half Color"){
            this->on_actionHalf_Color_triggered();
        }
        else if(renderer == "Anglaph, Greyscale"){
            this->on_actionGreyscale_triggered();
        }
        else if(renderer == "Side by Side, No Mirror"){
            this->on_actionNo_Mirror_triggered();
        }
        else if(renderer == "Side by Side, Mirror Left"){
            this->on_actionMirror_Left_triggered();
        }
        else if(renderer == "Side by Side, Mirror Right"){
            this->on_actionMirror_Right_triggered();
        }
        else if(renderer == "Side by Side, Mirror Both"){
            this->on_actionMirror_Both_triggered();
        }
        else if(renderer == "Interlaced, Horizontal"){
            this->on_actionHorizontal_triggered();
        }
        else if(renderer == "Interlaced, Vertical"){
            this->on_actionVertical_triggered();
        }
        else if(renderer == "Checkerboard"){
            this->on_actionCheckerboard_triggered();
        }
        else if(renderer == "Mono, Left"){
            this->on_actionLeft_Image_triggered();
        }
        else if(renderer == "Mono, Right"){
            this->on_actionRight_Image_triggered();
        }
        else{
            this->on_actionFull_Color_triggered();
        }
    }
    if(settings.contains("startfullscreen")){
        ui->actionFullscreen->setChecked(settings.value("startfullscreen").toBool());
    }
    else{
        ui->actionFullscreen->setChecked(false);
    }
    if(settings.contains("smoothzoom")){
        ui->actionSmooth_Zoom->setChecked(settings.value("smoothzoom").toBool());
    }
    else{
        ui->actionSmooth_Zoom->setChecked(false);
    }
    if(settings.contains("startupdirectory")){
        if(currentFile == ""){
            QDir::setCurrent(settings.value("startupdirectory").toString());
        }
    }
}

void DepthViewWindow::on_actionCheckerboard_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new CheckerBoardRender(this);
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionLeft_Image_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SingleRender();
    SingleRender::left = true;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionRight_Image_triggered(){
    delete ui->imageWidget->renderer;
    ui->imageWidget->renderer = new SingleRender();
    SingleRender::left = false;
    ui->imageWidget->repaint();
}

void DepthViewWindow::on_actionFirst_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    loadImage(entryList[0]);
}

void DepthViewWindow::on_actionLast_triggered(){
    QStringList entryList = QDir::current().entryList(fileFilters);
    loadImage(entryList[entryList.count()-1]);
}

void DepthViewWindow::on_actionZoomIn_triggered(){
    ui->imageWidget->zoomIn();
}

void DepthViewWindow::on_actionZoomOut_triggered(){
    ui->imageWidget->zoomOut();
}

void DepthViewWindow::on_actionSmooth_Zoom_toggled(bool val){
    if(val){
        StereoRender::scaleMode = Qt::SmoothTransformation;
    }
    else{
        StereoRender::scaleMode = Qt::FastTransformation;
    }
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//      Greenplum Database
//      Copyright (C) 2014 VMware, Inc. or its affiliates.
//
//      @filename:
//              CUpperBoundNDVs.cpp
//
//      @doc:
//              Implementation of upper bound on the number of distinct values for a
//              given set of columns
//---------------------------------------------------------------------------

#include "naucrates/statistics/CUpperBoundNDVs.h"

#include "gpopt/base/CColRefSet.h"
#include "gpopt/base/CColRefSetIter.h"

using namespace gpnaucrates;
using namespace gpopt;

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVWithRemap
//
//      @doc:
//              Copy upper bound ndvs with remapped column id; function will
//              return null if there is no mapping found for any of the columns
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVWithRemap(
	CMemoryPool *mp, UlongToColRefMap *colid_to_colref_map) const
{
	BOOL mapping_not_found = false;

	CColRefSet *column_refset_copy = GPOS_NEW(mp) CColRefSet(mp);
	CColRefSetIter column_refset_iter(*m_column_refset);
	while (column_refset_iter.Advance() && !mapping_not_found)
	{
		ULONG colid = column_refset_iter.Pcr()->Id();
		CColRef *column_ref = colid_to_colref_map->Find(&colid);
		if (nullptr != column_ref)
		{
			column_refset_copy->Include(column_ref);
		}
		else
		{
			mapping_not_found = true;
		}
	}

	if (0 < column_refset_copy->Size() && !mapping_not_found)
	{
		return GPOS_NEW(mp)
			CUpperBoundNDVs(column_refset_copy, UpperBoundNDVs());
	}

	column_refset_copy->Release();

	return nullptr;
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVs
//
//      @doc:
//              Copy upper bound ndvs
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVs(CMemoryPool *mp,
									CDouble upper_bound_ndv) const
{
	m_column_refset->AddRef();
	CUpperBoundNDVs *ndv_copy =
		GPOS_NEW(mp) CUpperBoundNDVs(m_column_refset, upper_bound_ndv);

	return ndv_copy;
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVs
//
//      @doc:
//              Copy upper bound ndvs
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVs(CMemoryPool *mp) const
{
	return CopyUpperBoundNDVs(mp, m_upper_bound_ndv);
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::OsPrint
//
//      @doc:
//              Print function
//
//---------------------------------------------------------------------------
IOstream &
CUpperBoundNDVs::OsPrint(IOstream &os) const
{
	os << "{" << std::endl;
	m_column_refset->OsPrint(os);
	os << " Upper Bound of NDVs" << UpperBoundNDVs() << std::endl;
	os << "}" << std::endl;

	return os;
}

// EOF
<commit_msg>Typo fix in logging message of UpperBoundNDVs module<commit_after>//---------------------------------------------------------------------------
//      Greenplum Database
//      Copyright (C) 2014 VMware, Inc. or its affiliates.
//
//      @filename:
//              CUpperBoundNDVs.cpp
//
//      @doc:
//              Implementation of upper bound on the number of distinct values for a
//              given set of columns
//---------------------------------------------------------------------------

#include "naucrates/statistics/CUpperBoundNDVs.h"

#include "gpopt/base/CColRefSet.h"
#include "gpopt/base/CColRefSetIter.h"

using namespace gpnaucrates;
using namespace gpopt;

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVWithRemap
//
//      @doc:
//              Copy upper bound ndvs with remapped column id; function will
//              return null if there is no mapping found for any of the columns
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVWithRemap(
	CMemoryPool *mp, UlongToColRefMap *colid_to_colref_map) const
{
	BOOL mapping_not_found = false;

	CColRefSet *column_refset_copy = GPOS_NEW(mp) CColRefSet(mp);
	CColRefSetIter column_refset_iter(*m_column_refset);
	while (column_refset_iter.Advance() && !mapping_not_found)
	{
		ULONG colid = column_refset_iter.Pcr()->Id();
		CColRef *column_ref = colid_to_colref_map->Find(&colid);
		if (nullptr != column_ref)
		{
			column_refset_copy->Include(column_ref);
		}
		else
		{
			mapping_not_found = true;
		}
	}

	if (0 < column_refset_copy->Size() && !mapping_not_found)
	{
		return GPOS_NEW(mp)
			CUpperBoundNDVs(column_refset_copy, UpperBoundNDVs());
	}

	column_refset_copy->Release();

	return nullptr;
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVs
//
//      @doc:
//              Copy upper bound ndvs
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVs(CMemoryPool *mp,
									CDouble upper_bound_ndv) const
{
	m_column_refset->AddRef();
	CUpperBoundNDVs *ndv_copy =
		GPOS_NEW(mp) CUpperBoundNDVs(m_column_refset, upper_bound_ndv);

	return ndv_copy;
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::CopyUpperBoundNDVs
//
//      @doc:
//              Copy upper bound ndvs
//
//---------------------------------------------------------------------------
CUpperBoundNDVs *
CUpperBoundNDVs::CopyUpperBoundNDVs(CMemoryPool *mp) const
{
	return CopyUpperBoundNDVs(mp, m_upper_bound_ndv);
}

//---------------------------------------------------------------------------
//      @function:
//              CUpperBoundNDVs::OsPrint
//
//      @doc:
//              Print function
//
//---------------------------------------------------------------------------
IOstream &
CUpperBoundNDVs::OsPrint(IOstream &os) const
{
	os << "{" << std::endl;
	m_column_refset->OsPrint(os);
	os << " Upper Bound of NDVs " << UpperBoundNDVs() << std::endl;
	os << "}" << std::endl;

	return os;
}

// EOF
<|endoftext|>