text:
/*
 * MsgConn.cpp
 *
 *  Created on: 2013-7-5
 *      Author: ziteng@mogujie.com
 */

#include "MsgConn.h"
#include "DBServConn.h"
#include "LoginServConn.h"
#include "RouteServConn.h"
#include "FileHandler.h"
#include "GroupChat.h"
#include "ImUser.h"
#include "AttachData.h"
#include "IM.Buddy.pb.h"
#include "IM.Message.pb.h"
#include "IM.Login.pb.h"
#include "IM.Other.pb.h"
#include "IM.Group.pb.h"
#include "IM.Server.pb.h"
#include "IM.SwitchService.pb.h"
#include "public_define.h"
#include "ImPduBase.h"
using namespace IM::BaseDefine;

#define TIMEOUT_WATI_LOGIN_RESPONSE		15000	// 15 seconds
#define TIMEOUT_WAITING_MSG_DATA_ACK	15000	// 15 seconds
#define LOG_MSG_STAT_INTERVAL			300000	// log message miss status in every 5 minutes;
#define MAX_MSG_CNT_PER_SECOND			20	// user can not send more than 20 msg in one second
static ConnMap_t g_msg_conn_map;
static UserMap_t g_msg_conn_user_map;

static uint64_t	g_last_stat_tick;	// 上次显示丢包率信息的时间
static uint32_t g_up_msg_total_cnt = 0;		// 上行消息包总数
static uint32_t g_up_msg_miss_cnt = 0;		// 上行消息包丢数
static uint32_t g_down_msg_total_cnt = 0;	// 下行消息包总数
static uint32_t g_down_msg_miss_cnt = 0;	// 下行消息丢包数

static bool g_log_msg_toggle = true;	// 是否把收到的MsgData写入Log的开关,通过kill -SIGUSR2 pid 打开/关闭

static CFileHandler* s_file_handler = NULL;
static CGroupChat* s_group_chat = NULL;

void msg_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam)
{
	ConnMap_t::iterator it_old;
	CMsgConn* pConn = NULL;
	uint64_t cur_time = get_tick_count();

	for (ConnMap_t::iterator it = g_msg_conn_map.begin(); it != g_msg_conn_map.end(); ) {
		it_old = it;
		it++;

		pConn = (CMsgConn*)it_old->second;
		pConn->OnTimer(cur_time);
	}

	if (cur_time > g_last_stat_tick + LOG_MSG_STAT_INTERVAL) {
		g_last_stat_tick = cur_time;
		log("up_msg_cnt=%u, up_msg_miss_cnt=%u, down_msg_cnt=%u, down_msg_miss_cnt=%u ",
			g_up_msg_total_cnt, g_up_msg_miss_cnt, g_down_msg_total_cnt, g_down_msg_miss_cnt);
	}
}

static void signal_handler_usr1(int sig_no)
{
	if (sig_no == SIGUSR1) {
		log("receive SIGUSR1 ");
		g_up_msg_total_cnt = 0;
		g_up_msg_miss_cnt = 0;
		g_down_msg_total_cnt = 0;
		g_down_msg_miss_cnt = 0;
	}
}

static void signal_handler_usr2(int sig_no)
{
	if (sig_no == SIGUSR2) {
		log("receive SIGUSR2 ");
		g_log_msg_toggle = !g_log_msg_toggle;
	}
}

static void signal_handler_hup(int sig_no)
{
	if (sig_no == SIGHUP) {
		log("receive SIGHUP exit... ");
		exit(0);
	}
}

void init_msg_conn()
{
	g_last_stat_tick = get_tick_count();
	signal(SIGUSR1, signal_handler_usr1);
	signal(SIGUSR2, signal_handler_usr2);
	signal(SIGHUP, signal_handler_hup);
	netlib_register_timer(msg_conn_timer_callback, NULL, 1000);
	s_file_handler = CFileHandler::getInstance();
	s_group_chat = CGroupChat::GetInstance();
}

////////////////////////////
CMsgConn::CMsgConn()
{
    m_user_id = 0;
    m_bOpen = false;
    m_bKickOff = false;
    m_last_seq_no = 0;
    m_msg_cnt_per_sec = 0;
    m_send_msg_list.clear();
    m_online_status = IM::BaseDefine::USER_STATUS_OFFLINE;
}

CMsgConn::~CMsgConn()
{

}

void CMsgConn::SendUserStatusUpdate(uint32_t user_status)
{
    if (!m_bOpen) {
		return;
	}

    CImUser* pImUser = CImUserManager::GetInstance()->GetImUserById(GetUserId());
    if (!pImUser) {
        return;
    }

    // 只有上下线通知才通知LoginServer
    if (user_status == ::IM::BaseDefine::USER_STATUS_ONLINE) {
        IM::Server::IMUserCntUpdate msg;
        msg.set_user_action(USER_CNT_INC);
        msg.set_user_id(pImUser->GetUserId());
        CImPdu pdu;
        pdu.SetPBMsg(&msg);
        pdu.SetServiceId(SID_OTHER);
        pdu.SetCommandId(CID_OTHER_USER_CNT_UPDATE);
        send_to_all_login_server(&pdu);

        IM::Server::IMUserStatusUpdate msg2;
        msg2.set_user_status(::IM::BaseDefine::USER_STATUS_ONLINE);
        msg2.set_user_id(pImUser->GetUserId());
        msg2.set_client_type((::IM::BaseDefine::ClientType)m_client_type);
        CImPdu pdu2;
        pdu2.SetPBMsg(&msg2);
        pdu2.SetServiceId(SID_OTHER);
        pdu2.SetCommandId(CID_OTHER_USER_STATUS_UPDATE);

        send_to_all_route_server(&pdu2);
    } else if (user_status == ::IM::BaseDefine::USER_STATUS_OFFLINE) {
        IM::Server::IMUserCntUpdate msg;
        msg.set_user_action(USER_CNT_DEC);
        msg.set_user_id(pImUser->GetUserId());
        CImPdu pdu;
        pdu.SetPBMsg(&msg);
        pdu.SetServiceId(SID_OTHER);
        pdu.SetCommandId(CID_OTHER_USER_CNT_UPDATE);
        send_to_all_login_server(&pdu);

        IM::Server::IMUserStatusUpdate msg2;
        msg2.set_user_status(::IM::BaseDefine::USER_STATUS_OFFLINE);
        msg2.set_user_id(pImUser->GetUserId());
        msg2.set_client_type((::IM::BaseDefine::ClientType)m_client_type);
        CImPdu pdu2;
        pdu2.SetPBMsg(&msg2);
        pdu2.SetServiceId(SID_OTHER);
        pdu2.SetCommandId(CID_OTHER_USER_STATUS_UPDATE);
        send_to_all_route_server(&pdu2);
    }
}

void CMsgConn::Close(bool kick_user)
{
    log("Close client, handle=%d, user_id=%u ", m_handle, GetUserId());
    if (m_handle != NETLIB_INVALID_HANDLE) {
        netlib_close(m_handle);
        g_msg_conn_map.erase(m_handle);
    }

    CImUser *pImUser = CImUserManager::GetInstance()->GetImUserById(GetUserId());
    if (pImUser) {
        pImUser->DelMsgConn(GetHandle());
        pImUser->DelUnValidateMsgConn(this);

        SendUserStatusUpdate(::IM::BaseDefine::USER_STATUS_OFFLINE);
        if (pImUser->IsMsgConnEmpty()) {
            CImUserManager::GetInstance()->RemoveImUser(pImUser);
        }
    }

    pImUser = CImUserManager::GetInstance()->GetImUserByLoginName(GetLoginName());
    if (pImUser) {
        pImUser->DelUnValidateMsgConn(this);
        if (pImUser->IsMsgConnEmpty()) {
            CImUserManager::GetInstance()->RemoveImUser(pImUser);
        }
    }

    ReleaseRef();
}

void CMsgConn::OnConnect(net_handle_t handle)
{
	m_handle = handle;
	m_login_time = get_tick_count();

	g_msg_conn_map.insert(make_pair(handle, this));

	netlib_option(handle, NETLIB_OPT_SET_CALLBACK, (void*)imconn_callback);
	netlib_option(handle, NETLIB_OPT_SET_CALLBACK_DATA, (void*)&g_msg_conn_map);
	netlib_option(handle, NETLIB_OPT_GET_REMOTE_IP, (void*)&m_peer_ip);
	netlib_option(handle, NETLIB_OPT_GET_REMOTE_PORT, (void*)&m_peer_port);
}

void CMsgConn::OnClose()
{
    log("Warning: peer closed. ");
	Close();
}

void CMsgConn::OnTimer(uint64_t curr_tick)
{
	m_msg_cnt_per_sec = 0;

    if (CHECK_CLIENT_TYPE_MOBILE(GetClientType()))
    {
        if (curr_tick > m_last_recv_tick + MOBILE_CLIENT_TIMEOUT) {
            log("mobile client timeout, handle=%d, uid=%u ", m_handle, GetUserId());
            Close();
            return;
        }
    }
    else
    {
        if (curr_tick > m_last_recv_tick + CLIENT_TIMEOUT) {
            log("client timeout, handle=%d, uid=%u ", m_handle, GetUserId());
            Close();
            return;
        }
    }

	if (!IsOpen()) {
		if (curr_tick > m_login_time + TIMEOUT_WATI_LOGIN_RESPONSE) {
			log("login timeout, handle=%d, uid=%u ", m_handle, GetUserId());
			Close();
			return;
		}
	}

	list<msg_ack_t>::iterator it_old;
	for (list<msg_ack_t>::iterator it = m_send_msg_list.begin(); it != m_send_msg_list.end(); ) {
		msg_ack_t msg = *it;
		it_old = it;
		it++;
		if (curr_tick >= msg.timestamp + TIMEOUT_WAITING_MSG_DATA_ACK) {
			log("!!!a msg missed, msg_id=%u, %u->%u ", msg.msg_id, msg.from_id, GetUserId());
			g_down_msg_miss_cnt++;
			m_send_msg_list.erase(it_old);
		} else {
			break;
		}
	}
}

void CMsgConn::HandlePdu(CImPdu* pPdu)
{
	// request authorization check
	if (pPdu->GetCommandId() != CID_LOGIN_REQ_USERLOGIN && !IsOpen() && IsKickOff()) {
        log("HandlePdu, wrong msg. ");
        throw CPduException(pPdu->GetServiceId(), pPdu->GetCommandId(), ERROR_CODE_WRONG_SERVICE_ID, "HandlePdu error, user not login. ");
		return;
    }
	switch (pPdu->GetCommandId()) {
        case CID_OTHER_HEARTBEAT:
            _HandleHeartBeat(pPdu);
            break;
        case CID_LOGIN_REQ_USERLOGIN:
            _HandleLoginRequest(pPdu );
            break;
        case CID_LOGIN_REQ_LOGINOUT:
            _HandleLoginOutRequest(pPdu);
            break;
        case CID_LOGIN_REQ_DEVICETOKEN:
            _HandleClientDeviceToken(pPdu);
            break;
        case CID_LOGIN_REQ_KICKPCCLIENT:
            _HandleKickPCClient(pPdu);
            break;
        case CID_LOGIN_REQ_PUSH_SHIELD:
            _HandlePushShieldRequest(pPdu);
            break;

        case CID_LOGIN_REQ_QUERY_PUSH_SHIELD:
            _HandleQueryPushShieldRequest(pPdu);
            break;
        case CID_MSG_DATA:
            _HandleClientMsgData(pPdu);
            break;
        case CID_MSG_DATA_ACK:
            _HandleClientMsgDataAck(pPdu);
            break;
        case CID_MSG_TIME_REQUEST:
            _HandleClientTimeRequest(pPdu);
            break;
        case CID_MSG_LIST_REQUEST:
            _HandleClientGetMsgListRequest(pPdu);
            break;
        case CID_MSG_GET_BY_MSG_ID_REQ:
            _HandleClientGetMsgByMsgIdRequest(pPdu);
            break;
        case CID_MSG_UNREAD_CNT_REQUEST:
            _HandleClientUnreadMsgCntRequest(pPdu );
            break;
        case CID_MSG_READ_ACK:
            _HandleClientMsgReadAck(pPdu);
            break;
        case CID_MSG_GET_LATEST_MSG_ID_REQ:
            _HandleClientGetLatestMsgIDReq(pPdu);
            break;
        case CID_SWITCH_P2P_CMD:
            _HandleClientP2PCmdMsg(pPdu );
            break;
        case CID_BUDDY_LIST_RECENT_CONTACT_SESSION_REQUEST:
            _HandleClientRecentContactSessionRequest(pPdu);
            break;
        case CID_BUDDY_LIST_USER_INFO_REQUEST:
            _HandleClientUserInfoRequest( pPdu );
            break;
        case CID_BUDDY_LIST_REMOVE_SESSION_REQ:
            _HandleClientRemoveSessionRequest( pPdu );
            break;
        case CID_BUDDY_LIST_ALL_USER_REQUEST:
            _HandleClientAllUserRequest(pPdu );
            break;
        case CID_BUDDY_LIST_CHANGE_AVATAR_REQUEST:
            _HandleChangeAvatarRequest(pPdu);
            break;
        case CID_BUDDY_LIST_CHANGE_SIGN_INFO_REQUEST:
            _HandleChangeSignInfoRequest(pPdu);
            break;

        case CID_BUDDY_LIST_USERS_STATUS_REQUEST:
            _HandleClientUsersStatusRequest(pPdu);
            break;
        case CID_BUDDY_LIST_DEPARTMENT_REQUEST:
            _HandleClientDepartmentRequest(pPdu);
            break;
        // for group process
        case CID_GROUP_NORMAL_LIST_REQUEST:
            s_group_chat->HandleClientGroupNormalRequest(pPdu, this);
            break;
        case CID_GROUP_INFO_REQUEST:
            s_group_chat->HandleClientGroupInfoRequest(pPdu, this);
            break;
        case CID_GROUP_CREATE_REQUEST:
            s_group_chat->HandleClientGroupCreateRequest(pPdu, this);
            break;
        case CID_GROUP_CHANGE_MEMBER_REQUEST:
            s_group_chat->HandleClientGroupChangeMemberRequest(pPdu, this);
            break;
        case CID_GROUP_SHIELD_GROUP_REQUEST:
            s_group_chat->HandleClientGroupShieldGroupRequest(pPdu, this);
            break;

        case CID_FILE_REQUEST:
            s_file_handler->HandleClientFileRequest(this, pPdu);
            break;
        case CID_FILE_HAS_OFFLINE_REQ:
            s_file_handler->HandleClientFileHasOfflineReq(this, pPdu);
            break;
        case CID_FILE_ADD_OFFLINE_REQ:
            s_file_handler->HandleClientFileAddOfflineReq(this, pPdu);
            break;
        case CID_FILE_DEL_OFFLINE_REQ:
            s_file_handler->HandleClientFileDelOfflineReq(this, pPdu);
            break;
        default:
            log("wrong msg, cmd id=%d, user id=%u. ", pPdu->GetCommandId(), GetUserId());
            break;
	}
}

void CMsgConn::_HandleHeartBeat(CImPdu *pPdu)
{
    //--> send pdu back for ack
    SendPdu(pPdu);
}

// process: send validate request to db server
void CMsgConn::_HandleLoginRequest(CImPdu* pPdu)
{
    // refuse second validate request
    if (m_login_name.length() != 0) {
        log("duplicate LoginRequest in the same conn ");
        return;
    }

    // check if all server connection are OK
    uint32_t result = 0;
    string result_string = "";
    CDBServConn* pDbConn = get_db_serv_conn_for_login();
    if (!pDbConn) {
        result = IM::BaseDefine::REFUSE_REASON_NO_DB_SERVER;
        result_string = "服务端异常";
	}
    else if (!is_login_server_available()) {
        result = IM::BaseDefine::REFUSE_REASON_NO_LOGIN_SERVER;
        result_string = "服务端异常";
	}
    else if (!is_route_server_available()) {
        result = IM::BaseDefine::REFUSE_REASON_NO_ROUTE_SERVER;
        result_string = "服务端异常";

}
    if (result) {
        IM::Login::IMLoginRes msg;
        msg.set_server_time(time(NULL));
        msg.set_result_code((IM::BaseDefine::ResultType)result);
        msg.set_result_string(result_string);
        CImPdu pdu;
        pdu.SetPBMsg(&msg);
        pdu.SetServiceId(SID_LOGIN);
        pdu.SetCommandId(CID_LOGIN_RES_USERLOGIN);
        pdu.SetSeqNum(pPdu->GetSeqNum());
        SendPdu(&pdu);
        Close();
        return;
    }
    IM::Login::IMLoginReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    //假如是汉字,则转成拼音
    m_login_name = msg.user_name();
    string password = msg.password();
    uint32_t online_status = msg.online_status();
    if (online_status < IM::BaseDefine::USER_STATUS_ONLINE || online_status > IM::BaseDefine::USER_STATUS_LEAVE) {
        log("HandleLoginReq, online status wrong: %u ", online_status);
        online_status = IM::BaseDefine::USER_STATUS_ONLINE;
    }
    m_client_version = msg.client_version();
    m_client_type = msg.client_type();
    m_online_status = online_status;
    log("HandleLoginReq, user_name=%s, status=%u, client_type=%u, client=%s, ",
        m_login_name.c_str(), online_status, m_client_type, m_client_version.c_str());
    CImUser* pImUser = CImUserManager::GetInstance()->GetImUserByLoginName(GetLoginName());
    if (!pImUser) {
        pImUser = new CImUser(GetLoginName());
        CImUserManager::GetInstance()->AddImUserByLoginName(GetLoginName(), pImUser);
    }
    pImUser->AddUnValidateMsgConn(this);

    CDbAttachData attach_data(ATTACH_TYPE_HANDLE, m_handle, 0);
    // continue to validate if the user is OK

    IM::Server::IMValidateReq msg2;
    msg2.set_user_name(msg.user_name());
    msg2.set_password(password);
    msg2.set_attach_data(attach_data.GetBuffer(), attach_data.GetLength());
    CImPdu pdu;
    pdu.SetPBMsg(&msg2);
    pdu.SetServiceId(SID_OTHER);
    pdu.SetCommandId(CID_OTHER_VALIDATE_REQ);
    pdu.SetSeqNum(pPdu->GetSeqNum());
    pDbConn->SendPdu(&pdu);
}

void CMsgConn::_HandleLoginOutRequest(CImPdu *pPdu)
{
    log("HandleLoginOutRequest, user_id=%d, client_type=%u. ", GetUserId(), GetClientType());
    CDBServConn* pDBConn = get_db_serv_conn();
	if (pDBConn) {
        IM::Login::IMDeviceTokenReq msg;
        msg.set_user_id(GetUserId());
        msg.set_device_token("");
        CImPdu pdu;
        pdu.SetPBMsg(&msg);
        pdu.SetServiceId(SID_LOGIN);
        pdu.SetCommandId(CID_LOGIN_REQ_DEVICETOKEN);
        pdu.SetSeqNum(pPdu->GetSeqNum());
		pDBConn->SendPdu(&pdu);
	}

    IM::Login::IMLogoutRsp msg2;
    msg2.set_result_code(0);
    CImPdu pdu2;
    pdu2.SetPBMsg(&msg2);
    pdu2.SetServiceId(SID_LOGIN);
    pdu2.SetCommandId(CID_LOGIN_RES_LOGINOUT);
    pdu2.SetSeqNum(pPdu->GetSeqNum());
    SendPdu(&pdu2);
    Close();
}
//--> mobile client kick off pc client
void CMsgConn::_HandleKickPCClient(CImPdu *pPdu)
{
    IM::Login::IMKickPCClientReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t user_id = GetUserId();
    if (!CHECK_CLIENT_TYPE_MOBILE(GetClientType()))
    {
        log("HandleKickPCClient, user_id = %u, cmd must come from mobile client. ", user_id);
        return;
    }
    log("HandleKickPCClient, user_id = %u. ", user_id);

    CImUser* pImUser = CImUserManager::GetInstance()->GetImUserById(user_id);
    if (pImUser)
    {
        pImUser->KickOutSameClientType(CLIENT_TYPE_MAC, IM::BaseDefine::KICK_REASON_MOBILE_KICK,this);
    }
    //--> send CID_OTHER_SERVER_KICK_USER to all other msg server
    CRouteServConn* pRouteConn = get_route_serv_conn();
    if (pRouteConn) {
        IM::Server::IMServerKickUser msg2;
        msg2.set_user_id(user_id);
        msg2.set_client_type(::IM::BaseDefine::CLIENT_TYPE_MAC);
        msg2.set_reason(IM::BaseDefine::KICK_REASON_MOBILE_KICK);
        CImPdu pdu;
        pdu.SetPBMsg(&msg2);
        pdu.SetServiceId(SID_OTHER);
        pdu.SetCommandId(CID_OTHER_SERVER_KICK_USER);
        pRouteConn->SendPdu(&pdu);
    }
    //--> send CID_LOGIN_RES_KICKPCCLIENT to client
    IM::Login::IMKickPCClientRsp msg2;
    msg2.set_user_id(user_id);
    msg2.set_result_code(0);
    CImPdu pdu;
    pdu.SetPBMsg(&msg2);
    pdu.SetServiceId(SID_LOGIN);
    pdu.SetCommandId(CID_LOGIN_RES_KICKPCCLIENT);
    pdu.SetSeqNum(pPdu->GetSeqNum());
    SendPdu(&pdu);
}

void CMsgConn::_HandleClientRecentContactSessionRequest(CImPdu *pPdu)
{
    CDBServConn* pConn = get_db_serv_conn_for_login();
    if (!pConn) {
        return;
    }

    IM::Buddy::IMRecentContactSessionReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    log("HandleClientRecentContactSessionRequest, user_id=%u, latest_update_time=%u. ", GetUserId(), msg.latest_update_time());

    msg.set_user_id(GetUserId());
    // 请求最近联系会话列表
    CDbAttachData attach_data(ATTACH_TYPE_HANDLE, m_handle, 0);
    msg.set_attach_data(attach_data.GetBuffer(), attach_data.GetLength());
    pPdu->SetPBMsg(&msg);
    pConn->SendPdu(pPdu);
}

void CMsgConn::_HandleClientMsgData(CImPdu* pPdu)
{
    IM::Message::IMMsgData msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
	if (msg.msg_data().length() == 0) {
		log("discard an empty message, uid=%u ", GetUserId());
		return;
	}

	if (m_msg_cnt_per_sec >= MAX_MSG_CNT_PER_SECOND) {
		log("!!!too much msg cnt in one second, uid=%u ", GetUserId());
		return;
	}

    if (msg.from_user_id() == msg.to_session_id() && CHECK_MSG_TYPE_SINGLE(msg.msg_type()))
    {
        log("!!!from_user_id == to_user_id. ");
        return;
    }

	m_msg_cnt_per_sec++;

	uint32_t to_session_id = msg.to_session_id();
    uint32_t msg_id = msg.msg_id();
	uint8_t msg_type = msg.msg_type();
    string msg_data = msg.msg_data();

	if (g_log_msg_toggle) {
		log("HandleClientMsgData, %d->%d, msg_type=%u, msg_id=%u. ", GetUserId(), to_session_id, msg_type, msg_id);
	}

	uint32_t cur_time = time(NULL);
    CDbAttachData attach_data(ATTACH_TYPE_HANDLE, m_handle, 0);
    msg.set_from_user_id(GetUserId());
    msg.set_create_time(cur_time);
    msg.set_attach_data(attach_data.GetBuffer(), attach_data.GetLength());
    pPdu->SetPBMsg(&msg);
	// send to DB storage server
	CDBServConn* pDbConn = get_db_serv_conn();
	if (pDbConn) {
		pDbConn->SendPdu(pPdu);
	}
}

void CMsgConn::_HandleClientMsgDataAck(CImPdu* pPdu)
{
    IM::Message::IMMsgDataAck msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));

    IM::BaseDefine::SessionType session_type = msg.session_type();
    if (session_type == IM::BaseDefine::SESSION_TYPE_SINGLE)
    {
        uint32_t msg_id = msg.msg_id();
        uint32_t session_id = msg.session_id();
        DelFromSendList(msg_id, session_id);
    }
}

void CMsgConn::_HandleClientTimeRequest(CImPdu* pPdu)
{
    IM::Message::IMClientTimeRsp msg;
    msg.set_server_time((uint32_t)time(NULL));
    CImPdu pdu;
    pdu.SetPBMsg(&msg);
    pdu.SetServiceId(SID_MSG);
    pdu.SetCommandId(CID_MSG_TIME_RESPONSE);
    pdu.SetSeqNum(pPdu->GetSeqNum());
	SendPdu(&pdu);
}

void CMsgConn::_HandleClientGetMsgListRequest(CImPdu *pPdu)
{
    IM::Message::IMGetMsgListReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t session_id = msg.session_id();
    uint32_t msg_id_begin = msg.msg_id_begin();
    uint32_t msg_cnt = msg.msg_cnt();
    uint32_t session_type = msg.session_type();
    log("HandleClientGetMsgListRequest, req_id=%u, session_type=%u, session_id=%u, msg_id_begin=%u, msg_cnt=%u. ",
        GetUserId(), session_type, session_id, msg_id_begin, msg_cnt);
    CDBServConn* pDBConn = get_db_serv_conn_for_login();
    if (pDBConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientGetMsgByMsgIdRequest(CImPdu *pPdu)
{
    IM::Message::IMGetMsgByIdReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t session_id = msg.session_id();
    uint32_t session_type = msg.session_type();
    uint32_t msg_cnt = msg.msg_id_list_size();
    log("_HandleClientGetMsgByMsgIdRequest, req_id=%u, session_type=%u, session_id=%u, msg_cnt=%u.",
        GetUserId(), session_type, session_id, msg_cnt);
    CDBServConn* pDBConn = get_db_serv_conn_for_login();
    if (pDBConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientUnreadMsgCntRequest(CImPdu* pPdu)
{
	log("HandleClientUnreadMsgCntReq, from_id=%u ", GetUserId());
    IM::Message::IMUnreadMsgCntReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));

	CDBServConn* pDBConn = get_db_serv_conn_for_login();
	if (pDBConn) {
		CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
	}
}

void CMsgConn::_HandleClientMsgReadAck(CImPdu* pPdu)
{
    IM::Message::IMMsgDataReadAck msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t session_type = msg.session_type();
    uint32_t session_id = msg.session_id();
    uint32_t msg_id = msg.msg_id();
    log("HandleClientMsgReadAck, user_id=%u, session_id=%u, msg_id=%u, session_type=%u. ", GetUserId(),session_id, msg_id, session_type);

	CDBServConn* pDBConn = get_db_serv_conn();
	if (pDBConn) {
        msg.set_user_id(GetUserId());
        pPdu->SetPBMsg(&msg);
		pDBConn->SendPdu(pPdu);
	}
    IM::Message::IMMsgDataReadNotify msg2;
    msg2.set_user_id(GetUserId());
    msg2.set_session_id(session_id);
    msg2.set_msg_id(msg_id);
    msg2.set_session_type((IM::BaseDefine::SessionType)session_type);
    CImPdu pdu;
    pdu.SetPBMsg(&msg2);
    pdu.SetServiceId(SID_MSG);
    pdu.SetCommandId(CID_MSG_READ_NOTIFY);
    CImUser* pUser = CImUserManager::GetInstance()->GetImUserById(GetUserId());
    if (pUser)
    {
        pUser->BroadcastPdu(&pdu, this);
    }
    CRouteServConn* pRouteConn = get_route_serv_conn();
    if (pRouteConn) {
        pRouteConn->SendPdu(&pdu);
    }

    if (session_type == IM::BaseDefine::SESSION_TYPE_SINGLE)
    {
        DelFromSendList(msg_id, session_id);
    }
}

void CMsgConn::_HandleClientGetLatestMsgIDReq(CImPdu *pPdu)
{
    IM::Message::IMGetLatestMsgIdReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t session_type = msg.session_type();
    uint32_t session_id = msg.session_id();
    log("HandleClientGetMsgListRequest, user_id=%u, session_id=%u, session_type=%u. ", GetUserId(),session_id, session_type);

    CDBServConn* pDBConn = get_db_serv_conn();
    if (pDBConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientP2PCmdMsg(CImPdu* pPdu)
{
    IM::SwitchService::IMP2PCmdMsg msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
	string cmd_msg = msg.cmd_msg_data();
	uint32_t from_user_id = msg.from_user_id();
	uint32_t to_user_id = msg.to_user_id();

	log("HandleClientP2PCmdMsg, %u->%u, cmd_msg: %s ", from_user_id, to_user_id, cmd_msg.c_str());

    CImUser* pFromImUser = CImUserManager::GetInstance()->GetImUserById(GetUserId());
	CImUser* pToImUser = CImUserManager::GetInstance()->GetImUserById(to_user_id);

	if (pFromImUser) {
		pFromImUser->BroadcastPdu(pPdu, this);
	}

	if (pToImUser) {
		pToImUser->BroadcastPdu(pPdu, NULL);
	}

	CRouteServConn* pRouteConn = get_route_serv_conn();
	if (pRouteConn) {
		pRouteConn->SendPdu(pPdu);
	}
}

void CMsgConn::_HandleClientUserInfoRequest(CImPdu* pPdu)
{
    IM::Buddy::IMUsersInfoReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t user_cnt = msg.user_id_list_size();
	log("HandleClientUserInfoReq, req_id=%u, user_cnt=%u ", GetUserId(), user_cnt);
	CDBServConn* pDBConn = get_db_serv_conn_for_login();
	if (pDBConn) {
		CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
		pDBConn->SendPdu(pPdu);
	}
}

void CMsgConn::_HandleClientRemoveSessionRequest(CImPdu* pPdu)
{
    IM::Buddy::IMRemoveSessionReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t session_type = msg.session_type();
    uint32_t session_id = msg.session_id();
    log("HandleClientRemoveSessionReq, user_id=%u, session_id=%u, type=%u ", GetUserId(), session_id, session_type);

    CDBServConn* pConn = get_db_serv_conn();
    if (pConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pConn->SendPdu(pPdu);
    }

    if (session_type == IM::BaseDefine::SESSION_TYPE_SINGLE)
    {
        IM::Buddy::IMRemoveSessionNotify msg2;
        msg2.set_user_id(GetUserId());
        msg2.set_session_id(session_id);
        msg2.set_session_type((IM::BaseDefine::SessionType)session_type);
        CImPdu pdu;
        pdu.SetPBMsg(&msg2);
        pdu.SetServiceId(SID_BUDDY_LIST);
        pdu.SetCommandId(CID_BUDDY_LIST_REMOVE_SESSION_NOTIFY);
        CImUser* pImUser = CImUserManager::GetInstance()->GetImUserById(GetUserId());
        if (pImUser) {
            pImUser->BroadcastPdu(&pdu, this);
        }
        CRouteServConn* pRouteConn = get_route_serv_conn();
        if (pRouteConn) {
            pRouteConn->SendPdu(&pdu);
        }
    }
}

void CMsgConn::_HandleClientAllUserRequest(CImPdu* pPdu)
{
    IM::Buddy::IMAllUserReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    uint32_t latest_update_time = msg.latest_update_time();
    log("HandleClientAllUserReq, user_id=%u, latest_update_time=%u. ", GetUserId(), latest_update_time);

    CDBServConn* pConn = get_db_serv_conn();
    if (pConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleChangeAvatarRequest(CImPdu* pPdu)
{
    IM::Buddy::IMChangeAvatarReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    log("HandleChangeAvatarRequest, user_id=%u ", GetUserId());
    CDBServConn* pDBConn = get_db_serv_conn();
    if (pDBConn) {
        msg.set_user_id(GetUserId());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientUsersStatusRequest(CImPdu* pPdu)
{
    IM::Buddy::IMUsersStatReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
	uint32_t user_count = msg.user_id_list_size();
	log("HandleClientUsersStatusReq, user_id=%u, query_count=%u.", GetUserId(), user_count);

    CRouteServConn* pRouteConn = get_route_serv_conn();
    if(pRouteConn)
    {
        msg.set_user_id(GetUserId());
        CPduAttachData attach(ATTACH_TYPE_HANDLE, m_handle,0, NULL);
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pRouteConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientDepartmentRequest(CImPdu *pPdu)
{
    IM::Buddy::IMDepartmentReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    log("HandleClientDepartmentRequest, user_id=%u, latest_update_time=%u.", GetUserId(), msg.latest_update_time());
    CDBServConn* pDBConn = get_db_serv_conn();
    if (pDBConn) {
        CDbAttachData attach(ATTACH_TYPE_HANDLE, m_handle, 0);
        msg.set_user_id(GetUserId());
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());
        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleClientDeviceToken(CImPdu *pPdu)
{
    if (!CHECK_CLIENT_TYPE_MOBILE(GetClientType()))
    {
        log("HandleClientDeviceToken, user_id=%u, not mobile client.", GetUserId());
        return;
    }
    IM::Login::IMDeviceTokenReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    string device_token = msg.device_token();
    log("HandleClientDeviceToken, user_id=%u, device_token=%s ", GetUserId(), device_token.c_str());

    IM::Login::IMDeviceTokenRsp msg2;
    msg.set_user_id(GetUserId());
    msg.set_client_type((::IM::BaseDefine::ClientType)GetClientType());
    CImPdu pdu;
    pdu.SetPBMsg(&msg2);
    pdu.SetServiceId(SID_LOGIN);
    pdu.SetCommandId(CID_LOGIN_RES_DEVICETOKEN);
    pdu.SetSeqNum(pPdu->GetSeqNum());
    SendPdu(&pdu);

    CDBServConn* pDBConn = get_db_serv_conn();
	if (pDBConn) {
        msg.set_user_id(GetUserId());
        pPdu->SetPBMsg(&msg);
		pDBConn->SendPdu(pPdu);
	}
}

void CMsgConn::AddToSendList(uint32_t msg_id, uint32_t from_id)
{
	//log("AddSendMsg, seq_no=%u, from_id=%u ", seq_no, from_id);
	msg_ack_t msg;
	msg.msg_id = msg_id;
	msg.from_id = from_id;
	msg.timestamp = get_tick_count();
	m_send_msg_list.push_back(msg);

	g_down_msg_total_cnt++;
}

void CMsgConn::DelFromSendList(uint32_t msg_id, uint32_t from_id)
{
	//log("DelSendMsg, seq_no=%u, from_id=%u ", seq_no, from_id);
	for (list<msg_ack_t>::iterator it = m_send_msg_list.begin(); it != m_send_msg_list.end(); it++) {
		msg_ack_t msg = *it;
		if ( (msg.msg_id == msg_id) && (msg.from_id == from_id) ) {
			m_send_msg_list.erase(it);
			break;
		}
	}
}

uint32_t CMsgConn::GetClientTypeFlag()
{
    uint32_t client_type_flag = 0x00;
    if (CHECK_CLIENT_TYPE_PC(GetClientType()))
    {
        client_type_flag = CLIENT_TYPE_FLAG_PC;
    }
    else if (CHECK_CLIENT_TYPE_MOBILE(GetClientType()))
    {
        client_type_flag = CLIENT_TYPE_FLAG_MOBILE;
    }
    return client_type_flag;
}

void CMsgConn::_HandleChangeSignInfoRequest(CImPdu* pPdu) {
        IM::Buddy::IMChangeSignInfoReq msg;
        CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
        log("HandleChangeSignInfoRequest, user_id=%u ", GetUserId());
        CDBServConn* pDBConn = get_db_serv_conn();
        if (pDBConn) {
                msg.set_user_id(GetUserId());
                CPduAttachData attach(ATTACH_TYPE_HANDLE, m_handle,0, NULL);
                msg.set_attach_data(attach.GetBuffer(), attach.GetLength());

                pPdu->SetPBMsg(&msg);
                pDBConn->SendPdu(pPdu);
            }
    }
void CMsgConn::_HandlePushShieldRequest(CImPdu* pPdu) {
    IM::Login::IMPushShieldReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    log("_HandlePushShieldRequest, user_id=%u, shield_status ", GetUserId(), msg.shield_status());
    CDBServConn* pDBConn = get_db_serv_conn();
    if (pDBConn) {
        msg.set_user_id(GetUserId());
        CPduAttachData attach(ATTACH_TYPE_HANDLE, m_handle,0, NULL);
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());

        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}

void CMsgConn::_HandleQueryPushShieldRequest(CImPdu* pPdu) {
    IM::Login::IMQueryPushShieldReq msg;
    CHECK_PB_PARSE_MSG(msg.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()));
    log("HandleChangeSignInfoRequest, user_id=%u ", GetUserId());
    CDBServConn* pDBConn = get_db_serv_conn();
    if (pDBConn) {
        msg.set_user_id(GetUserId());
        CPduAttachData attach(ATTACH_TYPE_HANDLE, m_handle,0, NULL);
        msg.set_attach_data(attach.GetBuffer(), attach.GetLength());

        pPdu->SetPBMsg(&msg);
        pDBConn->SendPdu(pPdu);
    }
}


text:
"""

Functions:
split_tdf   Split a tab-delimited format
read_tdf    OBSOLETE
write_tdf   OBSOLETE

strip_each

"""
import os, sys

def split_tdf(data, strip=False):
    # Bug: will skip blank lines.
    matrix = [
        x.rstrip("\r\n").split("\t") for x in data.split("\n") if x.strip()]
    if strip:
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                matrix[i][j] = matrix[i][j].strip()
    return matrix

## def read_tdf(handle, num_header_rows, num_header_cols):
##     # Format:
##     # - First num_header_cols contain metadata, last ones samples.
##     # - First row headings, last ones samples.
##     # - Return as a single matrix.
##     import filelib
##     import jmath

##     handle = filelib.openfh(handle)
##     data = split_tdf(handle.read())

##     X = []
##     num_cols = None
##     for cols in data:
##         if num_cols is None:
##             num_cols = len(cols)
##         assert len(cols) == num_cols
##         if len(X) >= num_header_rows:
##             x = map(jmath.safe_float, cols[num_header_cols:])
##             cols[num_header_cols:] = x
##         X.append(cols)
##     return X

## def write_tdf(data, outhandle):
##     for x in data:
##         x = map(str, x)
##         print >>outhandle, "\t".join(x)

CLEAN_RE = None
CLEAN_DISALLOWED = None
def _py_cleanwrite(data, outhandle, delim="\t"):
    global CLEAN_RE
    global CLEAN_DISALLOWED
    import re

    disallowed = "\r\n" + delim
    if CLEAN_RE is None or CLEAN_DISALLOWED != disallowed:
        CLEAN_RE = re.compile("[%s]" % disallowed)
        CLEAN_DISALLOWED = disallowed

    for x in data:
        x = x[:]
        for i in range(len(x)):
            if x[i] is None:
                x[i] = ""
        x = map(str, x)
        x = [CLEAN_RE.subn(" ", x)[0].strip() for x in x]
        x = delim.join(x)
        print >>outhandle, x
_cleanwrite = _py_cleanwrite

def cleanwrite(data, outhandle, delim="\t"):
    import types

    # The C version of _cleanwrite requires outhandle to be a file
    # object and won't work with StringIO objects.  If the user does
    # not provide a real file object, then use the python
    # implementation.
    if type(outhandle) is not types.FileType:
        _py_cleanwrite(data, outhandle, delim=delim)
        return
    #print "Calling _cleanwrite"
    _cleanwrite(data, outhandle, delim=delim)

def strip_each(L):
    return [x.strip() for x in L]

# Try and load C implementations of functions.  If I can't,
# then just ignore and use the pure python implementations.
try:
    #raise ImportError
    import ciolib
except ImportError:
    pass
else:
    this_module = sys.modules[__name__]
    for name in ciolib.__dict__.keys():
        if not name.startswith("__"):
            this_module.__dict__[name] = ciolib.__dict__[name]

redpajama_set_name: RedPajamaGithub


text:
id: 5900f3f71000cf542c50ff0a
challengeType: 5
title: 'Problem 139: Pythagorean tiles'
forumTopicId: 301767
---

## Description

Let (a, b, c) represent the three sides of a right angle triangle with integral length sides. It is possible to place four such triangles together to form a square with length c.
For example, (3, 4, 5) triangles can be placed together to form a 5 by 5 square with a 1 by 1 hole in the middle and it can be seen that the 5 by 5 square can be tiled with twenty-five 1 by 1 squares.

However, if (5, 12, 13) triangles were used then the hole would measure 7 by 7 and these could not be used to tile the 13 by 13 square.
Given that the perimeter of the right triangle is less than one-hundred million, how many Pythagorean triangles would allow such a tiling to take place?

## Instructions

## Tests

```yml
tests:
  - text: <code>euler139()</code> should return 10057761.
    testString: assert.strictEqual(euler139(), 10057761);

```

## Challenge Seed

```js
function euler139() {
  // Good luck!
  return true;
}

euler139();
```

## Solution

```js
// solution required
```


text:
"use strict";
var config = require('./../config');

function _getRouteByOrigin(routes, origin) {
  return routes.filter(
    function (routes) {
      return routes.origin === origin;
    }
  );
}

function _removeTlds(host) {
  config.tlds.forEach(function (tld) {
    host = host.replace(tld, '');
  });
  return host;
}

function _removeThirdLevelDomain(host) {
  return  host.replace(config.thirdLevelDomain, '');
}

module.exports = {
  parseHost: function (host) {
    var globalHost = _removeTlds(host),
        globalHost = _removeThirdLevelDomain(globalHost),
        hostArray = globalHost.split('.'),
        domain,
        origin;

    if (hostArray.length > 2) {
      origin = hostArray[0];
      domain = hostArray[1];
    } else {
      domain = hostArray[0];
      origin = domain;
    }
    return {
      domain: domain,
      origin: origin
    };
  },
  findTarget: function (domain, origin) {
    var dnsObject = require('./../domain/' + domain),
        routes = dnsObject().routes,
        route = _getRouteByOrigin(routes, origin);
    return route[0].target + ':' + route[0].port;
  }
};


text:
package io.dylemma.spac
package impl

import scala.annotation.tailrec

abstract class ParsableByIterator[S, In] extends Parsable[cats.Id, S, In] {
	protected def lendIterator[Out](source: S, f: Iterator[In] => Out): Out

	def parse[Out](source: S, callerFrame: SpacTraceElement, parser: Parser[In, Out]) = {
		lendIterator(source, iterator => {
			@tailrec def loop(handler: Parser.Handler[In, Out]): Out = {
				if (iterator.hasNext) {
					val in = iterator.next()
					handler.step(in) match {
						case Left(out) => out
						case Right(cont) => loop(cont)
					}
				} else {
					handler.finish()
				}
			}

			loop(parser.newHandler.asTopLevelHandler(callerFrame))
		})
	}
}


text:
/**
 *
 */
package org.jscruz.wallboard.health;

import com.codahale.metrics.health.HealthCheck;

/**
 *
 *

 *
Title : TemplateHealthCheck.java

 *
Description :

 *
Copyright : Copyright (c) 2015

 *
Company : Siemens Traffic

 *
Project : wallboard-api--0.0.1-SNAPSHOT

 *
Author : Jorge.Cruz-Lambert

 *

 *

 * Copyright (c) Siemens plc 2015. This is an unpublished work, the copyright in which vests in Siemens plc. All
 * rights reserved.

 * The information contained herein is the property of Siemens plc and is supplied without liability for any errors or
 * omissions and no part may be copied,

 * reproduced, used or disclosed except as authorised by contract or other prior written permission.

 * The copyright and the foregoing restriction on reproduction, use and disclosure extend to all the media in which this
 * information may be embodied.

 * Where any information is the responsibility of individual authors, the views contained within said documents do not
 * necessarily represent the views of Siemens plc.
 *

 */
public class TemplateHealthCheck extends HealthCheck
{
    private final String template;

    public TemplateHealthCheck(String template) {
        this.template = template;
    }

    @Override
    protected Result check() throws Exception {
        final String saying = String.format(template, "TEST");
        if (!saying.contains("TEST")) {
            return Result.unhealthy("template doesn't include a name");
        }
        return Result.healthy();
    }
}


text:
drop table users if exists;

create table users (
  id int,
  name varchar(20),
  group_id int,
  rol_id int
);

insert into users values(1, 'User1', 1, 1);
insert into users values(1, 'User1', 1, 2);
insert into users values(1, 'User1', 2, 1);
insert into users values(1, 'User1', 2, 2);


text:
bool Scanner::keywordsInitDone = false;
std::map<std::string, TokenType> Scanner::keywords =
  std::map<std::string, TokenType>();
Scanner::Scanner(std::string source, SparkleCode* interp) : source(source) {
  // store reference to interpreter inorder to call error function
  this->interp = interp;

  // if keywords not initialised, do so
  if (!keywordsInitDone) {
    keywordsInitDone = true;
    keywords["and"] = AND;
    keywords["class"] = CLASS;
    keywords["else"] = ELSE;
    keywords["false"] = FALSE;
    keywords["for"] = FOR;
    keywords["fn"] = FN;
    keywords["if"] = IF;
    keywords["or"] = OR;
    keywords["print"] = PRINT;
    keywords["return"] = RETURN;
    keywords["super"] = SUPER;
    keywords["this"] = THIS;
    keywords["var"] = VAR;
    keywords["while"] = WHILE;
  }
}

std::vector<Token> Scanner::scanTokens() {
  // read whole file
  while (!isAtEnd()) {
    // at begining of next lexeme
    start = current;
    scanToken();
  }

  // add end of file token
  tokens.push_back(Token(EofF, "", line));

  return tokens;
}

void Scanner::scanToken() {
  char c = advance();
  switch (c) {
    // skip whitespace
    case ' ':
    case '\r':
    case '\t': break;

    // new line and skip
    case '\n': line++; break;

    // single character tokens
    case '(': addToken(LEFT_PAREN); break;
    case ')': addToken(RIGHT_PAREN); break;
    case '{': addToken(LEFT_BRACE); break;
    case '}': addToken(RIGHT_BRACE); break;
    case ',': addToken(COMMA); break;
    case '.': addToken(DOT); break;
    case '-': addToken(MINUS); break;
    case '+': addToken(PLUS); break;
    case ';': addToken(SEMICOLON); break;
    case '*': addToken(STAR); break;

    // multi character operators
    case '!': addToken(match('=') ?
      NOT_EQUAL : NOT); break;
    case '=': addToken(match('=') ?
      EQUAL_EQUAL : TokenType::EQUAL); break;
    case '<': addToken(match('=') ?
      LESS_EQUAL : LESS); break;
    case '>': addToken(match('=') ?
      GREATER_EQUAL : GREATER); break;

    // is comment or division?
    case '/':
      if (match('/')) {
        while (peek() != '\n' && !isAtEnd()) advance();
      } else {
        addToken(SLASH);
      }
      break;

    case '"': string(); break;

    default:
      if (isDigit(c)) {
        number();
      } else if (isAlpha(c)) {
        identifier();
      } else {
        interp->error(line, "unexpected character");
      }
      break;
  }
}

bool Scanner::isAtEnd() {
  // had the end of the file been reached?
  return current >= source.length();
}

char Scanner::advance() {
  // return and consume next character
  current++;
  return source.at(current - 1);
}

void Scanner::addToken(TokenType type) {
  // add token to list of tokens
  std::string text = source.substr(start, current);
  tokens.push_back(Token(type, text, line));
}

void Scanner::addToken(TokenType type, std::string lit) {
  // add token to list of tokens
  std::string text = source.substr(start, current);
  tokens.push_back(Token(type, text, lit, line));
}

void Scanner::addToken(TokenType type, double lit) {
  // add token to list of tokens
  std::string text = source.substr(start, current);
  tokens.push_back(Token(type, text, lit, line));
}

bool Scanner::match(char expected) {
  // consume character and return if it equals expected
  if (isAtEnd()) return false;
  if (source.at(current) != expected) return false;

  current++;
  return true;
}

char Scanner::peek() {
  // get but don't consume character
  if (isAtEnd()) return '\0';
  return source.at(current);
}

char Scanner::peekNext() {
  if (current + 1 >= source.length()) return '\0';
  return source.at(current + 1);
}

void Scanner::string() {
  // loop until end of string
  while (peek() != '"' && !isAtEnd()) {
    if (peek() == '\n') line++;
    advance();
  }

  // unterminated string
  if (isAtEnd()) {
    interp->error(line, "unterminated string");
    return;
  }

  // consune closing "
  advance();

  // get read string and remove quotes
  std::string value = source.substr(start + 1, current - 2);
  addToken(STRING, value);
}

bool Scanner::isDigit(char c) {
  return c >= '0' && c <= '9';
}

void Scanner::number() {
  while (isDigit(peek())) advance();

  // is decimal
  if (peek() == '.' && isDigit(peekNext())) {
    // consume .
    advance();

    // consume decimal part
    while (isDigit(peek())) advance();
  }

  addToken(NUMBER, atof(source.substr(start, current).c_str()));
}

void Scanner::identifier() {
  while (isAlphaNumeric(peek())) advance();

  std::string text = source.substr(start, current);

  std::map<std::string, TokenType>::iterator pos = keywords.find(text);
  TokenType type;
  if (pos == keywords.end()) {
    type = IDENTIFIER;
  } else {
    type = pos->second;
  }
  addToken(type);
}

bool Scanner::isAlpha(char c) {
  return (c >= 'a' && c <= 'z') ||
         (c >= 'A' && c <= 'Z') ||
          c == '_';
}

bool Scanner::isAlphaNumeric(char c) {
  return isAlpha(c) || isDigit(c);
}


text:
<!doctype html>

    <title>GradRanker</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <link href="http://kirmani.io/wp-content/themes/mytheme/style.css" rel="stylesheet" type="text/css" />

    <link href="http://kirmani.io/wp-content/themes/mytheme/css/typography.css" rel="stylesheet" type="text/css" />

     <link rel="stylesheet" href="{{url_for('static', filename='css/style.css')}}">

{% raw %}

            <svg class="menu-icon" width="23" height="15" viewport="0 0 23 15" version="1.1" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="23" height="3"></rect><rect x="0" y="6" width="23" height="3"></rect><rect x="0" y="12" width="23" height="3"></rect></svg>

Home

About

Résumé

Blog

Applying for a {{profile.program.display}} at {{profile.school.display_name}} {{profile.field.display_name}}

            <form ng-submit="parse()" class="card">

Pick a University:

                    <select ng-model="profile.school" ng-value="{{profile.school}}" ng-options="school as school.display_name for (id, school) in schools | orderBy: 'display_name'" ng-change="parse()">
                    </select>

What field?

                    <select ng-model="profile.field" ng-value="{{profile.field}}" ng-options="fields[field] as fields[field].display_name for field in profile.school.fields | orderBy: 'display_name'" ng-change="parse()">
                    </select>

What are you applying for?

                    <select ng-model="profile.program" ng-value="{{profile.program}}" ng-options="program as program.display for program in programs" ng-change="parse()">
                    </select>

Try and predict missing scores?

(This tends to take more processing time and may not always work well)

                    <input type="checkbox" ng-model="predict" ng-change="parse()" />

Compare against only Americans?

                    <input type="checkbox" ng-model="americanOnly" ng-change="parse()" />

What is your national status?

                    <select ng-model="profile.status" ng-value="{{profile.status}}"  ng-options="status as status.display for status in statuses" ng-change="parse()" />
                    </select>

                <button type="button" class="button buttonBlue" ng-click="parse()" >See Results!

                </button>
            </form>
            <form ng-submit="test()" ng-if="parsed" class="card">

                        <input type="number" ng-model="profile.gre_verbal" ng-value="{{profile.gre_verbal}}" value="{{profile.gre_verbal}}" ng-change="test()" step="1" min="130" max="170" ng-class="{used: profile.gre_verbal >= 0}">

                        GRE Verbal

                        <input type="number" ng-model="profile.gre_quant" ng-value="{{profile.gre_quant}}" value="{{profile.gre_quant}}" ng-change="test()" step="1" min="130" max="170" ng-class="{used: profile.gre_quant >= 0}"/>

                        GRE Quant

                        <input type="number" ng-model="profile.gre_writing" ng-value="{{profile.gre_writing}}" value="{{profile.gre_writing}}" ng-change="test()" step="0.5" min="0.0" max="6.0" ng-class="{used: profile.gre_writing >= 0}" />

                        GRE Writing

                        <input type="number" ng-model="profile.gpa" ng-value="{{profile.gpa}}" value="{{profile.gpa}}" ng-change="test()" step="0.01" min="0.0" max="4.0" ng-class="{used: profile.gpa >= 0}"/>

                        GPA

            </form>

General Statistics

Predicted Admit Chance: {{admit * 100 | number: 0}}%

Your GradRank: {{score}}

Total Number of Applicants: {{numApplied}}

Number Accepted: {{numAccepted}}

Numbed Denied: {{numDenied}}

Acceptance Rate: {{acceptanceRate * 100}}%

Average Scores

                            Application
                            Accepted

                            GRE Verbal
                            {{avg_application_gre_verbal}}
                            {{avg_accepted_gre_verbal}}

                            GRE Quant
                            {{avg_application_gre_quant}}
                            {{avg_accepted_gre_quant}}

                            GRE Writing
                            {{avg_application_gre_writing}}
                            {{avg_accepted_gre_writing}}

                            GPA
                            {{avg_application_gpa}}
                            {{avg_accepted_gpa}}

Training Data

                            {{input.display}}
                            {{output.display}}</id>
                            Decision

                            {{test.inputs[$index]}}

                            {{test.outputs[$index]}}
                            {{test.expected[0]}}

        <form id="submitter-form" ng-submit="submit()">

Submit your results!

Where did you get in?

                    <select ng-model="submission.applications[$index].school" ng-value="{{submission.applications[$index].school}}" ng-options="school.id as school.display_name for (id, school) in schools | orderBy: 'display_name'" required>
                        <option value="">Select School!</option>
                    </select>

What field?

                    <select ng-model="submission.applications[$index].field" ng-value="{{submission.applications[$index].field}}" ng-options="field.id as field.display_name for (id, field) in fields | orderBy: 'display_name'" required>
                        <option value="">Select Field!</option>
                    </select>

What degree did you apply for?

                    <select ng-model="submission.applications[$index].ms_phd" ng-value="{{submission.applications[$index].ms_phd}}" ng-options="program.num as program.display for program in programs" required>
                        <option value="">Select Program!</option>
                    </select>

Were you admitted or denied?

                    <select ng-model="submission.applications[$index].decision" ng-value="{{submission.applications[$index].decision}}" ng-options="decision.value as decision.display for decision in decisions" required>
                        <option value="">Select Decision!</option>
                    </select>

            <button type="button" class="button buttonBlue" ng-click="number_of_schools_submitting = number_of_schools_submitting + 1">Add another school!

            </button>

Recommendations!

Recommender is a

                    <select ng-model="submission.recs[$index].from" ng-value="{{submission.recs[$index].from}}" ng-options="rec.value as rec.display for (id, rec) in recs_from" required>
                        <option value="">--- ----------</option>
                    </select>

observing you as a

                    <select ng-model="submission.recs[$index].observing" ng-value="{{submission.recs[$index].observing}}" ng-options="rec.value as rec.display for (id, rec) in recs_observing" required>
                        <option value="">--- ----------</option>
                    </select>

describing you as a

                    <select ng-model="submission.recs[$index].describing" ng-value="{{submission.recs[$index].describing}}" ng-options="rec.value as rec.display for (id, rec) in recs_describing" required>
                        <option value="">--- ----------</option>
                    </select>

            <button type="button" class="button buttonBlue" ng-click="number_of_recs_submitting = number_of_recs_submitting + 1">Add another recommendation!!

            </button>

Statement of Purpose

                <select ng-model="submission.sop" ng-value="{{submission.sop}}" ng-options="sop.value as sop.display for (id, sop) in sop" required>
                    <option value="">--- ----------</option>
                </select>

                <input type="number" ng-model="submission.gre_verbal" ng-value="{{submission.gre_verbal}}" value="{{submission.gre_verbal}}" step="1" min="130" max="170" ng-class="{used: submission.gre_verbal >= 0}" required />

                GRE Verbal

                <input type="number" ng-model="submission.gre_quant" ng-value="{{submission.gre_quant}}" value="{{submission.gre_quant}}" step="1" min="130" max="170" ng-class="{used: submission.gre_quant >= 0}" required />

                GRE Quant

                <input type="number" ng-model="submission.gre_writing" ng-value="{{submission.gre_writing}}" value="{{submission.gre_writing}}" step="0.5" min="0.0" max="6.0" ng-class="{used: submission.gre_writing >= 0}" required />

                GRE Writing

                <input type="number" ng-model="submission.gpa" ng-value="{{submission.gpa}}" value="{{submission.gpa}}" step="0.01" min="0.0" max="4.0" ng-class="{used: submission.gpa >= 0}" required />

                GPA

What is your national status?

                <select ng-model="submission.status" ng-value="{{submission.status}}"  ng-options="status.value as status.display for status in statuses" required />
                     <option value="">Select Status</option>
                </select>

Where does your undergrad institution rank in your field?

                <select ng-model="submission.rank" ng-value="{{submission.rank}}" ng-options="rank.value as rank.display for rank in ranks" required>
                    <option value="">Select Rank</option>
                </select>

What was your undergrad major?

                <select ng-model="submission.major" ng-value="{{submission.major}}" ng-options="major.value as major.display for (id, major) in majors">
                    <option value="">Select Major</option>
                </select>

How many months have you worked in a relevant internship?

                <input type="number" ng-model="submission.internships" ng-value="{{submission.internships}}" value="{{submission.internships}}" step="1" min="0.0" ng-class="{used: submission.internships >= 0}" required />

How many months have you been doing research?

                <input type="number" ng-model="submission.research" ng-value="{{submission.research}}" value="{{submission.research}}" step="1" min="0" ng-class="{used: submission.research >= 0}" required />

Did you do any REUs?

                <input type="checkbox" ng-model="submission.reu" />

Do you have any publications?

                <input type="checkbox" ng-model="submission.publications" />

Anything else?

                <textarea ng-model="submission.comments"> </textarea>

            <button type="submit" class="button buttonBlue">Send your results!

            </button>
        </form>

{% endraw %}


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// 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.

package com.google.devtools.build.buildjar.javac;

import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;

import com.sun.tools.javac.main.Main.Result;

import java.io.PrintWriter;
import java.util.List;

/**
 * This class wraps a single invocation of Javac. We
 * invoke javac statically but wrap it with a synchronization.
 * This is because the same javac cannot be invoked multiple
 * times in parallel.
 */
public class JavacRunnerImpl implements JavacRunner {

  private final List<BlazeJavaCompilerPlugin> plugins;

  /**
   * Passes extra information to BlazeJavacMain in case strict Java
   * dependencies are enforced.
   */
  public JavacRunnerImpl(List<BlazeJavaCompilerPlugin> plugins) {
    this.plugins = plugins;
  }

  @Override
  public synchronized Result invokeJavac(String[] args, PrintWriter output) {
    return new BlazeJavacMain(output, plugins).compile(args);
  }

}


text:
package openapi3filter

import (
	"context"
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/getkin/kin-openapi/openapi3"
	"github.com/getkin/kin-openapi/routers/gorillamux"
)

func TestIssue201(t *testing.T) {
	loader := openapi3.NewLoader()
	ctx := loader.Context
	spec := `
openapi: '3'
info:
  version: 1.0.0
  title: Sample API
paths:
  /_:
    get:
      description: ''
      responses:
        default:
          description: ''
          content:
            application/json:
              schema:
                type: object
          headers:
            X-Blip:
              description: ''
              required: true
              schema:
                pattern: '^blip$'
            x-blop:
              description: ''
              schema:
                pattern: '^blop$'
            X-Blap:
              description: ''
              required: true
              schema:
                pattern: '^blap$'
            X-Blup:
              description: ''
              required: true
              schema:
                pattern: '^blup$'
`[1:]

	doc, err := loader.LoadFromData([]byte(spec))
	require.NoError(t, err)

	err = doc.Validate(ctx)
	require.NoError(t, err)

	for name, testcase := range map[string]struct {
		headers map[string]string
		err     string
	}{

		"no error": {
			headers: map[string]string{
				"X-Blip": "blip",
				"x-blop": "blop",
				"X-Blap": "blap",
				"X-Blup": "blup",
			},
		},

		"missing non-required header": {
			headers: map[string]string{
				"X-Blip": "blip",
				// "x-blop": "blop",
				"X-Blap": "blap",
				"X-Blup": "blup",
			},
		},

		"missing required header": {
			err: `response header "X-Blip" missing`,
			headers: map[string]string{
				// "X-Blip": "blip",
				"x-blop": "blop",
				"X-Blap": "blap",
				"X-Blup": "blup",
			},
		},

		"invalid required header": {
			err: `response header "X-Blup" doesn't match the schema: string doesn't match the regular expression "^blup$"`,
			headers: map[string]string{
				"X-Blip": "blip",
				"x-blop": "blop",
				"X-Blap": "blap",
				"X-Blup": "bluuuuuup",
			},
		},
	} {
		t.Run(name, func(t *testing.T) {
			router, err := gorillamux.NewRouter(doc)
			require.NoError(t, err)

			r, err := http.NewRequest(http.MethodGet, `/_`, nil)
			require.NoError(t, err)

			r.Header.Add(headerCT, "application/json")
			for k, v := range testcase.headers {
				r.Header.Add(k, v)
			}

			route, pathParams, err := router.FindRoute(r)
			require.NoError(t, err)

			err = ValidateResponse(context.Background(), &ResponseValidationInput{
				RequestValidationInput: &RequestValidationInput{
					Request:    r,
					PathParams: pathParams,
					Route:      route,
				},
				Status: 200,
				Header: r.Header,
				Body:   io.NopCloser(strings.NewReader(`{}`)),
			})
			if e := testcase.err; e != "" {
				require.ErrorContains(t, err, e)
			} else {
				require.NoError(t, err)
			}
		})
	}
}


text:
""" Utility functions for sparse matrix module
"""

from __future__ import division, print_function, absolute_import

__all__ = ['upcast','getdtype','isscalarlike','isintlike',
            'isshape','issequence','isdense','ismatrix']

import warnings
import numpy as np

# keep this list syncronized with sparsetools
#supported_dtypes = ['bool', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32',
#        'int64', 'uint64', 'float32', 'float64',
#        'complex64', 'complex128']
supported_dtypes = ['bool', 'int8','uint8','short','ushort','intc','uintc',
        'longlong','ulonglong','single','double','longdouble',
        'csingle','cdouble','clongdouble']
supported_dtypes = [np.typeDict[x] for x in supported_dtypes]

_upcast_memo = {}

def upcast(*args):
    """Returns the nearest supported sparse dtype for the
    combination of one or more types.

    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype

    Examples
    --------

    >>> upcast('int32')
    <type 'numpy.int32'>
    >>> upcast('bool')
    <type 'numpy.bool_'>
    >>> upcast('int32','float32')
    <type 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <type 'numpy.complex128'>

    """

    t = _upcast_memo.get(hash(args))
    if t is not None:
        return t

    if np.all([np.issubdtype(np.bool, arg) for arg in args]):
        # numpy 1.5.x compat - it gives int8 for
        # np.find_common_type([np.bool, np.bool)
        upcast = np.bool
    else:
        upcast = np.find_common_type(args, [])

    for t in supported_dtypes:
        if np.can_cast(upcast, t):
            _upcast_memo[hash(args)] = t
            return t

    raise TypeError('no supported conversion for types: %r' % (args,))

def upcast_char(*args):
    """Same as `upcast` but taking dtype.char as input (faster)."""
    t = _upcast_memo.get(args)
    if t is not None:
        return t
    t = upcast(*map(np.dtype, args))
    _upcast_memo[args] = t
    return t

def upcast_scalar(dtype, scalar):
    """Determine data type for binary operation between an array of
    type `dtype` and a scalar.
    """
    return (np.array([0], dtype=dtype) * scalar).dtype

def to_native(A):
    return np.asarray(A,dtype=A.dtype.newbyteorder('native'))

def getdtype(dtype, a=None, default=None):
    """Function used to simplify argument processing.  If 'dtype' is not
    specified (is None), returns a.dtype; otherwise returns a np.dtype
    object created from the specified dtype argument.  If 'dtype' and 'a'
    are both None, construct a data type out of the 'default' parameter.
    Furthermore, 'dtype' must be in 'allowed' set.
    """
    #TODO is this really what we want?
    canCast = True
    if dtype is None:
        try:
            newdtype = a.dtype
        except AttributeError:
            if default is not None:
                newdtype = np.dtype(default)
                canCast = False
            else:
                raise TypeError("could not interpret data type")
    else:
        newdtype = np.dtype(dtype)
        if newdtype == np.object_:
            warnings.warn("object dtype is not supported by sparse matrices")

    return newdtype

def isscalarlike(x):
    """Is x either a scalar, an array scalar, or a 0-dim array?"""
    return np.isscalar(x) or (isdense(x) and x.ndim == 0)

def isintlike(x):
    """Is x appropriate as an index into a sparse matrix? Returns True
    if it can be cast safely to a machine int.
    """
    if issequence(x):
        return False
    else:
        try:
            if int(x) == x:
                return True
            else:
                return False
        except TypeError:
            return False

def isshape(x):
    """Is x a valid 2-tuple of dimensions?
    """
    try:
        # Assume it's a tuple of matrix dimensions (M, N)
        (M, N) = x
    except:
        return False
    else:
        if isintlike(M) and isintlike(N):
            if np.rank(M) == 0 and np.rank(N) == 0:
                return True
        return False

def issequence(t):
    return (isinstance(t, (list, tuple)) and (len(t) == 0 or np.isscalar(t[0]))) \
           or (isinstance(t, np.ndarray) and (t.ndim == 1))

def ismatrix(t):
    return ((issequence(t) and issequence(t[0]) and (len(t[0]) == 0 or np.isscalar(t[0][0])))
            or (isinstance(t, np.ndarray) and t.ndim == 2))

def isdense(x):
    return isinstance(x, np.ndarray)

class IndexMixin(object):
    """
    This class simply exists to hold the methods necessary for fancy indexing.
    """
    def _slicetoarange(self, j, shape):
        """ Given a slice object, use numpy arange to change it to a 1D
        array.
        """
        start, stop, step = j.indices(shape)
        return np.arange(start, stop, step)

    def _unpack_index(self, index):
        """ Parse index. Always return a tuple of the form (row, col).
        Where row/col is a integer, slice, or array of integers.
        """
        # First, check if indexing with single boolean matrix.
        from .base import spmatrix  # This feels dirty but...
        if (isinstance(index, (spmatrix, np.ndarray)) and
           (index.ndim == 2) and index.dtype.kind == 'b'):
                return index.nonzero()

        # Next, parse the tuple or object
        if isinstance(index, tuple):
            if len(index) == 2:
                row, col = index
            elif len(index) == 1:
                row, col = index[0], slice(None)
            else:
                raise IndexError('invalid number of indices')
        else:
            row, col = index, slice(None)

        # Next, check for validity, or transform the index as needed.
        row, col = self._check_boolean(row, col)
        return row, col

    def _check_boolean(self, row, col):
        from .base import isspmatrix  # ew...
        # Supporting sparse boolean indexing with both row and col does
        # not work because spmatrix.ndim is always 2.
        if isspmatrix(row) or isspmatrix(col):
            raise IndexError("Indexing with sparse matrices is not supported"
                    " except boolean indexing where matrix and index are equal"
                    " shapes.")
        if isinstance(row, np.ndarray) and row.dtype.kind == 'b':
            row = self._boolean_index_to_array(row)
        if isinstance(col, np.ndarray) and col.dtype.kind == 'b':
            col = self._boolean_index_to_array(col)
        return row, col

    def _boolean_index_to_array(self, i):
        if i.ndim > 1:
            raise IndexError('invalid index shape')
        return i.nonzero()[0]

    def _index_to_arrays(self, i, j):
        i, j = self._check_boolean(i, j)

        i_slice = isinstance(i, slice)
        if i_slice:
            i = self._slicetoarange(i, self.shape[0])[:,None]
        else:
            i = np.atleast_1d(i)

        if isinstance(j, slice):
            j = self._slicetoarange(j, self.shape[1])[None,:]
            if i.ndim == 1:
                i = i[:,None]
            elif not i_slice:
                raise IndexError('index returns 3-dim structure')
        elif isscalarlike(j):
            # row vector special case
            j = np.atleast_1d(j)
            if i.ndim == 1:
                i, j = np.broadcast_arrays(i, j)
                i = i[:, None]
                j = j[:, None]
                return i, j
        else:
            j = np.atleast_1d(j)
            if i_slice and j.ndim > 1:
                raise IndexError('index returns 3-dim structure')

        i, j = np.broadcast_arrays(i, j)

        if i.ndim == 1:
            # return column vectors for 1-D indexing
            i = i[None,:]
            j = j[None,:]
        elif i.ndim > 2:
            raise IndexError("Index dimension must be <= 2")

        return i, j


text:
#ifndef COMMON_UTILS_SINGLETONCLASS_H_
#define COMMON_UTILS_SINGLETONCLASS_H_

// Put this in the private: declarations for a class to be uncopyable.
#define DISALLOW_COPY(TypeName) \
    TypeName(const TypeName&)

// Put this in the private: declarations for a class to be unassignable.
#define DISALLOW_ASSIGN(TypeName) \
    void operator=(const TypeName&)

// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
    TypeName(const TypeName&);               \
    void operator=(const TypeName&)

// A macro to disallow all the implicit constructors, namely the
// default constructor, copy constructor and operator= functions.
//
// This should be used in the private: declarations for a class
// that wants to prevent anyone from instantiating it. This is
// especially useful for classes containing only static methods.
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
    TypeName();                                    \
    DISALLOW_COPY_AND_ASSIGN(TypeName)

/*------------------------------------------------------------------------
template <class T>
class SingletonClassStack

	Inherits From:
		            This method is safer for two reasons:
                     1. At the end of the process it will call the class's
                        destructor
                     2. There is no global initialization race
	Description:

	Data members:

------------------------------------------------------------------------*/
template <class T>
class SingletonClassStack {
public:
   static T& GetInstance() {
      static T obj;
      return obj;
   }

private:
    DISALLOW_IMPLICIT_CONSTRUCTORS(SingletonClassStack);
};

/*------------------------------------------------------------------------
template <class T>
class SingletonClassHeap

	Inherits From:

	Description:

	Data members:

------------------------------------------------------------------------*/
template <class T>
class SingletonClassHeap {
public:
   static T* GetInstance() {
      if (NULL == m_lpObj) {
         m_lpObj = new T;
      }

      return m_lpObj;
   }

   static void DeleteInstance() {
      if (NULL != m_lpObj) {
         delete m_lpObj;
         m_lpObj = NULL;
      }
   }

private:
    DISALLOW_IMPLICIT_CONSTRUCTORS(SingletonClassHeap);

    static T* m_lpObj;
};

template <class T> T* SingletonClassHeap<T>::m_lpObj = NULL;

#endif // COMMON_UTILS_SINGLETONCLASS_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./TestHelper.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         verbose="true"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="true"
         syntaxCheck="true">
    <testsuite name="Booklist - Testsuite">
        <directory>./test</directory>
    </testsuite>
    <filter>
        <blacklist>
            <directory suffix=".php">../tests</directory>
            <directory suffix=".php">../vendor</directory>
        </blacklist>
    </filter>
</phpunit>


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package de.esoco.data.element;

import de.esoco.data.validate.Validator;

import de.esoco.lib.property.PropertyName;

import java.math.BigDecimal;

import java.util.Set;

/********************************************************************
 * A data element implementation for {@link BigDecimal} values.
 *
 * @author eso
 */
public class BigDecimalDataElement extends DataElement<BigDecimal>
{
	//~ Enums ------------------------------------------------------------------

	/********************************************************************
	 * Enumeration of the available display styles.
	 */
	public enum DisplayStyle
	{
		DECIMAL, MULTI_FORMAT, CALCULATOR;
	}

	//~ Static fields/initializers ---------------------------------------------

	private static final long serialVersionUID = 1L;

	/** A style property that defines the rendering of big decimal values. */
	public static final PropertyName<DisplayStyle> DISPLAY_STYLE =
		PropertyName.newEnumName("CALCULATOR", DisplayStyle.class);

	/** The placeholder string for the decimal grouping character. */
	public static final String DECIMAL_GROUP_CHAR = "<dec:grp>";

	/** The placeholder string for the decimal separator character. */
	public static final String DECIMAL_SEPARATOR_CHAR = "<dec:sep>";

	/**
	 * Default input constraint for positive or negative decimal values with
	 * optional grouping characters. Contains the input character placeholders
	 * {@link #DECIMAL_GROUP_CHAR} and {@link #DECIMAL_SEPARATOR_CHAR} which
	 * must be replaced with the actual locale-specific pattern before using the
	 * string as a regular expression.
	 */
	public static final String DEFAULT_CONSTRAINT =
		"-?\\d+(" + DECIMAL_SEPARATOR_CHAR + "\\d*)?";

	/**
	 * Input constraint for positive currency values. To also allow negative
	 * values use {@link #SIGNED_CURRENCY_CONSTRAINT}. See the remarks for
	 * {@link #DEFAULT_CONSTRAINT}.
	 */
	public static final String CURRENCY_CONSTRAINT =
		"\\d+(" + DECIMAL_SEPARATOR_CHAR + "\\d{0,2})?";

	/**
	 * A variant of {@link #CURRENCY_CONSTRAINT} that allows both positive and
	 * negative valuess.
	 */
	public static final String SIGNED_CURRENCY_CONSTRAINT =
		"-?" + CURRENCY_CONSTRAINT;

	//~ Instance fields --------------------------------------------------------

	private BigDecimal aValue;

	//~ Constructors -----------------------------------------------------------

	/***************************************
	 * Creates a new read-only instance with a certain name and value.
	 *
	 * @param sName  The name of this element
	 * @param nValue The initial value
	 */
	public BigDecimalDataElement(String sName, BigDecimal nValue)
	{
		this(sName, nValue, null, null);
	}

	/***************************************
	 * Creates a new instance with a certain initial value and validator.
	 *
	 * @param sName      The name of this element
	 * @param rValue     The initial value
	 * @param rValidator The validator for the value or NULL for none
	 * @param rFlags     The optional flags for this data element
	 */
	public BigDecimalDataElement(String						   sName,
								 BigDecimal					   rValue,
								 Validator<? super BigDecimal> rValidator,
								 Set<Flag>					   rFlags)
	{
		super(sName, rValidator, rFlags);

		this.aValue = rValue;
	}

	/***************************************
	 * Default constructor for serialization.
	 */
	protected BigDecimalDataElement()
	{
	}

	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public BigDecimalDataElement copy(
		CopyMode		   eMode,
		PropertyName<?>... rCopyProperties)
	{
		return (BigDecimalDataElement) super.copy(eMode, rCopyProperties);
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public final BigDecimal getValue()
	{
		return aValue;
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	public void setStringValue(String sValue)
	{
		setValue(new BigDecimal(sValue));
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected BigDecimalDataElement newInstance()
	{
		return new BigDecimalDataElement();
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected void updateValue(BigDecimal rNewValue)
	{
		aValue = rNewValue;
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected boolean valuesEqual(BigDecimal a, BigDecimal b)
	{
		return a == b || (a != null && b != null && a.compareTo(b) == 0);
	}
}


text:
cask 'amanote' do
  version '0.9.7'
  sha256 'c4a6844de39f5b3efc6dc11b34bab5f34e9e6d8eb3ee1fcc87ad6b0a82ade0b4'

  # amazonaws.com/release.amanote.com was verified as official when first introduced to the cask
  url "https://s3-eu-west-1.amazonaws.com/release.amanote.com/beta/v#{version}/Amanote-#{version}.dmg"
  name 'Amanote'
  homepage 'https://amanote.com/'

  app 'Amanote.app'
end


text:
#ifndef __LWIPOPTS_H__
#define __LWIPOPTS_H__

#include "mem_manager.h"
#include "eagle_soc.h"

// Don't change:
#define NO_SYS                              1
#define NO_SYS_NO_TIMERS                    0
#define LWIP_NETIF_TX_SINGLE_PBUF           1
#define LWIP_ESP                            1
#define PBUF_RSV_FOR_WLAN                   1
#define ICACHE_FLASH                        1
#define EBUF_LWIP                           1

// Leave unchanged unless you really know what you're doing:
#define MEM_ALIGNMENT                       4
#define TCP_MSS                             1460
#define TCP_SND_BUF                         (2*TCP_MSS)
#define MEMP_MEM_MALLOC                     1
#define MEM_LIBC_MALLOC                     1

#define MEMP_NUM_TCP_PCB                    (*((volatile uint32*)0x600011FC))
#define LWIP_RAND()                         rand()

#if MEM_LIBC_MALLOC
#define mem_free                            vPortFree
#define mem_malloc                          pvPortMalloc
#define mem_calloc                          pvPortCalloc
#endif

#define MEMCPY(dst,src,len)                 os_memcpy(dst,src,len)
#define SMEMCPY(dst,src,len)                os_memcpy(dst,src,len)

static inline uint32_t sys_now(void)
{
    return NOW()/(TIMER_CLK_FREQ/1000);
}

// For espconn:
#define os_malloc(s)                        pvPortMalloc((s))
#define os_realloc(p, s)                    pvPortRealloc((p), (s))
#define os_zalloc(s)                        pvPortZalloc((s))
#define os_free(p)                          vPortFree((p))

// Required:
#define LWIP_DHCP                           1
#define LWIP_DNS                            1

// Optional:
#define LWIP_IGMP                           1
#define LWIP_NETIF_LOOPBACK                 0
#define LWIP_HAVE_LOOPIF                    0

// Tweakable:
#define ESP_TIMEWAIT_THRESHOLD              10000

#define TCP_TMR_INTERVAL                    125
#define TCP_KEEPIDLE_DEFAULT                3000
#define TCP_KEEPINTVL_DEFAULT               1000
#define TCP_KEEPCNT_DEFAULT                 3

#define LWIP_NETCONN                        0
#define LWIP_SOCKET                         0
#define MEMP_NUM_SYS_TIMEOUT                8

#define TCP_LOCAL_PORT_RANGE_START          0x1000
#define TCP_LOCAL_PORT_RANGE_END            0x7fff
#define UDP_LOCAL_PORT_RANGE_START          0x1000
#define UDP_LOCAL_PORT_RANGE_END            0x7fff

#define ARP_QUEUEING                        1
#define ETHARP_TRUST_IP_MAC                 1
#define IP_FRAG                             0
#define IP_REASSEMBLY                       0
#define IP_FRAG_USES_STATIC_BUF             1
#define TCP_QUEUE_OOSEQ                     0
#define LWIP_TCP_KEEPALIVE                  1
#define LWIP_STATS                          0

#ifdef LWIP_OUR_IF
  #define LWIP_NETIF_HOSTNAME               1 // our eagle_lwip_if.o required
  #define LWIP_NETIF_HOSTNAME_PREFIX        "esp8266-"
#endif

// #define LWIP_DEBUG
// #define IP_DEBUG                            LWIP_DBG_ON

#endif /* __LWIP_OPT_H__ */


text:
title: Calling APIs
description: This tutorial demonstrates how to make secure calls to an API
budicon: 546
---

<%= include('../../../_includes/_package', {
  org: 'auth0-samples',
  repo: 'auth0-ionic-samples',
  path: '07-Calling-Api',
  requirements: [
    'Ionic 1.3.1'
  ]
}) %>

<%= include('../../../_includes/_calling_apis') %>

## JWT Interceptor

To attach the user's JWT as an `Authorization` header, we could write a service that returns a token and attaches it to all HTTP requests. However, the **angular-jwt** library already provides this functionality. Ensure that **angular-jwt** is added to your app as a dependency and configure it with `jwtOptionsProvider` in the `config` block. A `tokenGetter` function needs to be provided to inform **angular-jwt** how it should be retrieving the user's JWT.

```js
// www/app.js

(function () {
  ...
  function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider, $httpProvider) {
    ...
    // Configuration for angular-jwt
    jwtOptionsProvider.config({
      tokenGetter: function() {
        return localStorage.getItem('id_token');
      },
      whiteListedDomains: ['localhost'],
      unauthenticatedRedirectPath: '/login'
    });

    //Push interceptor function to $httpProvider's interceptors
    $httpProvider.interceptors.push('jwtInterceptor');

  }

})();
```

## Not Sending the JWT for Specific Requests

This basic example will attach the JWT as an `Authorization` header to all requests. This may not be desired as some requests don't require authentication. You can choose not to send the JWT by specifying `skipAuthorization: true`.

```js
// www/components/home/home.service.js

(function () {
  ...
  function HomeController($state, authService, $scope, $http, $ionicPopup) {
    var vm = this;
    ...
    vm.ping = ping;
    ...
    function ping() {
    // This request will NOT send the token as it has skipAuthorization
      $http.get(SERVER_PATH + '/ping', { skipAuthorization: true })
        .success(onPingSuccess)
        .error(onPingFail);
    }
    ...
}());
```

## Avoiding Template Requests

Remember that template requests via `ui-router` or `ng-route` are HTTP requests. This means that `Authorization` headers will be attached as well and that might not be needed. You may provide some configuration to avoid sending the JWT for template requests.

```js
// www/app.js

(function () {
  ...
  function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider, $httpProvider) {
    ...
    // Configuration for angular-jwt
    jwtOptionsProvider.config({
      tokenGetter: function(options) {
    // Skip authentication for any requests ending in .html
    if (options.url.substr(options.url.length - 5) == '.html') {
      return null;
    }

        return localStorage.getItem('id_token');
      },
      whiteListedDomains: ['localhost'],
      unauthenticatedRedirectPath: '/login'
    });

    //Push interceptor function to $httpProvider's interceptors
    $httpProvider.interceptors.push('jwtInterceptor');

  }

})();
```

## Different Tokens Based on URLs

If for any reason you would want to send different tokens based on different URLs, you can configure the `tokenGetter` to do so.

```js
// www/app.js

(function () {
  ...
  function config($stateProvider, $urlRouterProvider, lockProvider, jwtOptionsProvider, $httpProvider) {
    ...
    // Configuration for angular-jwt
    jwtOptionsProvider.config({
      tokenGetter: function(options) {
        if (options.url.indexOf('http://auth0.com') === 0) {
          return localStorage.getItem('auth0.id_token');
        } else {
          return localStorage.getItem('id_token');
        }

        return localStorage.getItem('id_token');
      },
      whiteListedDomains: ['localhost'],
      unauthenticatedRedirectPath: '/login'
    });

    //Push interceptor function to $httpProvider's interceptors
    $httpProvider.interceptors.push('jwtInterceptor');

  }

})();
```


text:
How to Install iRedMail on CentOS 7 for Samba4 AD Integration – Part 10
============================================================

This series of tutorials will guide you on how to integrate iRedMail installed on a CentOS 7 machine with a [Samba4 Active Directory Domain Controller][3] in order for domain accounts to send or receive mail via Thunderbird desktop client or via Roundcube web interface.

The CentOS 7 server where iRedMail will be installed will allow SMTP or mail routing services via ports 25 and 587 and will also serve as a mail delivery agent through Dovecot, providing POP3 and IMAP services, both secured with self-signed certificates issued on the installation process.

The recipient mailboxes will be stored on the same CentOS server along with the webmail user agent provided by Roundcube. Samba4 Active Directory will be used by iRedMail to query and authenticate recipient accounts against the realm, to create mail lists with the help of Active Directory groups and to control the mail accounts via Samba4 AD DC.

#### Requirements:

1.  [Create an Active Directory Infrastructure with Samba4 on Ubuntu][1]

### Step 1: Install iRedMail in CentOS 7

1. Before starting with iRedMail installation first make sure you have a fresh CentOS 7 operating system installed on your machine using the instructions provided by this guide:

1.  [Fresh Installation of CentOS 7 Minimal][2]

2. Also, assure that the system is up-to-date with the latest security and packages updates by issuing the below command.

```
# yum update
```

3. The system will also need a FQDN hostname set by issuing the below command. Replace `mail.tecmint.lan` variable with your own custom FQDN.

```
# hostnamectl set-hostname mail.tecmint.lan
```

Verify system hostname with the below commands.

```
# hostname -s   # Short name
# hostname -f   # FQDN
# hostname -d   # Domain
# cat /etc/hostname  # Verify it with cat command
```
[
 ![Verify CentOS 7 Hostname](http://www.tecmint.com/wp-content/uploads/2017/03/Verify-CentOS-7-Hostname.png)
][4]

Verify CentOS 7 Hostname

4. Map the machine FQDN and short name against the machine loopback IP address by manually editing `/etc/hosts` file. Add the values as illustrated below and replace `mail.tecmint.lan` and mail values accordingly.

```
127.0.0.1   mail.tecmint.lan mail  localhost localhost.localdomain
```

5. iRedMail technicians recommends that SELinux should be completely disabled. Disable SELinux by editing /etc/selinux/config file and set SELINUX parameter from `permissive` to `disabled` as illustrated below.

```
SELINUX=disabled
```

Reboot the machine to apply new SELinux policies or run setenforce with 0 parameter to force SELinux to instantly disable.

```
# reboot
OR
# setenforce 0
```

6. Next, install the following packages that will come in-handy later for system administration:

```
# yum install bzip2 net-tools bash-completion wget
```

7. In order to install iRedMail, first go to the download page [http://www.iredmail.org/download.html][5] and grab the latest archive version of the software by issuing the below command.

```
# wget https://bitbucket.org/zhb/iredmail/downloads/iRedMail-0.9.6.tar.bz2
```

8. After the download finishes, extract the compressed archive and enter the extracted iRedMail directory by issuing the following commands.

```
# tar xjf iRedMail-0.9.6.tar.bz2
# cd iRedMail-0.9.6/
# ls
```

9. Start the installation process by executing iRedMail shell script with the following command. From now on a series of questions will be asked by the installer.

```
# bash iRedMail.sh
```

10. On the first welcome prompt hit on `Yes` to proceed further with the installation.

[
 ![iRedMail Setup Wizard](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Setup-Wizard.png)
][6]

iRedMail Setup Wizard

11. Next, choose the location where all the mail will be stored. The default directory that iRedMail uses to store mailboxes is `/var/vmail/` system path.

If this directory is located under a partition with enough storage to host mail for all your domain accounts then hit on Next to continue.

Otherwise change the default location with a different directory in case if you've configured a larger partition dedicated to mail storage.

[
 ![iRedMail Mail Storage Path](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Storage-Path.png)
][7]

iRedMail Mail Storage Path

12. On the next step choose the frontend web server through which you will interact with iRedMail. iRedMail administration panel will be completely disabled later, so we will use the frontend web server only to access accounts mail via Roundcube web panel.

If you don't have thousands of mail accounts per hour accessing the webmail interface you should go with Apache web server do to its flexibility and easy management.

[
 ![iRedMail Preferred Web Server](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Preferred-Web-Server.png)
][8]

iRedMail Preferred Web Server

13. On this step choose OpenLDAP backend database for compatibility reasons with Samba4 domain controller and hit Next to continue, although we won't use this OpenLDAP database later once we'll integrate iRedMail to Samba domain controller.

[
 ![iRedMail LDAP Backend](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-LDAP-Backend.png)
][9]

iRedMail LDAP Backend

14. Next, specify your Samba4 domain name for LDAP suffix as illustrated on the image below and hit Next to continue.

[
 ![iRedMail LDAP Suffix](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-LDAP-Suffix.png)
][10]

iRedMail LDAP Suffix

15. On the next prompt enter your domain name only and hit Next to move on. Replace `tecmint.lan` value accordingly.

[
 ![iRedMail Mail Domain](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Domain.png)
][11]

iRedMail Mail Domain

16. Now, setup a password for `postmaster@yourdomain.tld` administrator and hit Next to continue.

[
 ![iRedMail Mail Domain Administrator](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Domain-Administrator.png)
][12]

iRedMail Mail Domain Administrator

17. Next, choose from the list the optional components you want to integrate with your mail server. I strongly recommend to install Roundcube in order to provide a web interface for domain accounts to access mail, although Roundcube can be installed and configured on a different machine for this task in order to free mail server resources in case of high loads.

For local domains with restricted internet access and especially while we're using domain integration the other components are not very useful, except Awstats in case you need mail analysis.

[
 ![iRedMail Optional Components](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Optional-Components.png)
][13]

iRedMail Optional Components

18. On the next review screen type `Y` in order to apply configuration and start the installation process.

[
 ![iRedMail Configuration Changes](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Configuration-Changes.png)
][14]

iRedMail Configuration Changes

19. Finally, accept iRedMail scripts to automatically configure your machine firewall and MySQL configuration file by typing yes for all questions.

[
 ![iRedMail System Configuration](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-System-Configuration.png)
][15]

iRedMail System Configuration

20. After the installation finishes the installer will provide some sensitive information, such as iRedAdmin credentials, web panel URL addresses and the file location with all parameters used at the installation process.

[
 ![iRedMail Installation Summary](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Installation-Summary.png)
][16]

iRedMail Installation Summary

Read the displayed information above carefully and reboot the machine in order to enable all mail services by issuing the following command.

```
# init 6
```

21. After the system reboots, login with an account with root privileges or as root and list all network sockets and their associated programs your mail server listens on by issuing the following command.

From the socket list you will see that your mail server covers almost all services required by a mail server to properly function: SMTP/S, POP3/S, IMAP/S and antivirus along with spam protection.

```
# netstat -tulpn
```
[
 ![iRedMail Network Sockets](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Network-Sockets.png)
][17]

iRedMail Network Sockets

22. In order to view the location of all configuration files iRedMail has modified and the credentials used by iRedMail during the installation process for database administration, mail admin account and other accounts, display the contents of iRedMail.tips file.

The file is located in the directory where you've initially extracted the installation archive. Be aware that you should move and protect this file because it contains sensitive information about your mail server.

```
# less iRedMail-0.9.6/iRedMail.tips
```

23. The file mentioned above which contain details about your mail server will also be automatically mailed to the mail server administrator account, represented by the postmaster account.

The webmail can be accessed securely via HTTPS protocol by typing your machine IP address in a browser. Accept the error generated in browser by the iRedMail self-signed web certificate and log in with the password chosen for postmaster@your_domain.tld account during the initial installation. Read and store this e-mail to a safe mailbox.

```
https://192.168.1.254
```
[
 ![iRedMail Account Login](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Account-Login.png)
][18]

iRedMail Account Login

[
 ![iRedMail Web Mail](http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Web-Mail.png)
][19]

iRedMail Web Mail

That's all! By now, you'll have a full mail server configured on your premises which operates on its own, but not yet integrated with Samba4 Active Directory Domain Controller services.

On the next part we will see how to tamper iRedMail services (postfix, dovecot and roundcube configuration files) in order to query domain accounts, send, receive and read mail.

--------------------------------------------------------------------------------

作者简介:

I'am a computer addicted guy, a fan of open source and linux based system software, have about 4 years experience with Linux distributions desktop, servers and bash scripting.

--------------------------------------------------------------------------------

via: http://www.tecmint.com/install-iredmail-on-centos-7-for-samba4-ad-integration/

作者:[Matei Cezar][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:http://www.tecmint.com/author/cezarmatei/

[1]:http://www.tecmint.com/install-samba4-active-directory-ubuntu/
[2]:http://www.tecmint.com/centos-7-3-installation-guide/
[3]:http://www.tecmint.com/install-samba4-active-directory-ubuntu/
[4]:http://www.tecmint.com/wp-content/uploads/2017/03/Verify-CentOS-7-Hostname.png
[5]:http://www.iredmail.org/download.html
[6]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Setup-Wizard.png
[7]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Storage-Path.png
[8]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Preferred-Web-Server.png
[9]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-LDAP-Backend.png
[10]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-LDAP-Suffix.png
[11]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Domain.png
[12]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Mail-Domain-Administrator.png
[13]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Optional-Components.png
[14]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Configuration-Changes.png
[15]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-System-Configuration.png
[16]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Installation-Summary.png
[17]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Network-Sockets.png
[18]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Account-Login.png
[19]:http://www.tecmint.com/wp-content/uploads/2017/03/iRedMail-Web-Mail.png
[20]:http://www.tecmint.com/author/cezarmatei/
[21]:http://www.tecmint.com/10-useful-free-linux-ebooks-for-newbies-and-administrators/
[22]:http://www.tecmint.com/free-linux-shell-scripting-books/


text:
export default {
  'caption': 'Search by layer',
  'error-message-caption': 'Search by layer error',
  'error-message-empty-selected-layer': 'Search layer isn\'t selected',
  'approve-button': {
    'caption': 'Search'
  },
  'deny-button': {
    'caption': 'Cancel'
  },
  'layers-dropdown': {
    'caption': 'Search layer'
  },
  'founded-features-segment': {
    'caption': 'Search results',
    'nothing-found-message': 'On your request nothing has been found'
  },
  'show-selected': {
    'caption': 'Show selected objects'
  },
  'show': {
    'caption': 'Show object on map'
  }
};