<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once

namespace s3d
{
	template <class IndexType>
	inline DisjointSet<IndexType>::DisjointSet(const size_t n)
		: m_parents(n)
		, m_sizes(n, 1u)
	{
		assert(n <= MaxSize);

		std::iota(m_parents.begin(), m_parents.end(), static_cast<index_type>(0));
	}

	template <class IndexType>
	inline DisjointSet<IndexType>::operator bool() const noexcept
	{
		return isEmpty();
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::isEmpty() const noexcept
	{
		return m_parents.empty();
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::size() const noexcept
	{
		return m_parents.size();
	}

	template <class IndexType>
	inline typename DisjointSet<IndexType>::index_type DisjointSet<IndexType>::find(index_type i) noexcept
	{
		assert(i < size());

		// Path halving
		while (m_parents[i] != i)
		{
			i = m_parents[i] = m_parents[m_parents[i]];
		}

		return i;
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::connected(const index_type i, const index_type k) noexcept
	{
		return (find(i) == find(k));
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::merge(index_type i, index_type k) noexcept
	{
		i = find(i);
		k = find(k);

		if (i == k) // i and k are already in the same set
		{
			return false;
		}

		if (m_sizes[i] < m_sizes[k])
		{
			using std::swap;
			swap(i, k);
		}

		m_sizes[i] += m_sizes[k];
		m_parents[k] = i;

		return true;
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::size(const index_type i) noexcept
	{
		assert(i < size());

		return m_sizes[find(i)];
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::countSets() const noexcept
	{
		size_t count = 0;

		const size_t size = m_parents.size();

		for (size_t i = 0; i < size; ++i)
		{
			if (static_cast<index_type>(i) == m_parents[i])
			{
				++count;
			}
		}

		return count;
	}

	template <class IndexType>
	inline void DisjointSet<IndexType>::reset() noexcept
	{
		std::iota(m_parents.begin(), m_parents.end(), static_cast<index_type>(0));

		std::fill(m_sizes.begin(), m_sizes.end(), 1u);
	}
}
<commit_msg>[共通] fix warning<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once

namespace s3d
{
	template <class IndexType>
	inline DisjointSet<IndexType>::DisjointSet(const size_t n)
		: m_parents(n)
		, m_sizes(n, 1u)
	{
		assert(n <= MaxSize);

		std::iota(m_parents.begin(), m_parents.end(), static_cast<index_type>(0));
	}

	template <class IndexType>
	inline DisjointSet<IndexType>::operator bool() const noexcept
	{
		return isEmpty();
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::isEmpty() const noexcept
	{
		return m_parents.empty();
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::size() const noexcept
	{
		return m_parents.size();
	}

	template <class IndexType>
	inline typename DisjointSet<IndexType>::index_type DisjointSet<IndexType>::find(index_type i) noexcept
	{
		assert(static_cast<size_t>(i) < size());

		// Path halving
		while (m_parents[i] != i)
		{
			i = m_parents[i] = m_parents[m_parents[i]];
		}

		return i;
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::connected(const index_type i, const index_type k) noexcept
	{
		return (find(i) == find(k));
	}

	template <class IndexType>
	inline bool DisjointSet<IndexType>::merge(index_type i, index_type k) noexcept
	{
		i = find(i);
		k = find(k);

		if (i == k) // i and k are already in the same set
		{
			return false;
		}

		if (m_sizes[i] < m_sizes[k])
		{
			using std::swap;
			swap(i, k);
		}

		m_sizes[i] += m_sizes[k];
		m_parents[k] = i;

		return true;
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::size(const index_type i) noexcept
	{
		assert(static_cast<size_t>(i) < size());

		return m_sizes[find(i)];
	}

	template <class IndexType>
	inline size_t DisjointSet<IndexType>::countSets() const noexcept
	{
		size_t count = 0;

		const size_t size = m_parents.size();

		for (size_t i = 0; i < size; ++i)
		{
			if (static_cast<index_type>(i) == m_parents[i])
			{
				++count;
			}
		}

		return count;
	}

	template <class IndexType>
	inline void DisjointSet<IndexType>::reset() noexcept
	{
		std::iota(m_parents.begin(), m_parents.end(), static_cast<index_type>(0));

		std::fill(m_sizes.begin(), m_sizes.end(), 1u);
	}
}
<|endoftext|>


<commit_before><commit_msg>Gui: sort property by name in property view<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "InetAddress.h"

#include <decaf/lang/System.h>
#include <decaf/lang/Byte.h>
#include <decaf/net/Inet4Address.h>
#include <decaf/net/Inet6Address.h>
#include <decaf/net/UnknownHostException.h>
#include <decaf/lang/exceptions/RuntimeException.h>

#include <apr_network_io.h>
#include <decaf/internal/AprPool.h>

using namespace decaf;
using namespace decaf::net;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::internal;

////////////////////////////////////////////////////////////////////////////////
const unsigned char InetAddress::loopbackBytes[4] = { 127, 0, 0, 1 };
const unsigned char InetAddress::anyBytes[4] = { 0, 0, 0, 0 };

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress() : hostname(), reached(false), addressBytes() {
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress(const unsigned char* ipAddress, int numBytes) :
        hostname(), reached(false), addressBytes() {

    if (ipAddress == NULL) {
        throw NullPointerException(__FILE__, __LINE__, "InetAddress constructor called with null address array.");
    }

    if (numBytes < 0) {
        throw IllegalArgumentException(__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes);
    }

    unsigned char* copy = new unsigned char[numBytes];
    System::arraycopy(ipAddress, 0, copy, 0, numBytes);
    this->addressBytes.reset(copy, numBytes);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress(const std::string& hostname, const unsigned char* ipAddress, int numBytes) :
        hostname(hostname), reached(false), addressBytes() {

    if (ipAddress == NULL) {
        throw NullPointerException(__FILE__, __LINE__, "InetAddress constructor called with null address array.");
    }

    if (numBytes < 0) {
        throw IllegalArgumentException(__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes);
    }

    unsigned char* copy = new unsigned char[numBytes];
    System::arraycopy(ipAddress, 0, copy, 0, numBytes);
    this->addressBytes.reset(copy, numBytes);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::~InetAddress() {
}

////////////////////////////////////////////////////////////////////////////////
InetAddress* InetAddress::clone() const {
    return new InetAddress(*this);
}

////////////////////////////////////////////////////////////////////////////////
ArrayPointer<unsigned char> InetAddress::getAddress() const {
    return this->addressBytes.clone();
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostAddress() const {

    std::string address;

    for (int ix = 0; ix < this->addressBytes.length(); ix++) {
        address.append(Byte::toString(addressBytes[ix]));

        if (ix < this->addressBytes.length() - 1) {
            address.append(".");
        }
    }
    return address;
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostName() const {

    if (!this->hostname.empty()) {
        return this->hostname;
    }

    return this->getHostAddress();
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::toString() const {
    return getHostName() + " / " + getHostAddress();
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress(const std::string& hostname, const unsigned char* bytes, int numBytes) {

    if (numBytes == 4) {
        return Inet4Address(hostname, bytes, numBytes);
    } else if (numBytes == 16) {
        return Inet6Address(hostname, bytes, numBytes);
    } else {
        throw UnknownHostException(__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes);
    }
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress(const unsigned char* bytes, int numBytes) {

    if (numBytes == 4) {
        return Inet4Address(bytes, numBytes);
    } else if (numBytes == 16) {
        return Inet6Address(bytes, numBytes);
    } else {
        throw UnknownHostException(__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes);
    }
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLocalHost() {

    char hostname[APRMAXHOSTLEN + 1] = { 0 };

    try {

        AprPool pool;
        apr_status_t result = APR_SUCCESS;

        try {

            result = apr_gethostname(hostname, APRMAXHOSTLEN + 1, pool.getAprPool());

            if (result != APR_SUCCESS) {
                return getLoopbackAddress();
            }

        } catch (...) {
        }

        apr_sockaddr_t* address = NULL;
        result = apr_sockaddr_info_get(&address, hostname, APR_UNSPEC, 0, APR_IPV4_ADDR_OK, pool.getAprPool());

        if (result != APR_SUCCESS) {
            throw UnknownHostException(__FILE__, __LINE__, "Could not resolve the IP Address of this host.");
        }

        if (address->family == APR_INET) {
            return Inet4Address(hostname, (const unsigned char*) address->ipaddr_ptr, address->ipaddr_len);
        } else {
            return Inet6Address(hostname, (const unsigned char*) address->ipaddr_ptr, address->ipaddr_len);
        }
    }
    DECAF_CATCH_RETHROW( UnknownHostException)
    DECAF_CATCH_EXCEPTION_CONVERT( Exception, UnknownHostException)
    DECAF_CATCHALL_THROW( UnknownHostException)
}

////////////////////////////////////////////////////////////////////////////////
unsigned int InetAddress::bytesToInt(const unsigned char* bytes, int start) {

    // First mask the byte with 255, as when a negative
    // signed byte converts to an integer, it has bits
    // on in the first 3 bytes, we are only concerned
    // about the right-most 8 bits.
    // Then shift the rightmost byte to align with its
    // position in the integer.
    int value = ((bytes[start + 3] & 255)) | ((bytes[start + 2] & 255) << 8) | ((bytes[start + 1] & 255) << 16) | ((bytes[start] & 255) << 24);

    return value;
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getAnyAddress() {
    return Inet4Address("localhost", InetAddress::loopbackBytes, 4);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLoopbackAddress() {
    return Inet4Address(InetAddress::anyBytes, 4);
}
<commit_msg>https://issues.apache.org/jira/browse/AMQCPP-550<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "InetAddress.h"

#include <decaf/lang/System.h>
#include <decaf/lang/Byte.h>
#include <decaf/net/Inet4Address.h>
#include <decaf/net/Inet6Address.h>
#include <decaf/net/UnknownHostException.h>
#include <decaf/lang/exceptions/RuntimeException.h>

#include <apr_network_io.h>
#include <decaf/internal/AprPool.h>

using namespace decaf;
using namespace decaf::net;
using namespace decaf::lang;
using namespace decaf::lang::exceptions;
using namespace decaf::internal;

////////////////////////////////////////////////////////////////////////////////
const unsigned char InetAddress::loopbackBytes[4] = { 127, 0, 0, 1 };
const unsigned char InetAddress::anyBytes[4] = { 0, 0, 0, 0 };

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress() : hostname(), reached(false), addressBytes() {
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress(const unsigned char* ipAddress, int numBytes) :
        hostname(), reached(false), addressBytes() {

    if (ipAddress == NULL) {
        throw NullPointerException(__FILE__, __LINE__, "InetAddress constructor called with null address array.");
    }

    if (numBytes < 0) {
        throw IllegalArgumentException(__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes);
    }

    unsigned char* copy = new unsigned char[numBytes];
    System::arraycopy(ipAddress, 0, copy, 0, numBytes);
    this->addressBytes.reset(copy, numBytes);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::InetAddress(const std::string& hostname, const unsigned char* ipAddress, int numBytes) :
        hostname(hostname), reached(false), addressBytes() {

    if (ipAddress == NULL) {
        throw NullPointerException(__FILE__, __LINE__, "InetAddress constructor called with null address array.");
    }

    if (numBytes < 0) {
        throw IllegalArgumentException(__FILE__, __LINE__, "Number of bytes value is invalid: %d", numBytes);
    }

    unsigned char* copy = new unsigned char[numBytes];
    System::arraycopy(ipAddress, 0, copy, 0, numBytes);
    this->addressBytes.reset(copy, numBytes);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress::~InetAddress() {
}

////////////////////////////////////////////////////////////////////////////////
InetAddress* InetAddress::clone() const {
    return new InetAddress(*this);
}

////////////////////////////////////////////////////////////////////////////////
ArrayPointer<unsigned char> InetAddress::getAddress() const {
    return this->addressBytes.clone();
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostAddress() const {

    std::string address;

    for (int ix = 0; ix < this->addressBytes.length(); ix++) {
        address.append(Byte::toString(addressBytes[ix]));

        if (ix < this->addressBytes.length() - 1) {
            address.append(".");
        }
    }
    return address;
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::getHostName() const {

    if (!this->hostname.empty()) {
        return this->hostname;
    }

    return this->getHostAddress();
}

////////////////////////////////////////////////////////////////////////////////
std::string InetAddress::toString() const {
    return getHostName() + " / " + getHostAddress();
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress(const std::string& hostname, const unsigned char* bytes, int numBytes) {

    if (numBytes == 4) {
        return Inet4Address(hostname, bytes, numBytes);
    } else if (numBytes == 16) {
        return Inet6Address(hostname, bytes, numBytes);
    } else {
        throw UnknownHostException(__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes);
    }
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getByAddress(const unsigned char* bytes, int numBytes) {

    if (numBytes == 4) {
        return Inet4Address(bytes, numBytes);
    } else if (numBytes == 16) {
        return Inet6Address(bytes, numBytes);
    } else {
        throw UnknownHostException(__FILE__, __LINE__, "Number of Bytes passed was invalid: %d", numBytes);
    }
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLocalHost() {

    char hostname[APRMAXHOSTLEN + 1] = { 0 };

    try {

        AprPool pool;
        apr_status_t result = APR_SUCCESS;

        try {

            result = apr_gethostname(hostname, APRMAXHOSTLEN + 1, pool.getAprPool());

            if (result != APR_SUCCESS) {
                return getLoopbackAddress();
            }

        } catch (...) {
        }

        apr_sockaddr_t* address = NULL;
        result = apr_sockaddr_info_get(&address, hostname, APR_UNSPEC, 0, APR_IPV4_ADDR_OK, pool.getAprPool());

        if (result != APR_SUCCESS || address == NULL) {
            throw UnknownHostException(__FILE__, __LINE__, "Could not resolve the IP Address of this host.");
        }

        if (address->family == APR_INET) {
            return Inet4Address(hostname, (const unsigned char*) address->ipaddr_ptr, address->ipaddr_len);
        } else {
            return Inet6Address(hostname, (const unsigned char*) address->ipaddr_ptr, address->ipaddr_len);
        }
    }
    DECAF_CATCH_RETHROW( UnknownHostException)
    DECAF_CATCH_EXCEPTION_CONVERT( Exception, UnknownHostException)
    DECAF_CATCHALL_THROW( UnknownHostException)
}

////////////////////////////////////////////////////////////////////////////////
unsigned int InetAddress::bytesToInt(const unsigned char* bytes, int start) {

    // First mask the byte with 255, as when a negative
    // signed byte converts to an integer, it has bits
    // on in the first 3 bytes, we are only concerned
    // about the right-most 8 bits.
    // Then shift the rightmost byte to align with its
    // position in the integer.
    int value = ((bytes[start + 3] & 255)) | ((bytes[start + 2] & 255) << 8) | ((bytes[start + 1] & 255) << 16) | ((bytes[start] & 255) << 24);

    return value;
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getAnyAddress() {
    return Inet4Address("localhost", InetAddress::loopbackBytes, 4);
}

////////////////////////////////////////////////////////////////////////////////
InetAddress InetAddress::getLoopbackAddress() {
    return Inet4Address(InetAddress::anyBytes, 4);
}
<|endoftext|>


<commit_before>//
// Created by 欧文韬 on 2015/7/5.
//

#ifdef _MSC_VER
#include <winsock2.h>
#else
#include <sys/time.h>
#endif

#include <assert.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include <ctime>
#include <algorithm>

#include "hiredis_happ.h"

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
#include "hiredis/adapters/libuv.h"
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
#include "hiredis/adapters/libevent.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if defined(_MSC_VER)
    #include <winsock2.h>
    #include <process.h>
    #include <sys/locking.h>
    #include <Windows.h>
    #define THREAD_SPIN_COUNT 2000

    typedef HANDLE thread_t;
    #define THREAD_FUNC unsigned __stdcall
    #define THREAD_CREATE(threadvar, fn, arg) do { \
        uintptr_t threadhandle = _beginthreadex(NULL,0,fn,(arg),0,NULL); \
        (threadvar) = (thread_t) threadhandle; \
    } while (0)
    #define THREAD_JOIN(th) WaitForSingleObject(th, INFINITE)
    #define THREAD_RETURN return (0)

    #define THREAD_SLEEP_MS(TM) Sleep(TM)
#elif defined(__GNUC__) || defined(__clang__)
#include <pthread.h>
#include <errno.h>
#include <unistd.h>

typedef pthread_t thread_t;
#define THREAD_FUNC void*
#define THREAD_CREATE(threadvar, fn, arg) \
        pthread_create(&(threadvar), NULL, fn, arg)
#define THREAD_JOIN(th) pthread_join(th, NULL)
#define THREAD_RETURN pthread_exit (NULL); return NULL

#define THREAD_SLEEP_MS(TM) ((TM > 1000)? sleep(TM / 1000): usleep(0)); usleep((TM % 1000) * 1000)
#endif

#ifdef __cplusplus
}
#endif

static hiredis::happ::cluster g_clu;

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
static uv_loop_t* main_loop;
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
static event_base* main_loop;
#endif

static pthread_mutex_t g_mutex;
static std::list<std::string> g_cmds;

static void on_connect_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn) {
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    redisLibuvAttach(conn->get_context(), main_loop);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    redisLibeventAttach(conn->get_context(), main_loop);
#endif

    if (NULL != conn) {
        printf("start connect to %s\n", conn->get_key().name.c_str());
    } else {
        printf("error: connection not found when connect\n");
    }
}

static void on_connected_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn, const struct redisAsyncContext* c, int status) {
    if (NULL == conn) {
        printf("error: connection not found when connected\n");
        return;
    }

    if (REDIS_OK == status) {
        printf("%s connected success\n", conn->get_key().name.c_str());
    } else {
        char no_msg[] = "none";
        printf("%s connected failed, status %d, err: %d, msg %s\n",
           conn->get_key().name.c_str(),
           status, c? c->err: 0,
           (c && c->errstr)? c->errstr: no_msg
        );
    }
}

static void on_disconnected_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn, const struct redisAsyncContext* c, int status) {
    if (NULL == conn) {
        printf("error: connection not found when connected\n");
        return;
    }

    if (REDIS_OK == status) {
        printf("%s disconnected\n", conn->get_key().name.c_str());
    } else {
        char no_msg[] = "none";
        printf("%s disconnected status %d, err: %d, msg %s\n",
               conn->get_key().name.c_str(),
               status, c? c->err: 0,
               (c && c->errstr)? c->errstr: no_msg
        );
    }
}

static std::vector<std::string> split_word(const std::string& cmd_line) {
    std::vector<std::string> ret;

    std::string seg;
    for(size_t i = 0; i < cmd_line.size(); ++ i) {
        if (cmd_line[i] == '\r' || cmd_line[i] == '\n' || cmd_line[i] == '\t' || cmd_line[i] == ' ') {
            if(seg.empty()) {
                continue;
            }

            ret.push_back(seg);
            seg.clear();
        } else {
            char c = cmd_line[i];
            if ('\'' == c || '\"' == c) {
                for (++ i; i < cmd_line.size() && c != cmd_line[i]; ++ i) {
                    if (c == '\"' && '\\' == cmd_line[i]) {
                        ++ i;
                        if (i < cmd_line.size()) {
                            seg.push_back(cmd_line[i]);
                        }
                    } else {
                        seg.push_back(cmd_line[i]);
                    }
                }

                ++ i;
            } else {
                seg.push_back(c);
            }
        }
    }

    if(!seg.empty()) {
        ret.push_back(seg);
    }

    return ret;
}

static void dump_callback(hiredis::happ::cmd_exec* cmd, struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(dump_callback));

    if (cmd->result() != hiredis::happ::error_code::REDIS_HAPP_OK) {
        printf("cmd_exec result: %d\n", cmd->result());
    }
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void subscribe_callback(struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(subscribe_callback));

    printf(" ===== subscribe message received =====\n");
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void monitor_callback(struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(monitor_callback));

    printf(" ----- monitor message received ----- \n");
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void on_timer_proc(
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_timer_t* handle
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    evutil_socket_t fd, short event, void *arg
#endif
) {
    static time_t sec = time(NULL);
    static time_t usec = 0;

    usec += 100000;
    if (usec > 10000000) {
        sec += usec / 10000000;
        usec %= 10000000;
    }

    // 提取命令
    pthread_mutex_lock(&g_mutex);
    std::list<std::string> pending_cmds;
    if(!g_cmds.empty()) {
        pending_cmds.swap(g_cmds);
    }
    pthread_mutex_unlock(&g_mutex);

    // 执行命令
    while(!pending_cmds.empty()) {
        std::string cmd_line = pending_cmds.front();
        pending_cmds.pop_front();

        std::vector<std::string> cmds = split_word(cmd_line);
        std::string cmd = cmds.empty()? "": cmds.front();
        std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
        hiredis::happ::cmd_exec::callback_fn_t cbk = dump_callback;
        bool is_raw = false;
        int k = 1;
        if ("INFO" == cmd || "MULTI" == cmd || "EXEC" == cmd || "SLAVEOF" == cmd || "CONFIG" == cmd || "SHUTDOWN" == cmd ||
            "CLUSTER" == cmd) {
            k = -1;
        } else if ("SCRIPT" == cmd) {
            k = -1;
        } else if ("EVALSHA" == cmd || "EVAL" == cmd) {
            k = 3;
        } else if ("SUBSCRIBE" == cmd || "UNSUBSCRIBE" == cmd || "PSUBSCRIBE" == cmd || "PUNSUBSCRIBE" == cmd) {
            cbk = subscribe_callback;
            is_raw = true;
        } else if ("MONITOR" == cmd) {
            cbk = monitor_callback;
            is_raw = true;
        }

        // 生成参数
        std::vector<const char*> pc;
        std::vector<size_t> ps;
        for(size_t i = 0; i < cmds.size(); ++ i) {
            pc.push_back(cmds[i].c_str());
            ps.push_back(cmds[i].size());
        }

        if (is_raw) { // 执行特殊命令

            const hiredis::happ::cluster::slot_t* slot_info = NULL;
            if (cmds.size() > 1) {
                slot_info = g_clu.get_slot_by_key(cmds[1].c_str(), cmds[1].size());
                assert(slot_info);
            }

            const hiredis::happ::connection::key_t* conn_key = g_clu.get_slot_master(NULL == slot_info? -1: slot_info->index);
            if (NULL == conn_key) {
                printf("connection not found.\n");
                continue;
            }

            hiredis::happ::connection_t* conn = g_clu.get_connection(conn_key->name);
            if (NULL == conn) {
                conn = g_clu.make_connection(*conn_key);
            }

            if (NULL == conn) {
                printf("connect to %s failed.\n", conn_key->name.c_str());
                continue;
            }
            conn->redis_raw_cmd(cbk, static_cast<int>(cmds.size()), &pc[0], &ps[0]);

        } else { // 执行请求-回包命令
            if (k >= 0 && k < static_cast<int>(cmds.size())) {
                cmd = cmds[k];
                g_clu.exec(cmd.c_str(), cmd.size(), cbk, reinterpret_cast<void*>(cbk), static_cast<int>(cmds.size()), &pc[0], &ps[0]);
            } else {
                g_clu.exec(NULL, 0, cbk, reinterpret_cast<void*>(cbk), static_cast<int>(cmds.size()), &pc[0], &ps[0]);
            }
        }
    }

    g_clu.proc(sec, usec);
}

static THREAD_FUNC proc_uv_thd(void *) {
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_run(main_loop, UV_RUN_DEFAULT);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    event_base_dispatch(main_loop);
#endif

    THREAD_RETURN;
}

static void on_log_fn(const char* content) {
    puts(content);
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        printf("usage: %s <ip> <port>\n", argv[0]);
        return 0;
    }

#ifdef _MSC_VER
    {
        WORD wVersionRequested;
        WSADATA wsaData;

        wVersionRequested = MAKEWORD(2, 2);

        (void)WSAStartup(wVersionRequested, &wsaData);
    }
#endif

    const char* ip = argv[1];
    long lport = 0;
    lport = strtol(argv[2], NULL, 10);
    uint16_t port = static_cast<uint16_t>(lport);

    g_clu.init(ip, port);

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    main_loop = uv_default_loop();
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    main_loop = event_init();
#endif

    // 事件分发器
    g_clu.set_on_connect(on_connect_cbk);
    g_clu.set_on_connected(on_connected_cbk);
    g_clu.set_on_disconnected(on_disconnected_cbk);
    g_clu.set_timeout(5); // 测试工具，5秒超时

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    // 设置定时器
    uv_timer_t timer_obj;
    uv_timer_init(main_loop, &timer_obj);
    uv_timer_start(&timer_obj, on_timer_proc, 1000, 100);

#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    // 设置定时器
    struct timeval tv;
    struct event ev;
    event_assign(&ev, main_loop, -1, EV_PERSIST, on_timer_proc, NULL);
    tv.tv_sec = 0;
    tv.tv_usec = 100000;
    evtimer_add(&ev, &tv);
#endif

    // 设置日志
    g_clu.set_log_writer(on_log_fn, on_log_fn, 65536);

    g_clu.start();

    thread_t uv_thd;
    pthread_mutex_init(&g_mutex, NULL);
    THREAD_CREATE(uv_thd, proc_uv_thd, NULL);

    std::string cmd;
    while(std::getline(std::cin, cmd)) {
        if (cmd.empty()) {
            continue;
        }

        // 追加命令
        pthread_mutex_lock(&g_mutex);
        g_cmds.push_back(cmd);
        pthread_mutex_unlock(&g_mutex);

        cmd.clear();
    }

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_stop(main_loop);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    event_base_loopbreak(main_loop);
#endif

    THREAD_JOIN(uv_thd);
    pthread_mutex_destroy(&g_mutex);

    g_clu.reset();

    return 0;
}
<commit_msg>fix sample compile problem<commit_after>//
// Created by 欧文韬 on 2015/7/5.
//

#ifdef _MSC_VER
#include <winsock2.h>
#else
#include <sys/time.h>
#endif

#include <assert.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include <ctime>
#include <algorithm>

#include "hiredis_happ.h"

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
#include "hiredis/adapters/libuv.h"
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
#include "hiredis/adapters/libevent.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if defined(_MSC_VER)
    #include <winsock2.h>
    #include <process.h>
    #include <sys/locking.h>
    #include <Windows.h>
    #define THREAD_SPIN_COUNT 2000

    typedef HANDLE thread_t;
    #define THREAD_FUNC unsigned __stdcall
    #define THREAD_CREATE(threadvar, fn, arg) do { \
        uintptr_t threadhandle = _beginthreadex(NULL,0,fn,(arg),0,NULL); \
        (threadvar) = (thread_t) threadhandle; \
    } while (0)
    #define THREAD_JOIN(th) WaitForSingleObject(th, INFINITE)
    #define THREAD_RETURN return (0)

    #define THREAD_SLEEP_MS(TM) Sleep(TM)
#elif defined(__GNUC__) || defined(__clang__)
#include <pthread.h>
#include <errno.h>
#include <unistd.h>

typedef pthread_t thread_t;
#define THREAD_FUNC void*
#define THREAD_CREATE(threadvar, fn, arg) \
        pthread_create(&(threadvar), NULL, fn, arg)
#define THREAD_JOIN(th) pthread_join(th, NULL)
#define THREAD_RETURN pthread_exit (NULL); return NULL

#define THREAD_SLEEP_MS(TM) ((TM > 1000)? sleep(TM / 1000): usleep(0)); usleep((TM % 1000) * 1000)
#endif

#ifdef __cplusplus
}
#endif

static hiredis::happ::cluster g_clu;

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
static uv_loop_t* main_loop;
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
static event_base* main_loop;
#endif

static pthread_mutex_t g_mutex;
static std::list<std::string> g_cmds;

static void on_connect_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn) {
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    redisLibuvAttach(conn->get_context(), main_loop);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    redisLibeventAttach(conn->get_context(), main_loop);
#endif

    if (NULL != conn) {
        printf("start connect to %s\n", conn->get_key().name.c_str());
    } else {
        printf("error: connection not found when connect\n");
    }
}

static void on_connected_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn, const struct redisAsyncContext* c, int status) {
    if (NULL == conn) {
        printf("error: connection not found when connected\n");
        return;
    }

    if (REDIS_OK == status) {
        printf("%s connected success\n", conn->get_key().name.c_str());
    } else {
        char no_msg[] = "none";
        printf("%s connected failed, status %d, err: %d, msg %s\n",
           conn->get_key().name.c_str(),
           status, c? c->err: 0,
           (c && c->errstr)? c->errstr: no_msg
        );
    }
}

static void on_disconnected_cbk(hiredis::happ::cluster*, hiredis::happ::connection* conn, const struct redisAsyncContext* c, int status) {
    if (NULL == conn) {
        printf("error: connection not found when connected\n");
        return;
    }

    if (REDIS_OK == status) {
        printf("%s disconnected\n", conn->get_key().name.c_str());
    } else {
        char no_msg[] = "none";
        printf("%s disconnected status %d, err: %d, msg %s\n",
               conn->get_key().name.c_str(),
               status, c? c->err: 0,
               (c && c->errstr)? c->errstr: no_msg
        );
    }
}

static std::vector<std::string> split_word(const std::string& cmd_line) {
    std::vector<std::string> ret;

    std::string seg;
    for(size_t i = 0; i < cmd_line.size(); ++ i) {
        if (cmd_line[i] == '\r' || cmd_line[i] == '\n' || cmd_line[i] == '\t' || cmd_line[i] == ' ') {
            if(seg.empty()) {
                continue;
            }

            ret.push_back(seg);
            seg.clear();
        } else {
            char c = cmd_line[i];
            if ('\'' == c || '\"' == c) {
                for (++ i; i < cmd_line.size() && c != cmd_line[i]; ++ i) {
                    if (c == '\"' && '\\' == cmd_line[i]) {
                        ++ i;
                        if (i < cmd_line.size()) {
                            seg.push_back(cmd_line[i]);
                        }
                    } else {
                        seg.push_back(cmd_line[i]);
                    }
                }

                ++ i;
            } else {
                seg.push_back(c);
            }
        }
    }

    if(!seg.empty()) {
        ret.push_back(seg);
    }

    return ret;
}

static void dump_callback(hiredis::happ::cmd_exec* cmd, struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(dump_callback));

    if (cmd->result() != hiredis::happ::error_code::REDIS_HAPP_OK) {
        printf("cmd_exec result: %d\n", cmd->result());
    }
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void subscribe_callback(struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(subscribe_callback));

    printf(" ===== subscribe message received =====\n");
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void monitor_callback(struct redisAsyncContext*, void* r, void* p) {
    assert(p == reinterpret_cast<void*>(monitor_callback));

    printf(" ----- monitor message received ----- \n");
    g_clu.dump(std::cout, reinterpret_cast<redisReply*>(r), 0);
}

static void on_timer_proc(
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_timer_t* handle
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    evutil_socket_t fd, short event, void *arg
#endif
) {
    static time_t sec = time(NULL);
    static time_t usec = 0;

    usec += 100000;
    if (usec > 10000000) {
        sec += usec / 10000000;
        usec %= 10000000;
    }

    // 提取命令
    pthread_mutex_lock(&g_mutex);
    std::list<std::string> pending_cmds;
    if(!g_cmds.empty()) {
        pending_cmds.swap(g_cmds);
    }
    pthread_mutex_unlock(&g_mutex);

    // 执行命令
    while(!pending_cmds.empty()) {
        std::string cmd_line = pending_cmds.front();
        pending_cmds.pop_front();

        std::vector<std::string> cmds = split_word(cmd_line);
        std::string cmd = cmds.empty()? "": cmds.front();
        std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::toupper);
        hiredis::happ::cmd_exec::callback_fn_t cbk = dump_callback;
        redisCallbackFn raw_cbk = NULL;
        bool is_raw = false;
        int k = 1;
        if ("INFO" == cmd || "MULTI" == cmd || "EXEC" == cmd || "SLAVEOF" == cmd || "CONFIG" == cmd || "SHUTDOWN" == cmd ||
            "CLUSTER" == cmd) {
            k = -1;
        } else if ("SCRIPT" == cmd) {
            k = -1;
        } else if ("EVALSHA" == cmd || "EVAL" == cmd) {
            k = 3;
        } else if ("SUBSCRIBE" == cmd || "UNSUBSCRIBE" == cmd || "PSUBSCRIBE" == cmd || "PUNSUBSCRIBE" == cmd) {
            raw_cbk = subscribe_callback;
            is_raw = true;
        } else if ("MONITOR" == cmd) {
            raw_cbk = monitor_callback;
            is_raw = true;
        }

        // 生成参数
        std::vector<const char*> pc;
        std::vector<size_t> ps;
        for(size_t i = 0; i < cmds.size(); ++ i) {
            pc.push_back(cmds[i].c_str());
            ps.push_back(cmds[i].size());
        }

        if (is_raw) { // 执行特殊命令

            const hiredis::happ::cluster::slot_t* slot_info = NULL;
            if (cmds.size() > 1) {
                slot_info = g_clu.get_slot_by_key(cmds[1].c_str(), cmds[1].size());
                assert(slot_info);
            }

            const hiredis::happ::connection::key_t* conn_key = g_clu.get_slot_master(NULL == slot_info? -1: slot_info->index);
            if (NULL == conn_key) {
                printf("connection not found.\n");
                continue;
            }

            hiredis::happ::connection* conn = g_clu.get_connection(conn_key->name);
            if (NULL == conn) {
                conn = g_clu.make_connection(*conn_key);
            }

            if (NULL == conn) {
                printf("connect to %s failed.\n", conn_key->name.c_str());
                continue;
            }
            conn->redis_raw_cmd(raw_cbk, raw_cbk, static_cast<int>(cmds.size()), &pc[0], &ps[0]);

        } else { // 执行请求-回包命令
            if (k >= 0 && k < static_cast<int>(cmds.size())) {
                cmd = cmds[k];
                g_clu.exec(cmd.c_str(), cmd.size(), cbk, reinterpret_cast<void*>(cbk), static_cast<int>(cmds.size()), &pc[0], &ps[0]);
            } else {
                g_clu.exec(NULL, 0, cbk, reinterpret_cast<void*>(cbk), static_cast<int>(cmds.size()), &pc[0], &ps[0]);
            }
        }
    }

    g_clu.proc(sec, usec);
}

static THREAD_FUNC proc_uv_thd(void *) {
#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_run(main_loop, UV_RUN_DEFAULT);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    event_base_dispatch(main_loop);
#endif

    THREAD_RETURN;
}

static void on_log_fn(const char* content) {
    puts(content);
}

int main(int argc, char* argv[]) {
    if (argc < 3) {
        printf("usage: %s <ip> <port>\n", argv[0]);
        return 0;
    }

#ifdef _MSC_VER
    {
        WORD wVersionRequested;
        WSADATA wsaData;

        wVersionRequested = MAKEWORD(2, 2);

        (void)WSAStartup(wVersionRequested, &wsaData);
    }
#endif

    const char* ip = argv[1];
    long lport = 0;
    lport = strtol(argv[2], NULL, 10);
    uint16_t port = static_cast<uint16_t>(lport);

    g_clu.init(ip, port);

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    main_loop = uv_default_loop();
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    main_loop = event_init();
#endif

    // 事件分发器
    g_clu.set_on_connect(on_connect_cbk);
    g_clu.set_on_connected(on_connected_cbk);
    g_clu.set_on_disconnected(on_disconnected_cbk);
    g_clu.set_timeout(5); // 测试工具，5秒超时

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    // 设置定时器
    uv_timer_t timer_obj;
    uv_timer_init(main_loop, &timer_obj);
    uv_timer_start(&timer_obj, on_timer_proc, 1000, 100);

#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    // 设置定时器
    struct timeval tv;
    struct event ev;
    event_assign(&ev, main_loop, -1, EV_PERSIST, on_timer_proc, NULL);
    tv.tv_sec = 0;
    tv.tv_usec = 100000;
    evtimer_add(&ev, &tv);
#endif

    // 设置日志
    g_clu.set_log_writer(on_log_fn, on_log_fn, 65536);

    g_clu.start();

    thread_t uv_thd;
    pthread_mutex_init(&g_mutex, NULL);
    THREAD_CREATE(uv_thd, proc_uv_thd, NULL);

    std::string cmd;
    while(std::getline(std::cin, cmd)) {
        if (cmd.empty()) {
            continue;
        }

        // 追加命令
        pthread_mutex_lock(&g_mutex);
        g_cmds.push_back(cmd);
        pthread_mutex_unlock(&g_mutex);

        cmd.clear();
    }

#if defined(HIREDIS_HAPP_ENABLE_LIBUV)
    uv_stop(main_loop);
#elif defined(HIREDIS_HAPP_ENABLE_LIBEVENT)
    event_base_loopbreak(main_loop);
#endif

    THREAD_JOIN(uv_thd);
    pthread_mutex_destroy(&g_mutex);

    g_clu.reset();

    return 0;
}
<|endoftext|>


<commit_before>#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/io/GML.hh>

#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/utilities/Filesystem.hh>

#include <iostream>
#include <map>
#include <regex>
#include <string>
#include <vector>

int main( int argc, char** argv )
{
  if( argc <= 1 )
    return -1;

  using DataType          = double;
  using VertexType        = unsigned short;
  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  std::vector<std::string> filenames;

  for( int i = 1; i < argc; i++ )
    filenames.push_back( argv[i] );

  aleph::topology::io::GMLReader reader;

  // Maps a data set ID to its corresponding Betti number. This is
  // required in order to generate a curve that measures how these
  // numbers change.
  std::map<unsigned, unsigned> id_to_betti;

  for( auto&& filename : filenames )
  {
    std::cerr << "* Processing " << filename << "...";

    SimplicialComplex K;
    reader( filename, K );

    K.sort();

    bool dualize                    = true;
    bool includeAllUnpairedCreators = true;

    auto diagrams
      = aleph::calculatePersistenceDiagrams( K,
                                             dualize,
                                             includeAllUnpairedCreators );

    std::cerr << "finished\n";

    auto basename
      = aleph::utilities::basename( filename );

    std::regex reDataSetSuffix( "\\D*([[:digit:]]+).*" );
    std::smatch matches;

    if( std::regex_match( basename, matches, reDataSetSuffix ) )
    {
      unsigned id = static_cast<unsigned>( std::stoull( matches[1] ) );

      if( diagrams.size() >= 2 )
        id_to_betti[id] = static_cast<unsigned>( diagrams[1].betti() );
      else
        id_to_betti[id] = static_cast<unsigned>( 0 );
    }
    else
      throw std::runtime_error( "Unable to identify ID" );
  }

  std::cerr << "* Obtained " << id_to_betti.size() << " data sets\n";

  for( auto&& pair : id_to_betti )
    std::cout << pair.first << "\t" << pair.second << "\n";

  std::cout << "\n\n";
}
<commit_msg>Decreased verbosity of Betti number calculation<commit_after>#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/io/GML.hh>

#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>

#include <aleph/utilities/Filesystem.hh>

#include <iostream>
#include <map>
#include <regex>
#include <string>
#include <vector>

int main( int argc, char** argv )
{
  if( argc <= 1 )
    return -1;

  bool verbose            = false;

  using DataType          = double;
  using VertexType        = unsigned short;
  using Simplex           = aleph::topology::Simplex<DataType, VertexType>;
  using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;

  std::vector<std::string> filenames;

  for( int i = 1; i < argc; i++ )
    filenames.push_back( argv[i] );

  aleph::topology::io::GMLReader reader;

  // Maps a data set ID to its corresponding Betti number. This is
  // required in order to generate a curve that measures how these
  // numbers change.
  std::map<unsigned, unsigned> id_to_betti;

  for( auto&& filename : filenames )
  {
    if( verbose )
      std::cerr << "* Processing " << filename << "...";

    SimplicialComplex K;
    reader( filename, K );

    K.sort();

    bool dualize                    = true;
    bool includeAllUnpairedCreators = true;

    auto diagrams
      = aleph::calculatePersistenceDiagrams( K,
                                             dualize,
                                             includeAllUnpairedCreators );

    if( verbose )
      std::cerr << "finished\n";

    auto basename
      = aleph::utilities::basename( filename );

    std::regex reDataSetSuffix( "\\D*([[:digit:]]+).*" );
    std::smatch matches;

    if( std::regex_match( basename, matches, reDataSetSuffix ) )
    {
      unsigned id = static_cast<unsigned>( std::stoull( matches[1] ) );

      if( diagrams.size() >= 2 )
        id_to_betti[id] = static_cast<unsigned>( diagrams[1].betti() );
      else
        id_to_betti[id] = static_cast<unsigned>( 0 );
    }
    else
      throw std::runtime_error( "Unable to identify ID" );
  }

  if( verbose )
    std::cerr << "* Obtained " << id_to_betti.size() << " data sets\n";

  for( auto&& pair : id_to_betti )
    std::cout << pair.first << "\t" << pair.second << "\n";

  std::cout << "\n\n";
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: browserids.hxx,v $
 *
 *  $Revision: 1.26 $
 *
 *  last change: $Author: oj $ $Date: 2002-07-09 07:44:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX

#ifndef _SBASLTID_HRC
#include <offmgr/sbasltid.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif

#define ID_BROWSER_COPY                     SID_COPY
#define ID_BROWSER_CUT                      SID_CUT
#define ID_BROWSER_EDITDOC                  SID_EDITDOC
#define ID_BROWSER_UNDORECORD               SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD               SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE                    SID_PASTE
#define ID_BROWSER_REDO                     SID_REDO
#define ID_BROWSER_SAVEDOC                  SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC                SID_SAVEASDOC
#define ID_BROWSER_TITLE                    SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO                     SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS            SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER               SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT            SID_SBA_BRW_UPDATE

#define ID_BROWSER_SEARCH                   SID_FM_SEARCH
#define ID_BROWSER_SORTUP                   SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN                 SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER               SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT               SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT                SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER             SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED                 SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH                  SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL           SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET               20  // Spaltenformatierung
#define ID_BROWSER_COLWIDTH                 21  // Spaltenbreite
#define ID_BROWSER_TABLEATTR                22  // table format attributes
#define ID_BROWSER_ROWHEIGHT                23  // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO               24  // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL                 SID_FM_COUNTALL // count all
#define ID_BROWSER_SQL                      SID_SOURCEVIEW
#define ID_BROWSER_ADDTABLE                 SID_FM_ADDTABLE
#define ID_BROWSER_DESIGN                   SID_SBA_QRY_DESIGN
#define ID_BROWSER_EXPLORER                 SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE      SID_DOCUMENT_DATA_SOURCE

// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE                 1
#define ID_TREE_CLOSE_CONN                   2
#define ID_TREE_REBUILD_CONN                 3
#define ID_TREE_RELATION_DESIGN              7
#define ID_TABLE_DESIGN_NO_CONNECTION        8
#define ID_OPEN_DOCUMENT                     9
#define ID_EDIT_DOCUMENT                    10
#define ID_NEW_LINK                         11
#define ID_EDIT_LINK                        12
#define ID_DROP_LINK                        13
#define ID_CREATE_NEW_DOC                   14
#define ID_FORM_NEW_TEXT                    15
#define ID_FORM_NEW_CALC                    16
#define ID_FORM_NEW_IMPRESS                 17
#define ID_FORM_NEW_PILOT                   18
#define ID_FORM_NEW_TEMPLATE                19
#define ID_NEW_QUERY_DESIGN                 20
#define ID_EDIT_QUERY_DESIGN                21
#define ID_NEW_QUERY_SQL                    22
#define ID_EDIT_QUERY_SQL                   23
#define ID_DROP_QUERY                       24
#define ID_NEW_TABLE_DESIGN                 25
#define ID_EDIT_TABLE                       26
#define ID_DROP_TABLE                       27
#define ID_NEW_VIEW_DESIGN                  28
#define ID_DIRECT_SQL                       32
#define ID_BROWSER_REFRESH_REBUILD          34
#define ID_RENAME_ENTRY                     35
#define ID_INDEX_NEW                        36
#define ID_INDEX_DROP                       37
#define ID_INDEX_RENAME                     38
#define ID_INDEX_SAVE                       39
#define ID_INDEX_RESET                      40

#define ID_BROWSER_QUERY_EXECUTE            SID_FM_EXECUTE
#define ID_BROWSER_CLEAR_QUERY              SID_SBA_CLEAR_QUERY
#define ID_RELATION_ADD_RELATION            SID_SBA_ADD_RELATION
#define ID_BROWSER_QUERY_VIEW_FUNCTIONS     SID_SBA_QUERY_VIEW_FUNCTIONS
#define ID_BROWSER_QUERY_VIEW_TABLES        SID_SBA_QUERY_VIEW_TABLES
#define ID_BROWSER_QUERY_VIEW_ALIASES       SID_SBA_QUERY_VIEW_ALIASES
#define ID_BROWSER_QUERY_DISTINCT_VALUES    SID_SBA_QUERY_DISTINCT_VALUES
#define ID_BROWSER_CLOSE                    SID_CLOSEDOC
#define ID_BROWSER_ESACPEPROCESSING         SID_FM_NATIVESQL

#define ID_QUERY_FUNCTION                   (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME                  (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME                  (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT                   (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION        (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN                    SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT                   SID_ZOOM_OUT

#endif // DBACCESS_UI_BROWSER_ID_HXX
<commit_msg>#100280# new define for report autopilot<commit_after>/*************************************************************************
 *
 *  $RCSfile: browserids.hxx,v $
 *
 *  $Revision: 1.27 $
 *
 *  last change: $Author: oj $ $Date: 2002-07-25 06:54:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#define DBACCESS_UI_BROWSER_ID_HXX

#ifndef _SBASLTID_HRC
#include <offmgr/sbasltid.hrc>
#endif
#ifndef _DBACCESS_SLOTID_HRC_
#include "dbaccess_slotid.hrc"
#endif

#define ID_BROWSER_COPY                     SID_COPY
#define ID_BROWSER_CUT                      SID_CUT
#define ID_BROWSER_EDITDOC                  SID_EDITDOC
#define ID_BROWSER_UNDORECORD               SID_FM_RECORD_UNDO
#define ID_BROWSER_SAVERECORD               SID_FM_RECORD_SAVE
#define ID_BROWSER_PASTE                    SID_PASTE
#define ID_BROWSER_REDO                     SID_REDO
#define ID_BROWSER_SAVEDOC                  SID_SAVEDOC
#define ID_BROWSER_SAVEASDOC                SID_SAVEASDOC
#define ID_BROWSER_TITLE                    SID_DOCINFO_TITLE
#define ID_BROWSER_UNDO                     SID_UNDO
#define ID_BROWSER_INSERTCOLUMNS            SID_SBA_BRW_INSERT
#define ID_BROWSER_FORMLETTER               SID_SBA_BRW_MERGE
#define ID_BROWSER_INSERTCONTENT            SID_SBA_BRW_UPDATE

#define ID_BROWSER_SEARCH                   SID_FM_SEARCH
#define ID_BROWSER_SORTUP                   SID_FM_SORTUP
#define ID_BROWSER_SORTDOWN                 SID_FM_SORTDOWN
#define ID_BROWSER_AUTOFILTER               SID_FM_AUTOFILTER
#define ID_BROWSER_FILTERCRIT               SID_FM_FILTERCRIT
#define ID_BROWSER_ORDERCRIT                SID_FM_ORDERCRIT
#define ID_BROWSER_REMOVEFILTER             SID_FM_REMOVE_FILTER_SORT
#define ID_BROWSER_FILTERED                 SID_FM_FORM_FILTERED
#define ID_BROWSER_REFRESH                  SID_FM_REFRESH
#define ID_BROWSER_EXPL_PREVLEVEL           SID_EXPLORER_PREVLEVEL
#define ID_BROWSER_COLATTRSET               20  // Spaltenformatierung
#define ID_BROWSER_COLWIDTH                 21  // Spaltenbreite
#define ID_BROWSER_TABLEATTR                22  // table format attributes
#define ID_BROWSER_ROWHEIGHT                23  // Zeilenhoehe
#define ID_BROWSER_COLUMNINFO               24  // copies the column description to insert it into the table design
#define ID_BROWSER_COUNTALL                 SID_FM_COUNTALL // count all
#define ID_BROWSER_SQL                      SID_SOURCEVIEW
#define ID_BROWSER_ADDTABLE                 SID_FM_ADDTABLE
#define ID_BROWSER_DESIGN                   SID_SBA_QRY_DESIGN
#define ID_BROWSER_EXPLORER                 SID_DSBROWSER_EXPLORER
#define ID_BROWSER_DOCUMENT_DATASOURCE      SID_DOCUMENT_DATA_SOURCE

// The following ids are local to special components (e.g. menus), so they don't need to be unique
// overall. Please have this in mind when changing anything
#define ID_TREE_ADMINISTRATE                 1
#define ID_TREE_CLOSE_CONN                   2
#define ID_TREE_REBUILD_CONN                 3
#define ID_TREE_RELATION_DESIGN              7
#define ID_TABLE_DESIGN_NO_CONNECTION        8
#define ID_OPEN_DOCUMENT                     9
#define ID_EDIT_DOCUMENT                    10
#define ID_NEW_LINK                         11
#define ID_EDIT_LINK                        12
#define ID_DROP_LINK                        13
#define ID_CREATE_NEW_DOC                   14
#define ID_FORM_NEW_TEXT                    15
#define ID_FORM_NEW_CALC                    16
#define ID_FORM_NEW_IMPRESS                 17
#define ID_FORM_NEW_PILOT                   18
#define ID_FORM_NEW_TEMPLATE                19
#define ID_NEW_QUERY_DESIGN                 20
#define ID_EDIT_QUERY_DESIGN                21
#define ID_NEW_QUERY_SQL                    22
#define ID_EDIT_QUERY_SQL                   23
#define ID_DROP_QUERY                       24
#define ID_NEW_TABLE_DESIGN                 25
#define ID_EDIT_TABLE                       26
#define ID_DROP_TABLE                       27
#define ID_NEW_VIEW_DESIGN                  28
#define ID_DIRECT_SQL                       32
#define ID_BROWSER_REFRESH_REBUILD          34
#define ID_RENAME_ENTRY                     35
#define ID_INDEX_NEW                        36
#define ID_INDEX_DROP                       37
#define ID_INDEX_RENAME                     38
#define ID_INDEX_SAVE                       39
#define ID_INDEX_RESET                      40
#define ID_DOCUMENT_CREATE_REPWIZ           41

#define ID_BROWSER_QUERY_EXECUTE            SID_FM_EXECUTE
#define ID_BROWSER_CLEAR_QUERY              SID_SBA_CLEAR_QUERY
#define ID_RELATION_ADD_RELATION            SID_SBA_ADD_RELATION
#define ID_BROWSER_QUERY_VIEW_FUNCTIONS     SID_SBA_QUERY_VIEW_FUNCTIONS
#define ID_BROWSER_QUERY_VIEW_TABLES        SID_SBA_QUERY_VIEW_TABLES
#define ID_BROWSER_QUERY_VIEW_ALIASES       SID_SBA_QUERY_VIEW_ALIASES
#define ID_BROWSER_QUERY_DISTINCT_VALUES    SID_SBA_QUERY_DISTINCT_VALUES
#define ID_BROWSER_CLOSE                    SID_CLOSEDOC
#define ID_BROWSER_ESACPEPROCESSING         SID_FM_NATIVESQL

#define ID_QUERY_FUNCTION                   (SID_SBA_START + 41) // Funktionen anzeigen
#define ID_QUERY_TABLENAME                  (SID_SBA_START + 42) // Tabellennamen anzeigen
#define ID_QUERY_ALIASNAME                  (SID_SBA_START + 43) // Aliasnamen anzeigen
#define ID_QUERY_DISTINCT                   (SID_SBA_START + 44) // Distinct anzeigen
#define ID_QUERY_EDIT_JOINCONNECTION        (SID_SBA_START + 45) // show-edit Join
#define ID_QUERY_ZOOM_IN                    SID_ZOOM_IN
#define ID_QUERY_ZOOM_OUT                   SID_ZOOM_OUT

#endif // DBACCESS_UI_BROWSER_ID_HXX
<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define TYPICAL_MAT_SIZES_CORE_ARITHM   ::szVGA, ::sz720p, ::sz1080p
#define TYPICAL_MAT_TYPES_CORE_ARITHM   CV_8UC1, CV_8SC1, CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4, CV_8UC4, CV_32SC1, CV_32FC1
#define TYPICAL_MATS_CORE_ARITHM        testing::Combine( testing::Values( TYPICAL_MAT_SIZES_CORE_ARITHM ), testing::Values( TYPICAL_MAT_TYPES_CORE_ARITHM ) )

PERF_TEST_P(Size_MatType, min, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, minScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, max, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, maxScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, absdiff, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, absdiffScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, add, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    declare.time(50);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, addScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtract, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtractScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}
<commit_msg>Add performance tests for elementwise multiplication<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

#define TYPICAL_MAT_SIZES_CORE_ARITHM   ::szVGA, ::sz720p, ::sz1080p
#define TYPICAL_MAT_TYPES_CORE_ARITHM   CV_8UC1, CV_8SC1, CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4, CV_8UC4, CV_32SC1, CV_32FC1
#define TYPICAL_MATS_CORE_ARITHM        testing::Combine( testing::Values( TYPICAL_MAT_SIZES_CORE_ARITHM ), testing::Values( TYPICAL_MAT_TYPES_CORE_ARITHM ) )

PERF_TEST_P(Size_MatType, min, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, minScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() min(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, max, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, maxScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    TEST_CYCLE() max(a, b, c);

    SANITY_CHECK(c);
}

PERF_TEST_P(Size_MatType, absdiff, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, absdiffScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: absdiff can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() absdiff(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, add, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);
    declare.time(50);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, addScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: add can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() add(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtract, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Mat b = Mat(sz, type);
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, subtractScalar, TYPICAL_MATS_CORE_ARITHM)
{
    Size sz = get<0>(GetParam());
    int type = get<1>(GetParam());
    cv::Mat a = Mat(sz, type);
    cv::Scalar b;
    cv::Mat c = Mat(sz, type);

    declare.in(a, b, WARMUP_RNG).out(c);

    if (CV_MAT_DEPTH(type) == CV_32S)
    {
        //see ticket 1529: subtract can be without saturation on 32S
        a /= 2;
        b /= 2;
    }

    TEST_CYCLE() subtract(a, b, c);

    SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiply, TYPICAL_MATS_CORE_ARITHM)
{
	Size sz = get<0>(GetParam());
	int type = get<1>(GetParam());
	cv::Mat a = Mat(sz, type);
	cv::Mat b = Mat(sz, type);
	cv::Mat c = Mat(sz, type);

	declare.in(a, b, WARMUP_RNG).out(c);

	if (CV_MAT_DEPTH(type) == CV_32S)
	{
		//According to docs, saturation is not applied when result is 32bit integer
		a /= (2 << 16);
		b /= (2 << 16);
	}

	TEST_CYCLE() multiply(a, b, c);

	SANITY_CHECK(c, 1e-8);
}

PERF_TEST_P(Size_MatType, multiplyScale, TYPICAL_MATS_CORE_ARITHM)
{
	Size sz = get<0>(GetParam());
	int type = get<1>(GetParam());
	cv::Mat a = Mat(sz, type);
	cv::Mat b = Mat(sz, type);
	cv::Mat c = Mat(sz, type);
	double scale = 0.5;

	declare.in(a, b, WARMUP_RNG).out(c);

	if (CV_MAT_DEPTH(type) == CV_32S)
	{
		//According to docs, saturation is not applied when result is 32bit integer
		a /= (2 << 16);
		b /= (2 << 16);
	}

	TEST_CYCLE() multiply(a, b, c, scale);

	SANITY_CHECK(c, 1e-8);
}
<|endoftext|>


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

#include <cstdlib>

#ifdef CLEVER_WIN32
# include <direct.h>
# include <windows.h>
# define PATH_MAX MAX_PATH
#else
# include <dirent.h>
# include <unistd.h>
# include <sys/resource.h>
# include <sys/time.h>
#endif

#include "compiler/value.h"
#include "modules/std/sys/sys.h"
#include "types/nativetypes.h"
#include "compiler/pkgmanager.h"

#ifndef PATH_MAX
# define PATH_MAX 1024
#endif

namespace clever { namespace packages { namespace std {

namespace sys {

/**
 * Int system(string command)
 * Calls a command and returns the exit code.
 */
static CLEVER_FUNCTION(system) {
	CLEVER_RETURN_INT(::system(CLEVER_ARG_STR(0).c_str()));
}

/**
 * Void putenv(String env)
 * Sets an environment variable
 */
static CLEVER_FUNCTION(putenv) {
    ::putenv(const_cast<char*>(CLEVER_ARG_STR(0).c_str()));
}

/**
 * String getenv(String env)
 * Gets an environment variable
 */
static CLEVER_FUNCTION(getenv) {
	const char* ret = ::getenv(const_cast<char*>(CLEVER_ARG_STR(0).c_str()));

	if (ret) {
		CLEVER_RETURN_STR(CSTRINGT(ret));
	} else {
		CLEVER_RETURN_EMPTY_STR();
	}
}

/**
 * String getcwd()
 * Gets the current working directory
 */
static CLEVER_FUNCTION(getcwd) {
	char temp[PATH_MAX];
    const char* path = ::getcwd(temp, PATH_MAX);

	if (path) {
		CLEVER_RETURN_STR(CSTRINGT(path));
	} else {
		CLEVER_RETURN_EMPTY_STR();
	}
}

/**
 * String argv(Int i)
 * Get i-th argv value
 */
static CLEVER_FUNCTION(argv) {
	size_t i = static_cast<size_t>(CLEVER_ARG_INT(0));

	if (i >= (size_t)*g_clever_argc) {
		CLEVER_RETURN_EMPTY_STR();
	} else {
		CLEVER_RETURN_STR(CSTRINGT((*g_clever_argv)[i]));
	}
}

/**
 * Int argc()
 * Get argc value
 */
static CLEVER_FUNCTION(argc) {
	CLEVER_RETURN_INT(*g_clever_argc);
}

/**
 * Void sleep(Int time)
 * Sleep for 'time' milliseconds.
 */
static CLEVER_FUNCTION(sleep) {
	int time = static_cast<int>(CLEVER_ARG_INT(0));

#ifdef CLEVER_WIN32
	SleepEx(time, false);
#else
	usleep(time * 1000);
#endif
}

} // namespace os

/**
 * Initializes Standard module
 */
CLEVER_MODULE_INIT(SYSModule) {
	BEGIN_DECLARE_FUNCTION();

	addFunction(new Function("system", &CLEVER_NS_FNAME(sys, system), CLEVER_INT))
		->addArg("command", CLEVER_STR);

	addFunction(new Function("putenv", &CLEVER_NS_FNAME(sys, putenv), CLEVER_VOID))
		->addArg("env", CLEVER_STR);

	addFunction(new Function("getenv", &CLEVER_NS_FNAME(sys, getenv), CLEVER_STR))
		->addArg("var", CLEVER_STR);

	addFunction(new Function("getcwd", &CLEVER_NS_FNAME(sys, getcwd), CLEVER_STR));

	addFunction(new Function("argc", &CLEVER_NS_FNAME(sys, argc), CLEVER_INT));

	addFunction(new Function("argv", &CLEVER_NS_FNAME(sys, argv), CLEVER_STR))
		->addArg("i", CLEVER_INT);

	addFunction(new Function("sleep", &CLEVER_NS_FNAME(sys, sleep), CLEVER_VOID))
		->addArg("time", CLEVER_INT);

	END_DECLARE();
}

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

#include <cstdlib>

#ifdef CLEVER_WIN32
# include <direct.h>
# include <windows.h>
# define PATH_MAX MAX_PATH
#else
# include <dirent.h>
# include <unistd.h>
# include <sys/resource.h>
# include <sys/time.h>
#endif

#include "compiler/value.h"
#include "modules/std/sys/sys.h"
#include "types/nativetypes.h"
#include "compiler/pkgmanager.h"

#ifndef PATH_MAX
# define PATH_MAX 1024
#endif

namespace clever { namespace packages { namespace std {

namespace sys {

/**
 * Int system(String command)
 * Calls a command and returns the exit code.
 */
static CLEVER_FUNCTION(system) {
	CLEVER_RETURN_INT(::system(CLEVER_ARG_STR(0).c_str()));
}

/**
 * Void putenv(String env)
 * Sets an environment variable
 */
static CLEVER_FUNCTION(putenv) {
    ::putenv(const_cast<char*>(CLEVER_ARG_STR(0).c_str()));
}

/**
 * String getenv(String env)
 * Gets an environment variable
 */
static CLEVER_FUNCTION(getenv) {
	const char* ret = ::getenv(const_cast<char*>(CLEVER_ARG_STR(0).c_str()));

	if (ret) {
		CLEVER_RETURN_STR(CSTRINGT(ret));
	} else {
		CLEVER_RETURN_EMPTY_STR();
	}
}

/**
 * String getcwd()
 * Gets the current working directory
 */
static CLEVER_FUNCTION(getcwd) {
	char temp[PATH_MAX];
    const char* path = ::getcwd(temp, PATH_MAX);

	if (path) {
		CLEVER_RETURN_STR(CSTRINGT(path));
	} else {
		CLEVER_RETURN_EMPTY_STR();
	}
}

/**
 * String argv(Int i)
 * Get i-th argv value
 */
static CLEVER_FUNCTION(argv) {
	size_t i = static_cast<size_t>(CLEVER_ARG_INT(0));

	if (i >= (size_t)*g_clever_argc) {
		CLEVER_RETURN_EMPTY_STR();
	} else {
		CLEVER_RETURN_STR(CSTRINGT((*g_clever_argv)[i]));
	}
}

/**
 * Int argc()
 * Get argc value
 */
static CLEVER_FUNCTION(argc) {
	CLEVER_RETURN_INT(*g_clever_argc);
}

/**
 * Void sleep(Int time)
 * Sleep for 'time' milliseconds.
 */
static CLEVER_FUNCTION(sleep) {
	int time = static_cast<int>(CLEVER_ARG_INT(0));

#ifdef CLEVER_WIN32
	SleepEx(time, false);
#else
	usleep(time * 1000);
#endif
}

} // namespace os

/**
 * Initializes Standard module
 */
CLEVER_MODULE_INIT(SYSModule) {
	BEGIN_DECLARE_FUNCTION();

	addFunction(
		new Function("system", &CLEVER_NS_FNAME(sys, system), CLEVER_INT))
		->addArg("command", CLEVER_STR);

	addFunction(
		new Function("putenv", &CLEVER_NS_FNAME(sys, putenv), CLEVER_VOID))
		->addArg("env", CLEVER_STR);

	addFunction(
		new Function("getenv", &CLEVER_NS_FNAME(sys, getenv), CLEVER_STR))
		->addArg("var", CLEVER_STR);

	addFunction(
		new Function("getcwd", &CLEVER_NS_FNAME(sys, getcwd), CLEVER_STR));

	addFunction(
		new Function("argc", &CLEVER_NS_FNAME(sys, argc), CLEVER_INT));

	addFunction(
		new Function("argv", &CLEVER_NS_FNAME(sys, argv), CLEVER_STR))
		->addArg("i", CLEVER_INT);

	addFunction(
		new Function("sleep", &CLEVER_NS_FNAME(sys, sleep), CLEVER_VOID))
		->addArg("time", CLEVER_INT);

	END_DECLARE();
}

}}} // clever::packages::std
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "grantleeview_p.h"

#include "context.h"
#include "action.h"
#include "response.h"

#include <QString>
#include <QStringBuilder>
#include <QtCore/QLoggingCategory>

Q_LOGGING_CATEGORY(CUTELYST_GRANTLEE, "cutelyst.grantlee")

using namespace Cutelyst;

GrantleeView::GrantleeView(QObject *parent) :
    ViewInterface(parent),
    d_ptr(new GrantleeViewPrivate)
{
    Q_D(GrantleeView);

    d->loader = QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader);

    d->engine = new Grantlee::Engine(this);
    d->engine->addTemplateLoader(d->loader);
}

GrantleeView::~GrantleeView()
{
    delete d_ptr;
}

QString GrantleeView::includePath() const
{
    Q_D(const GrantleeView);
    return d->includePath;
}

void GrantleeView::setIncludePath(const QString &path)
{
    Q_D(GrantleeView);
    d->loader->setTemplateDirs(QStringList() << path);
    d->includePath = path;
}

QString GrantleeView::templateExtension() const
{
    Q_D(const GrantleeView);
    return d->extension;
}

void GrantleeView::setTemplateExtension(const QString &extension)
{
    Q_D(GrantleeView);
    d->extension = extension;
}

QString GrantleeView::wrapper() const
{
    Q_D(const GrantleeView);
    return d->wrapper;
}

void GrantleeView::setWrapper(const QString &name)
{
    Q_D(GrantleeView);
    d->wrapper = name;
}

void GrantleeView::setCache(bool enable)
{
    Q_D(GrantleeView);

    if (enable != d->cache.isNull()) {
        return; // already enabled
    }

    delete d->engine;
    d->engine = new Grantlee::Engine(this);

    if (enable) {
        d->cache = QSharedPointer<Grantlee::CachingLoaderDecorator>(new Grantlee::CachingLoaderDecorator(d->loader));
        d->engine->addTemplateLoader(d->cache);
    } else {
        d->cache.clear();
        d->engine->addTemplateLoader(d->loader);
    }
}

bool GrantleeView::isCaching() const
{
    Q_D(const GrantleeView);
    return !d->cache.isNull();
}

bool GrantleeView::render(Context *ctx)
{
    Q_D(const GrantleeView);

    QVariantHash &stash = ctx->stash();
    QString templateFile = stash.value(QStringLiteral("template")).toString();
    if (templateFile.isEmpty()) {
        if (ctx->action() && !ctx->action()->reverse().isEmpty()) {
            templateFile = ctx->action()->reverse() % d->extension;
        }

        if (templateFile.isEmpty()) {
            qCCritical(CUTELYST_GRANTLEE) << "Cannot render template, template name or template stash key not defined";
            return false;
        }
    }

    stash.insert(QStringLiteral("ctx"), QVariant::fromValue(ctx));
    Grantlee::Context gCtx(stash);

    Grantlee::Template tmpl;
    if (d->wrapper.isEmpty()) {
        tmpl = d->engine->loadByName(templateFile);
    } else {
        tmpl = d->engine->loadByName(d->wrapper);

        gCtx.insert(QStringLiteral("template"), templateFile);
    }

    ctx->res()->body() = tmpl->render(&gCtx).toUtf8();

    if (tmpl->error() != Grantlee::NoError) {
        qCCritical(CUTELYST_GRANTLEE) << "Error while rendering template" << tmpl->errorString();
    }

    return tmpl->error() == Grantlee::NoError;
}
<commit_msg>Preload all Grantlee templates<commit_after>/*
 * Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "grantleeview_p.h"

#include "context.h"
#include "action.h"
#include "response.h"

#include <QString>
#include <QStringBuilder>
#include <QDirIterator>
#include <QtCore/QLoggingCategory>

Q_LOGGING_CATEGORY(CUTELYST_GRANTLEE, "cutelyst.grantlee")

using namespace Cutelyst;

GrantleeView::GrantleeView(QObject *parent) :
    ViewInterface(parent),
    d_ptr(new GrantleeViewPrivate)
{
    Q_D(GrantleeView);

    d->loader = QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader);

    d->engine = new Grantlee::Engine(this);
    d->engine->addTemplateLoader(d->loader);
}

GrantleeView::~GrantleeView()
{
    delete d_ptr;
}

QString GrantleeView::includePath() const
{
    Q_D(const GrantleeView);
    return d->includePath;
}

void GrantleeView::setIncludePath(const QString &path)
{
    Q_D(GrantleeView);
    d->loader->setTemplateDirs(QStringList() << path);
    d->includePath = path;
}

QString GrantleeView::templateExtension() const
{
    Q_D(const GrantleeView);
    return d->extension;
}

void GrantleeView::setTemplateExtension(const QString &extension)
{
    Q_D(GrantleeView);
    d->extension = extension;
}

QString GrantleeView::wrapper() const
{
    Q_D(const GrantleeView);
    return d->wrapper;
}

void GrantleeView::setWrapper(const QString &name)
{
    Q_D(GrantleeView);
    d->wrapper = name;
}

void GrantleeView::setCache(bool enable)
{
    Q_D(GrantleeView);

    if (enable != d->cache.isNull()) {
        return; // already enabled
    }

    delete d->engine;
    d->engine = new Grantlee::Engine(this);

    if (enable) {
        d->cache = QSharedPointer<Grantlee::CachingLoaderDecorator>(new Grantlee::CachingLoaderDecorator(d->loader));
        d->engine->addTemplateLoader(d->cache);
    } else {
        d->cache.clear();
        d->engine->addTemplateLoader(d->loader);
    }

    QDirIterator it(d->includePath,
                    QDir::Files | QDir::NoDotAndDotDot,
                    QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString path = it.next();
        path.remove(d->includePath);
        if (path.startsWith(QLatin1Char('/'))) {
            path.remove(0, 1);
        }

        if (d->cache->canLoadTemplate(path)) {
            d->cache->loadByName(path, d->engine);
        }
    }
}

bool GrantleeView::isCaching() const
{
    Q_D(const GrantleeView);
    return !d->cache.isNull();
}

bool GrantleeView::render(Context *ctx)
{
    Q_D(const GrantleeView);

    QVariantHash &stash = ctx->stash();
    QString templateFile = stash.value(QStringLiteral("template")).toString();
    if (templateFile.isEmpty()) {
        if (ctx->action() && !ctx->action()->reverse().isEmpty()) {
            templateFile = ctx->action()->reverse() % d->extension;
            if (templateFile.startsWith(QLatin1Char('/'))) {
                templateFile.remove(0, 1);
            }
        }

        if (templateFile.isEmpty()) {
            qCCritical(CUTELYST_GRANTLEE) << "Cannot render template, template name or template stash key not defined";
            return false;
        }
    }

    stash.insert(QStringLiteral("ctx"), QVariant::fromValue(ctx));
    Grantlee::Context gCtx(stash);

    Grantlee::Template tmpl;
    if (d->wrapper.isEmpty()) {
        tmpl = d->engine->loadByName(templateFile);
    } else {
        tmpl = d->engine->loadByName(d->wrapper);

        gCtx.insert(QStringLiteral("template"), templateFile);
    }

    ctx->res()->body() = tmpl->render(&gCtx).toUtf8();

    if (tmpl->error() != Grantlee::NoError) {
        qCCritical(CUTELYST_GRANTLEE) << "Error while rendering template" << tmpl->errorString();
    }

    return tmpl->error() == Grantlee::NoError;
}
<|endoftext|>