<commit_before>
#include "rsGlobalExtern.hpp"
#include "rodsErrorTable.hpp"
#include "initServer.hpp"
#include "miscServerFunct.hpp"
#include "specificQuery.hpp"

#include "irods_log.hpp"
#include "grid_report.hpp"
#include "ies_client_hints.hpp"
#include "irods_resource_manager.hpp"
#include "irods_resource_backport.hpp"
#include "irods_server_properties.hpp"

#include <jansson.h>

int _rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf );

int rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf ) {
    rodsServerHost_t* rods_host;
    int status = getAndConnRcatHost(
                     _comm,
                     MASTER_RCAT,
                     NULL,
                     &rods_host );
    if ( status < 0 ) {
        return status;
    }

    if ( rods_host->localFlag == LOCAL_HOST ) {
#ifdef RODS_CAT
        status = _rsIESClientHints(
                     _comm,
                     _bbuf );
#else
        status = SYS_NO_RCAT_SERVER_ERR;
#endif
    }
    else {
        status = rcIESClientHints( rods_host->conn,
                               _bbuf );
    }

    if ( status < 0 ) {
        rodsLog(
            LOG_ERROR,
            "rsIESClientHints: rcIESClientHints failed, status = %d",
            status );
    }

    return status;

} // rsIESClientHints

#ifdef RODS_CAT

irods::error get_strict_acls(
    rsComm_t*    _comm,
    std::string& _acls ) {
    if( ! _comm ) {
        return ERROR(
            SYS_INVALID_INPUT_PARAM,
            "comm is null" );
    }

    irods::server_properties& props = irods::server_properties::getInstance();
    props.capture_if_needed();
    irods::error ret = props.get_property<std::string>(
                           irods::STRICT_ACL_KW,
                           _acls );

    return PASS( ret );

} // get_strict_acls

irods::error get_query_array(
    rsComm_t* _comm,
    json_t*&  _queries ) {
    if( !_comm ) {
        return ERROR(
                   SYS_INVALID_INPUT_PARAM,
                   "comm is null" );
    }

    _queries = json_array();
    if ( !_queries ) {
        return ERROR(
                   SYS_MALLOC_ERR,
                   "allocation of json object failed" );
    }

    specificQueryInp_t spec_inp;
    memset( &spec_inp, 0, sizeof( specificQueryInp_t ) );

    spec_inp.maxRows = MAX_SQL_ROWS;
    spec_inp.continueInx = 0;
    spec_inp.sql = "ls";

    genQueryOut_t* gen_out = 0;
    int status = rsSpecificQuery(
                     _comm,
                     &spec_inp,
                     &gen_out );
    if( status < 0 ) {
        return ERROR(
                   status,
                   "rsSpecificQuery for 'ls' failed" );
    }

    // first attribute is the alias of the specific query
    int   len    = gen_out->sqlResult[ 0 ].len;
    char* values = gen_out->sqlResult[ 0 ].value;

    for( int i = 0 ;
         i < gen_out->rowCnt ;
         ++i ) {

        char* alias = &values[ len * i ];
        if( !alias ) {
            rodsLog(
                LOG_ERROR,
                "get_query_array - alias at %d is null",
                i );
            continue;
        }

        json_array_append( _queries, json_string( alias ) );

    } // for i

    freeGenQueryOut( &gen_out );

    return SUCCESS();

} // get_query_array

int _rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf ) {
    if( ! _comm ) {
        return SYS_INVALID_INPUT_PARAM;

    }

    json_t* ies_hints = json_object();
    if ( !ies_hints ) {
        rodsLog(
            LOG_ERROR,
            "failed to allocate json_object" );
        return SYS_MALLOC_ERR;
    }

    std::string acls;
    irods::error ret = get_strict_acls(
                           _comm,
                           acls );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    json_object_set(
        ies_hints,
        "strict_acls",
        json_string( acls.c_str() ) );

    json_t* query_arr = 0;
    ret = get_query_array( _comm, query_arr );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }
    json_object_set(
        ies_hints,
        "specific_queries",
        query_arr );

    char* tmp_buf = json_dumps( ies_hints, JSON_INDENT( 4 ) );

    // *SHOULD* free All The Things...
    json_decref( ies_hints );

    ( *_bbuf ) = ( bytesBuf_t* ) malloc( sizeof( bytesBuf_t ) );
    if ( !( *_bbuf ) ) {
        rodsLog(
            LOG_ERROR,
            "_rsIESClientHints: failed to allocate _bbuf" );
        return SYS_MALLOC_ERR;

    }

    ( *_bbuf )->buf = tmp_buf;
    ( *_bbuf )->len = strlen( tmp_buf );

    return 0;

} // _rsIESClientHints

#endif // RODS_CAT

<commit_msg>[#2212] CID67049:<commit_after>
#include "rsGlobalExtern.hpp"
#include "rodsErrorTable.hpp"
#include "initServer.hpp"
#include "miscServerFunct.hpp"
#include "specificQuery.hpp"

#include "irods_log.hpp"
#include "grid_report.hpp"
#include "ies_client_hints.hpp"
#include "irods_resource_manager.hpp"
#include "irods_resource_backport.hpp"
#include "irods_server_properties.hpp"

#include <jansson.h>

int _rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf );

int rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf ) {
    rodsServerHost_t* rods_host;
    int status = getAndConnRcatHost(
                     _comm,
                     MASTER_RCAT,
                     NULL,
                     &rods_host );
    if ( status < 0 ) {
        return status;
    }

    if ( rods_host->localFlag == LOCAL_HOST ) {
#ifdef RODS_CAT
        status = _rsIESClientHints(
                     _comm,
                     _bbuf );
#else
        status = SYS_NO_RCAT_SERVER_ERR;
#endif
    }
    else {
        status = rcIESClientHints( rods_host->conn,
                               _bbuf );
    }

    if ( status < 0 ) {
        rodsLog(
            LOG_ERROR,
            "rsIESClientHints: rcIESClientHints failed, status = %d",
            status );
    }

    return status;

} // rsIESClientHints

#ifdef RODS_CAT

irods::error get_strict_acls(
    rsComm_t*    _comm,
    std::string& _acls ) {
    if( ! _comm ) {
        return ERROR(
            SYS_INVALID_INPUT_PARAM,
            "comm is null" );
    }

    irods::server_properties& props = irods::server_properties::getInstance();
    props.capture_if_needed();
    irods::error ret = props.get_property<std::string>(
                           irods::STRICT_ACL_KW,
                           _acls );

    return PASS( ret );

} // get_strict_acls

irods::error get_query_array(
    rsComm_t* _comm,
    json_t*&  _queries ) {
    if( !_comm ) {
        return ERROR(
                   SYS_INVALID_INPUT_PARAM,
                   "comm is null" );
    }

    _queries = json_array();
    if ( !_queries ) {
        return ERROR(
                   SYS_MALLOC_ERR,
                   "allocation of json object failed" );
    }

    specificQueryInp_t spec_inp;
    memset( &spec_inp, 0, sizeof( specificQueryInp_t ) );

    spec_inp.maxRows = MAX_SQL_ROWS;
    spec_inp.continueInx = 0;
    spec_inp.sql = "ls";

    genQueryOut_t* gen_out = 0;
    int status = rsSpecificQuery(
                     _comm,
                     &spec_inp,
                     &gen_out );
    if( status < 0 ) {
        return ERROR(
                   status,
                   "rsSpecificQuery for 'ls' failed" );
    }

    // first attribute is the alias of the specific query
    int   len    = gen_out->sqlResult[ 0 ].len;
    char* values = gen_out->sqlResult[ 0 ].value;

    for( int i = 0 ;
         i < gen_out->rowCnt ;
         ++i ) {

        char* alias = &values[ len * i ];
        json_array_append( _queries, json_string( alias ) );

    } // for i

    freeGenQueryOut( &gen_out );

    return SUCCESS();

} // get_query_array

int _rsIESClientHints(
    rsComm_t*    _comm,
    bytesBuf_t** _bbuf ) {
    if( ! _comm ) {
        return SYS_INVALID_INPUT_PARAM;

    }

    json_t* ies_hints = json_object();
    if ( !ies_hints ) {
        rodsLog(
            LOG_ERROR,
            "failed to allocate json_object" );
        return SYS_MALLOC_ERR;
    }

    std::string acls;
    irods::error ret = get_strict_acls(
                           _comm,
                           acls );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }

    json_object_set(
        ies_hints,
        "strict_acls",
        json_string( acls.c_str() ) );

    json_t* query_arr = 0;
    ret = get_query_array( _comm, query_arr );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
    }
    json_object_set(
        ies_hints,
        "specific_queries",
        query_arr );

    char* tmp_buf = json_dumps( ies_hints, JSON_INDENT( 4 ) );

    // *SHOULD* free All The Things...
    json_decref( ies_hints );

    ( *_bbuf ) = ( bytesBuf_t* ) malloc( sizeof( bytesBuf_t ) );
    if ( !( *_bbuf ) ) {
        rodsLog(
            LOG_ERROR,
            "_rsIESClientHints: failed to allocate _bbuf" );
        return SYS_MALLOC_ERR;

    }

    ( *_bbuf )->buf = tmp_buf;
    ( *_bbuf )->len = strlen( tmp_buf );

    return 0;

} // _rsIESClientHints

#endif // RODS_CAT

<|endoftext|>


<commit_before>/*******************************************************************************
 * libmodman - A library for extending applications
 * Copyright (C) 2009 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 ******************************************************************************/

#ifndef MODULE_HPP_
#define MODULE_HPP_

#include <typeinfo>
#include <cstdlib>

#ifdef WIN32
#define DLL_PUBLIC __declspec(dllexport)
#else
#define DLL_PUBLIC __attribute__ ((visibility("default")))
#endif

#define MM_MODULE_VERSION 1
#define MM_MODULE_NAME __module

#define MM_MODULE_DEFINE extern "C" struct com::googlecode::libmodman::module DLL_PUBLIC MM_MODULE_NAME[]
#define MM_MODULE_LAST { MM_MODULE_VERSION, NULL, NULL, NULL, NULL }
#define MM_MODULE_RECORD(type, init, test, symb) \
	{ MM_MODULE_VERSION, type::base_type(), init, test, symb }

#define MM_MODULE_EZ(clsname, cond, symb) \
	static bool clsname ## _test() { \
		return (cond); \
	} \
	static com::googlecode::libmodman::base_extension** clsname ## _init() { \
		com::googlecode::libmodman::base_extension** retval = new com::googlecode::libmodman::base_extension*[2]; \
		retval[0] = new clsname(); \
		retval[1] = NULL; \
		return retval; \
	} \
	MM_MODULE_DEFINE = { \
		MM_MODULE_RECORD(clsname, clsname ## _init, clsname ## _test, symb), \
		MM_MODULE_LAST, \
	};

namespace com {
namespace googlecode {
namespace libmodman {

class DLL_PUBLIC base_extension {
public:
	static const char* base_type() { return typeid(base_extension).name(); }
	static bool        singleton();

	virtual ~base_extension();
	virtual bool operator<(const base_extension&) const;
};

template <class T>
class DLL_PUBLIC extension : public base_extension {
public:
	static const char* base_type() { return typeid(T).name(); }
};

struct module {
	const unsigned int  vers;
	const char* const   type;
	base_extension**  (*init)();
	bool              (*test)();
	const char* const   symb;
};

}
}
}

#endif /* MODULE_HPP_ */
<commit_msg>fix a wierd definition incompatibility between win32 and unix<commit_after>/*******************************************************************************
 * libmodman - A library for extending applications
 * Copyright (C) 2009 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 ******************************************************************************/

#ifndef MODULE_HPP_
#define MODULE_HPP_

#include <typeinfo>
#include <cstdlib>

#ifdef WIN32
#define DLL_PUBLIC __declspec(dllexport)
#define __MOD_DEF_PREFIX extern "C"
#else
#define DLL_PUBLIC __attribute__ ((visibility("default")))
#define __MOD_DEF_PREFIX
#endif

#define MM_MODULE_VERSION 1
#define MM_MODULE_NAME __module
#define MM_MODULE_DEFINE __MOD_DEF_PREFIX struct com::googlecode::libmodman::module DLL_PUBLIC MM_MODULE_NAME[]

#define MM_MODULE_LAST { MM_MODULE_VERSION, NULL, NULL, NULL, NULL }
#define MM_MODULE_RECORD(type, init, test, symb) \
	{ MM_MODULE_VERSION, type::base_type(), init, test, symb }

#define MM_MODULE_EZ(clsname, cond, symb) \
	static bool clsname ## _test() { \
		return (cond); \
	} \
	static com::googlecode::libmodman::base_extension** clsname ## _init() { \
		com::googlecode::libmodman::base_extension** retval = new com::googlecode::libmodman::base_extension*[2]; \
		retval[0] = new clsname(); \
		retval[1] = NULL; \
		return retval; \
	} \
	MM_MODULE_DEFINE = { \
		MM_MODULE_RECORD(clsname, clsname ## _init, clsname ## _test, symb), \
		MM_MODULE_LAST, \
	};

namespace com {
namespace googlecode {
namespace libmodman {

class DLL_PUBLIC base_extension {
public:
	static const char* base_type() { return typeid(base_extension).name(); }
	static bool        singleton();

	virtual ~base_extension();
	virtual bool operator<(const base_extension&) const;
};

template <class T>
class DLL_PUBLIC extension : public base_extension {
public:
	static const char* base_type() { return typeid(T).name(); }
};

struct module {
	const unsigned int  vers;
	const char* const   type;
	base_extension**  (*init)();
	bool              (*test)();
	const char* const   symb;
};

}
}
}

#endif /* MODULE_HPP_ */
<|endoftext|>


<commit_before>#pragma once

#include <boost/config.hpp>

#include "blackhole/attribute.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/files/backend.hpp"
#include "blackhole/sink/files/config.hpp"
#include "blackhole/sink/files/flusher.hpp"
#include "blackhole/sink/files/rotation.hpp"
#include "blackhole/sink/files/writer.hpp"
#include "blackhole/utils/unique.hpp"

namespace blackhole {

namespace sink {

template<class Backend, class Rotator, class = void>
class file_handler_t;

template<class Backend>
class file_handler_t<Backend, NoRotation, void> {
    Backend m_backend;
    files::writer_t<Backend> writer;
    files::flusher_t<Backend> flusher;
public:
    file_handler_t(const std::string& path, const files::config_t<NoRotation>& config) :
        m_backend(path),
        writer(m_backend),
        flusher(config.autoflush, m_backend)
    {}

    void handle(const std::string& message) {
        writer.write(message);
        flusher.flush();
    }

    const Backend& backend() {
        return m_backend;
    }
};

template<class Backend, class Rotator>
class file_handler_t<
    Backend,
    Rotator,
    typename std::enable_if<
        !std::is_same<Rotator, NoRotation>::value
    >::type>
{
    Backend m_backend;
    files::writer_t<Backend> writer;
    files::flusher_t<Backend> flusher;
    Rotator rotator;
public:
    file_handler_t(const std::string& path, const files::config_t<Rotator>& config) :
        m_backend(path),
        writer(m_backend),
        flusher(config.autoflush, m_backend),
        rotator(config.rotation, m_backend)
    {}

    void handle(const std::string& message) {
        writer.write(message);
        flusher.flush();
        if (rotator.necessary(message)) {
            rotator.rotate();
        }
    }

    const Backend& backend() {
        return m_backend;
    }
};

template<class Backend = files::boost_backend_t, class Rotator = NoRotation>
class files_t {
    typedef file_handler_t<Backend, Rotator> handler_type;
    typedef std::unordered_map<std::string, std::shared_ptr<handler_type>> handlers_type;

    files::config_t<Rotator> config;
    handlers_type m_handlers;
public:
    typedef files::config_t<Rotator> config_type;

    static const char* name() {
        return "files";
    }

    files_t(const config_type& config) :
        config(config)
    {}

    void consume(const std::string& message, const log::attributes_t& attributes = log::attributes_t()) {
        auto filename = make_filename(attributes);
        auto it = m_handlers.find(filename);
        if (it == m_handlers.end()) {
            it = m_handlers.insert(it, std::make_pair(filename, std::make_shared<handler_type>(filename, config)));
        }
        it->second->handle(message);
    }

    const handlers_type& handlers() {
        return m_handlers;
    }

    std::string make_filename(const log::attributes_t& attributes) const {
        auto it = config.path.begin();
        auto end = config.path.end();
        std::string filename;
        while (it != end) {
            if (*it == '%' && it + 1 != end && *(it + 1) == '(') {
                it += 2;

                std::string key;
                bool found = false;
                while (it != end) {
                    if (*it == ')' && it + 1 != end && *(it + 1) == 's') {
                        found = true;
                        it += 2;
                        break;
                    }
                    key.push_back(*it);
                    it++;
                }

                if (found) {
                    auto ait = attributes.find(key);
                    if (ait != attributes.end()) {
                        std::ostringstream stream;
                        stream << ait->second.value;
                        filename.append(stream.str());
                    } else {
                        filename.append(key);
                    }
                } else {
                    filename.append(key);
                }
            }

            if (it == end) {
                break;
            }
            filename.push_back(*it);
            it++;
        }
//        std::cout << "filename=" << filename << std::endl;
        return filename;
    }
};

} // namespace sink

template<class Backend, class Watcher>
struct unique_id_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef sink::rotator_t<Backend, Watcher> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;

    typedef std::map<std::string, boost::any> variant_map_t;

    static std::string generate(const boost::any& config) {
        const variant_map_t& cfg = boost::any_cast<variant_map_t>(config);

        auto rotation_it = cfg.find("rotation");
        if (rotation_it != cfg.end()) {
            const variant_map_t& rotation = boost::any_cast<variant_map_t>(rotation_it->second);

            const bool has_size_watcher = rotation.find("size") != rotation.end();
            const bool has_datetime_watcher = rotation.find("period") != rotation.end();

            if (has_size_watcher && has_datetime_watcher) {
                throw blackhole::error_t("set watcher is not implemented yet");
            } else if (has_size_watcher) {
                return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "size");
            } else if (has_datetime_watcher) {
                return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "datetime");
            }

            throw blackhole::error_t("rotation section not properly configures: no watcher settings found");
        }

        return sink_type::name();
    }
};

template<class Backend>
struct config_traits<sink::files_t<Backend, sink::NoRotation>> {
    static std::string name() {
        return sink::files_t<Backend, sink::NoRotation>::name();
    }
};

template<class Backend, class Watcher>
struct config_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef sink::rotator_t<Backend, Watcher> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;

    static std::string name() {
        return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), Watcher::name());
    }
};

namespace aux {

template<class Backend, class Rotator>
struct filler<sink::files_t<Backend, Rotator>> {
    template<class Extractor, class Config>
    static void extract_to(const Extractor& ex, Config& config) {
        ex["path"].to(config.path);
        ex["autoflush"].to(config.autoflush);
    }
};

template<class Backend, class Watcher>
struct filler<sink::rotator_t<Backend, Watcher>> {
    template<class Extractor, class Config>
    static void extract_to(const Extractor& ex, Config& config) {
        ex["rotation"]["pattern"].to(config.rotation.pattern);
        ex["rotation"]["backups"].to(config.rotation.backups);
    }
};

} // namespace aux

template<class Backend>
struct factory_traits<sink::files_t<Backend>> {
    typedef sink::files_t<Backend> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
    }
};

template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
    typedef sink::rotation::watcher::size_t watcher_type;
    typedef sink::rotator_t<Backend, watcher_type> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
        aux::filler<rotator_type>::extract_to(ex, config);
        ex["rotation"]["size"].to(config.rotation.watcher.size);
    }
};

template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::datetime_t<>>>> {
    typedef sink::rotation::watcher::datetime_t<> watcher_type;
    typedef sink::rotator_t<Backend, watcher_type> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
        aux::filler<rotator_type>::extract_to(ex, config);
        ex["rotation"]["period"].to(config.rotation.watcher.period);
    }
};

} // namespace blackhole
<commit_msg>[Aux] Files sink now uses generic string formatter for substituting attributes into generic filename pattern.<commit_after>#pragma once

#include <boost/config.hpp>

#include "blackhole/attribute.hpp"
#include "blackhole/detail/string/formatting/formatter.hpp"
#include "blackhole/repository/factory/traits.hpp"
#include "blackhole/sink/files/backend.hpp"
#include "blackhole/sink/files/config.hpp"
#include "blackhole/sink/files/flusher.hpp"
#include "blackhole/sink/files/rotation.hpp"
#include "blackhole/sink/files/writer.hpp"
#include "blackhole/utils/unique.hpp"

namespace blackhole {

namespace sink {

template<class Backend, class Rotator, class = void>
class file_handler_t;

template<class Backend>
class file_handler_t<Backend, NoRotation, void> {
    Backend m_backend;
    files::writer_t<Backend> writer;
    files::flusher_t<Backend> flusher;
public:
    file_handler_t(const std::string& path, const files::config_t<NoRotation>& config) :
        m_backend(path),
        writer(m_backend),
        flusher(config.autoflush, m_backend)
    {}

    void handle(const std::string& message) {
        writer.write(message);
        flusher.flush();
    }

    const Backend& backend() {
        return m_backend;
    }
};

template<class Backend, class Rotator>
class file_handler_t<
    Backend,
    Rotator,
    typename std::enable_if<
        !std::is_same<Rotator, NoRotation>::value
    >::type>
{
    Backend m_backend;
    files::writer_t<Backend> writer;
    files::flusher_t<Backend> flusher;
    Rotator rotator;
public:
    file_handler_t(const std::string& path, const files::config_t<Rotator>& config) :
        m_backend(path),
        writer(m_backend),
        flusher(config.autoflush, m_backend),
        rotator(config.rotation, m_backend)
    {}

    void handle(const std::string& message) {
        writer.write(message);
        flusher.flush();
        if (rotator.necessary(message)) {
            rotator.rotate();
        }
    }

    const Backend& backend() {
        return m_backend;
    }
};

struct substitute_attribute_t {
    const log::attributes_t& attributes;

    void operator()(aux::attachable_ostringstream& stream, const std::string& placeholder) const {
        auto it = attributes.find(placeholder);
        if (it == attributes.end()) {
            stream.rdbuf()->storage()->append(placeholder);
        } else {
            stream << it->second.value;
        }
    }
};

template<class Backend = files::boost_backend_t, class Rotator = NoRotation>
class files_t {
    typedef file_handler_t<Backend, Rotator> handler_type;
    typedef std::unordered_map<std::string, std::shared_ptr<handler_type>> handlers_type;

    files::config_t<Rotator> config;
    handlers_type m_handlers;
//    aux::formatter_t formatter;
public:
    typedef files::config_t<Rotator> config_type;

    static const char* name() {
        return "files";
    }

    files_t(const config_type& config) :
        config(config)
//        formatter(config.path)
    {}

    void consume(const std::string& message, const log::attributes_t& attributes = log::attributes_t()) {
        auto filename = make_filename(attributes);
        auto it = m_handlers.find(filename);
        if (it == m_handlers.end()) {
            it = m_handlers.insert(it, std::make_pair(filename, std::make_shared<handler_type>(filename, config)));
        }
        it->second->handle(message);
    }

    const handlers_type& handlers() {
        return m_handlers;
    }

    std::string make_filename(const log::attributes_t& attributes) {
        aux::formatter_t formatter(config.path);
        formatter.on_placeholder(substitute_attribute_t { attributes });
        return formatter.execute();
    }
};

} // namespace sink

template<class Backend, class Watcher>
struct unique_id_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef sink::rotator_t<Backend, Watcher> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;

    typedef std::map<std::string, boost::any> variant_map_t;

    static std::string generate(const boost::any& config) {
        const variant_map_t& cfg = boost::any_cast<variant_map_t>(config);

        auto rotation_it = cfg.find("rotation");
        if (rotation_it != cfg.end()) {
            const variant_map_t& rotation = boost::any_cast<variant_map_t>(rotation_it->second);

            const bool has_size_watcher = rotation.find("size") != rotation.end();
            const bool has_datetime_watcher = rotation.find("period") != rotation.end();

            if (has_size_watcher && has_datetime_watcher) {
                throw blackhole::error_t("set watcher is not implemented yet");
            } else if (has_size_watcher) {
                return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "size");
            } else if (has_datetime_watcher) {
                return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), "datetime");
            }

            throw blackhole::error_t("rotation section not properly configures: no watcher settings found");
        }

        return sink_type::name();
    }
};

template<class Backend>
struct config_traits<sink::files_t<Backend, sink::NoRotation>> {
    static std::string name() {
        return sink::files_t<Backend, sink::NoRotation>::name();
    }
};

template<class Backend, class Watcher>
struct config_traits<sink::files_t<Backend, sink::rotator_t<Backend, Watcher>>> {
    typedef sink::rotator_t<Backend, Watcher> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;

    static std::string name() {
        return utils::format("%s/%s/%s", sink_type::name(), rotator_type::name(), Watcher::name());
    }
};

namespace aux {

template<class Backend, class Rotator>
struct filler<sink::files_t<Backend, Rotator>> {
    template<class Extractor, class Config>
    static void extract_to(const Extractor& ex, Config& config) {
        ex["path"].to(config.path);
        ex["autoflush"].to(config.autoflush);
    }
};

template<class Backend, class Watcher>
struct filler<sink::rotator_t<Backend, Watcher>> {
    template<class Extractor, class Config>
    static void extract_to(const Extractor& ex, Config& config) {
        ex["rotation"]["pattern"].to(config.rotation.pattern);
        ex["rotation"]["backups"].to(config.rotation.backups);
    }
};

} // namespace aux

template<class Backend>
struct factory_traits<sink::files_t<Backend>> {
    typedef sink::files_t<Backend> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
    }
};

template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::size_t>>> {
    typedef sink::rotation::watcher::size_t watcher_type;
    typedef sink::rotator_t<Backend, watcher_type> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
        aux::filler<rotator_type>::extract_to(ex, config);
        ex["rotation"]["size"].to(config.rotation.watcher.size);
    }
};

template<class Backend>
struct factory_traits<sink::files_t<Backend, sink::rotator_t<Backend, sink::rotation::watcher::datetime_t<>>>> {
    typedef sink::rotation::watcher::datetime_t<> watcher_type;
    typedef sink::rotator_t<Backend, watcher_type> rotator_type;
    typedef sink::files_t<Backend, rotator_type> sink_type;
    typedef typename sink_type::config_type config_type;

    static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
        aux::filler<sink_type>::extract_to(ex, config);
        aux::filler<rotator_type>::extract_to(ex, config);
        ex["rotation"]["period"].to(config.rotation.watcher.period);
    }
};

} // namespace blackhole
<|endoftext|>


<commit_before>// Project: Parallel Collaborative Ranking with AltSVM and SGD
// Collaborative work by Dohyung Park and Jin Zhang
// Date: 11/26/2014
//
// The script will:
// [1a] solve the problem with alternative rankSVM via liblineaer
// [1b] solve the problem with stochasitic gradient descent in hogwild style
// [1c] solve the problem with stochastic gradient descent in nomad style
//
// Run: ./collrank [training (comparison) file] [test (rating) file] [rank] [num_threads]

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include "problem.hpp"

int main (int argc, char* argv[]) {
  if (argc < 5) {
    cout << "Solve collaborative ranking problem with given training/testing data set" << endl;
    cout << "Usage ./collrank [training (comparison) file] [test (rating) file] [rank] [num_threads]" << endl;
    return 0;
  }

  int rank = atoi(argv[3]);
  double lambda = atof(argv[4]);
  int n_threads = atoi(argv[5]);

  Problem p(rank, n_threads);

  printf("Reading data files..\n");

  p.read_data(argv[1], argv[2]);
  omp_set_dynamic(0);
  omp_set_num_threads(n_threads);

  double time;

  time = omp_get_wtime();
  printf("Running AltSVM with random init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_RANDOM);

  time = omp_get_wtime();
  printf("Running AltSVM with svd init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_SVD);

  time = omp_get_wtime();
  printf("Running AltSVM with all-ones init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_ALLONES);

  time = omp_get_wtime();
  printf("Running Random SGD with SVD init.. \n");
  p.run_sgd_random(L2_HINGE, lambda, 1e-1, 1e-5, INIT_SVD);

/*
  time = omp_get_wtime();
  printf("Running NOMADi SGD.. \n");
  p.run_sgd_nomad_item(100., 1e-1, 1e-5, INIT_RANDOM);

  time = omp_get_wtime();
  printf("Running NOMADu SGD.. \n");
  p.run_sgd_nomad_user(100., 1e-1, 1e-5, INIT_RANDOM);
*/

  return 0;
}
<commit_msg>revised instruction comment<commit_after>// Project: Parallel Collaborative Ranking with AltSVM and SGD
// Collaborative work by Dohyung Park and Jin Zhang
// Date: 11/26/2014
//
// The script will:
// [1a] solve the problem with alternative rankSVM via liblineaer
// [1b] solve the problem with stochasitic gradient descent in hogwild style
// [1c] solve the problem with stochastic gradient descent in nomad style
//
// Run: ./collrank [training (comparison) file] [test (rating) file] [rank] [num_threads]

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include "problem.hpp"

int main (int argc, char* argv[]) {
  if (argc < 5) {
    cout << "Solve collaborative ranking problem with given training/testing data set" << endl;
    cout << "Usage ./collrank [training (comparison) file] [test (rating) file] [rank] [lambda] [num_threads]" << endl;
    return 0;
  }

  int rank = atoi(argv[3]);
  double lambda = atof(argv[4]);
  int n_threads = atoi(argv[5]);

  Problem p(rank, n_threads);

  printf("Reading data files..\n");

  p.read_data(argv[1], argv[2]);
  omp_set_dynamic(0);
  omp_set_num_threads(n_threads);

  double time;

  time = omp_get_wtime();
  printf("Running AltSVM with random init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_RANDOM);

  time = omp_get_wtime();
  printf("Running AltSVM with svd init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_SVD);

  time = omp_get_wtime();
  printf("Running AltSVM with all-ones init.. \n");
	p.run_altsvm(L2_HINGE, lambda, INIT_ALLONES);

  time = omp_get_wtime();
  printf("Running Random SGD with SVD init.. \n");
  p.run_sgd_random(L2_HINGE, lambda, 1e-1, 1e-5, INIT_SVD);

/*
  time = omp_get_wtime();
  printf("Running NOMADi SGD.. \n");
  p.run_sgd_nomad_item(100., 1e-1, 1e-5, INIT_RANDOM);

  time = omp_get_wtime();
  printf("Running NOMADu SGD.. \n");
  p.run_sgd_nomad_user(100., 1e-1, 1e-5, INIT_RANDOM);
*/

  return 0;
}
<|endoftext|>


<commit_before>#include "game.h"
#include "../../visualization/src/visualization.h"
#include "param.h"
#include <fstream>
#include <random>

using namespace std;

namespace mo {
namespace game {
//-----------------------------------------------------------------

Aquarium::Aquarium(const std::string &background_name) {
  background_img_ = imread(background_name);
}

void Aquarium::load_characters(
    const std::vector<std::string> &character_imgnames) {
  for (auto character_imgname : character_imgnames)
    characters_.push_back(Character(character_imgname));
}

void Aquarium::run() {
  static constexpr int dt{10}; // msec
  double time{0.0};            // msec
  std::default_random_engine generator;
  std::normal_distribution<double> distribution(0.0, 0.1);

  while (1) {
    background_img_.copyTo(composite_img_);

    // movement on x,y
    for (auto character : characters_) {
      character.update_position(composite_img_.cols, composite_img_.rows,
                                distribution, generator, dt);
      character.update_shape(time);

      warpAffine(character.img(), composite_img_, character.affine_mat());
    }

    if (show("aquarium", composite_img_, dt) == 'q')
      break;
    time += dt;
  }
} // namespace game

//-----------------------------------------------------------------
Character::Character(const string &image_name) {
  character_img_ = imread(image_name);
}

void Character::update_position(const int bgimg_w, const int bgimg_h,
                                std::normal_distribution<double> &distribution,
                                std::default_random_engine &generator,
                                const int dt) {
  // get an alias
  double &posx = affine_mat_.at<double>(0, 2);
  double &posy = affine_mat_.at<double>(1, 2);

  // add normal distribution to the velocity.
  vx_ += distribution(generator);
  vy_ += distribution(generator);

  // let it stay inside background image.
  if (posx > bgimg_w - character_img_.cols && vx_ > 0 || posx < 0 && vx_ < 0)
    vx_ *= -1;
  if (posy > bgimg_h - character_img_.rows && vy_ > 0 || posy < 0 && vy_ < 0)
    vy_ *= -1;

  // integrate velocity to position.
  posx += vx_ * dt;
  posy += vy_ * dt;
}

void Character::update_shape(const double time) {
  affine_mat_.at<double>(0, 0) = 1 + size_change_ratio_ * sin(time * 0.001);
  affine_mat_.at<double>(1, 1) = 1 + size_change_ratio_ * sin(time * 0.001);
}

} // namespace game
} // namespace mo
<commit_msg>game: debug.<commit_after>#include "game.h"
#include "../../visualization/src/visualization.h"
#include "param.h"
#include <fstream>
#include <random>

using namespace std;

namespace mo {
namespace game {
//-----------------------------------------------------------------

Aquarium::Aquarium(const std::string &background_name) {
  background_img_ = imread(background_name);
}

void Aquarium::load_characters(
    const std::vector<std::string> &character_imgnames) {
  for (auto character_imgname : character_imgnames)
    characters_.push_back(Character(character_imgname));
}

void Aquarium::run() {
  static constexpr int dt{1000}; // msec
  double time{0.0};              // msec
  std::default_random_engine generator;
  std::normal_distribution<double> distribution(0.0, 0.1);

  while (1) {
    background_img_.copyTo(composite_img_);

    // movement on x,y
    for (auto character : characters_) {
      character.update_position(composite_img_.cols, composite_img_.rows,
                                distribution, generator, dt);
      character.update_shape(time);

      warpAffine(character.img(), composite_img_, character.affine_mat());
    }

    if (show("aquarium", composite_img_, dt) == 'q')
      break;
    time += dt;
  }
} // namespace game

//-----------------------------------------------------------------
Character::Character(const string &image_name) {
  character_img_ = imread(image_name);
}

void Character::update_position(const int bgimg_w, const int bgimg_h,
                                std::normal_distribution<double> &distribution,
                                std::default_random_engine &generator,
                                const int dt) {
  // get an alias
  double &posx = affine_mat_.at<double>(0, 2);
  double &posy = affine_mat_.at<double>(1, 2);

  // add normal distribution to the velocity.
  //  vx_ += distribution(generator);
  //  vy_ += distribution(generator);

  // let it stay inside background image.
  if ((posx > bgimg_w - character_img_.cols && vx_ > 0) ||
      (posx < 0 && vx_ < 0))
    vx_ *= -1;
  if ((posy > bgimg_h - character_img_.rows && vy_ > 0) ||
      (posy < 0 && vy_ < 0))
    vy_ *= -1;

  // integrate velocity to position.
  posx += vx_ * dt;
  posy += vy_ * dt;
}

void Character::update_shape(const double time) {
  affine_mat_.at<double>(0, 0) = 1 + size_change_ratio_ * sin(time * 0.001);
  affine_mat_.at<double>(1, 1) = 1 + size_change_ratio_ * sin(time * 0.001);
}

} // namespace game
} // namespace mo
<|endoftext|>


<commit_before>#include "gamemechanics.h"
#include <QPainter>
#include <QtCore/qmath.h>

GameMechanics::GameMechanics(QWidget *parent) :
	QWidget(parent)
{
	imageName = new QString("");
	pieceCount = 3;
	array = new QImage*[pieceCount];
	for (int i = 0; i < pieceCount; i++)
		array[i] = new QImage[pieceCount];
	emptyPeace = QPoint(pieceCount-1,pieceCount-1);
}

//-----------------------------------------

void GameMechanics::mixArray()
{ 	//Начинаем перемешивать части картинок по алгоритму
    int x1,y1,x2,y2;
	for(int x=0;x<pieceCount;x++){
		for(int y=0;y<pieceCount;y++){
            if(y=pieceCount)
                {
                array[x1][y1] = array[x][y];
                array[x][y] = array[x+1][y];
                array[x+1][y]=array[x1][y1];
                }
                else
                   {
                     array[x1][y1] = array[x][y];
                     array[x][y] = array[x][y+1];
                     array[x][y+1] = array[x1][y1];
                    }
		}
	}
    for(int k=0;k<(pieceCount*(rand()%(5)));k++){
       for(y2=0;y2<pieceCount;y2++){
         for(x2=0;x2<pieceCount;x2++){
            if(x2=pieceCount)
                {
                array[x1][y1] = array[x2][y2];
                array[x2][y2] = array[x2][y2+1];
                array[x2][y2+1]=array[x1][y1];
                }
                else
                   {
                     array[x1][y1] = array[x2][y2];
                     array[x2][y2] = array[x2+1][y2];
                     array[x2+1][y2] = array[x1][y1];
                    }
        }
    }
    }
}
//-----------------------------------------

void GameMechanics::imagePressed(QImage &pict1, QImage &pict2)
{
	QImage temp;
	temp=pict1;
	pict1=pict2;
	pict2=temp;

}

//-----------------------------------------

void GameMechanics::newGame(QString* imageName)
{

}

//-----------------------------------------

void GameMechanics::hint()
{

}

//-----------------------------------------

GameMechanics::~GameMechanics()
{
	delete imageName;
	for (int i = 0; i < pieceCount; i++)
		delete[] array[i];
	delete[] array;
}

//-----------------------------------------

void GameMechanics::paintEvent(QPaintEvent *paintEvent)
{
	QPainter painter(this);
	painter.begin(this);
	for(int x = 0;x < pieceCount;x++)
		for(int y = 0;y<pieceCount;y++)
			painter.drawImage(this->width()/pieceCount*x,this->height()/pieceCount*y,array[x][y]);
	painter.end();
}

//-----------------------------------------
<commit_msg>Другой вариант перемешивания с использованием imagePress...<commit_after>#include "gamemechanics.h"
#include <QPainter>
#include <QtCore/qmath.h>

GameMechanics::GameMechanics(QWidget *parent) :
	QWidget(parent)
{
	imageName = new QString("");
	pieceCount = 3;
	array = new QImage*[pieceCount];
	for (int i = 0; i < pieceCount; i++)
		array[i] = new QImage[pieceCount];
	emptyPeace = QPoint(pieceCount-1,pieceCount-1);
}

//-----------------------------------------

void GameMechanics::mixArray()
{ 	//Начинаем перемешивать части картинок по алгоритму
    int x1,y1,x2,y2;
    x1=0;
    y1=0;
	for(int x=0;x<pieceCount;x++){
        for(int y=0;y<(pieceCount+1);y++){
            if(y==pieceCount)
                {
                imagePressed(array[x][y], array[x+1][y]);
                }
                else
                   {
                     imagePressed(array[x][y], array[x][y+1]);
                    }
		}
	}
    for(int k=0;k<(pieceCount*(rand()%(5)));k++){
       for(y2=0;y2<pieceCount;y2++){
         for(x2=0;x2<(pieceCount+1);x2++){
            if(x2==pieceCount)
                {
                imagePressed(array[x2][y2], array[x2][y2+1]);
                }
                else
                   {
                     imagePressed(array[x2][y2], array[x2+1][y2]);
                    }
        }
    }
    }
}
//-----------------------------------------

void GameMechanics::imagePressed(QImage &pict1, QImage &pict2)
{
	QImage temp;
	temp=pict1;
	pict1=pict2;
	pict2=temp;

}

//-----------------------------------------

void GameMechanics::newGame(QString* imageName)
{

}

//-----------------------------------------

void GameMechanics::hint()
{

}

//-----------------------------------------

GameMechanics::~GameMechanics()
{
	delete imageName;
	for (int i = 0; i < pieceCount; i++)
		delete[] array[i];
	delete[] array;
}

//-----------------------------------------

void GameMechanics::paintEvent(QPaintEvent *paintEvent)
{
	QPainter painter(this);
	painter.begin(this);
	for(int x = 0;x < pieceCount;x++)
		for(int y = 0;y<pieceCount;y++)
			painter.drawImage(this->width()/pieceCount*x,this->height()/pieceCount*y,array[x][y]);
	painter.end();
}

//-----------------------------------------
<|endoftext|>


<commit_before>#include "canvas/CanvasContext.h"

#include "SDL_opengles.h"

CanvasContext::CanvasContext ()
{
    CanvasState state;
    state.alpha = 1;
    state.blendMode = 0;
    _states.push(state);
}

void CanvasContext::save ()
{
    glPushMatrix();
    _states.push(_states.top());
}

void CanvasContext::restore ()
{
    glPopMatrix();
    _states.pop();
}

void CanvasContext::scale (float x, float y)
{
    glScalef(x, y, 0);
}

void CanvasContext::rotate (float angle)
{
    glRotatef(angle, 0, 0, 1);
}

void CanvasContext::translate (float x, float y)
{
    glTranslatef(x, y, 0);
}

void CanvasContext::setAlpha (float alpha)
{
    _states.top().alpha = alpha;
}

void CanvasContext::setBlendMode (int blendMode)
{
}

void CanvasContext::drawImage (const Texture* texture, float dx, float dy)
{
    float w = texture->getWidth();
    float h = texture->getHeight();
    CanvasState& state = _states.top();

    GLfloat verts[] = {
        dx, dy,
        dx + w, dy,
        dx, dy + h,
        dx + w, dy + h,
    };
    GLfloat uv[] = {
        0, 0,
        1, 0,
        0, 1,
        1, 1,
    };

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture->getId());
    glVertexPointer(2, GL_FLOAT, 0, verts);
    glEnableClientState(GL_VERTEX_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 0, uv);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    //glColor4f(1, 1, 1, 0.5);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    //glColor4f(1, 1, 1, 1);
    //glDisable(GL_BLEND);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisable(GL_TEXTURE_2D);
}
<commit_msg>A bit of const.<commit_after>#include "canvas/CanvasContext.h"

#include "SDL_opengles.h"

CanvasContext::CanvasContext ()
{
    CanvasState state;
    state.alpha = 1;
    state.blendMode = 0;
    _states.push(state);
}

void CanvasContext::save ()
{
    glPushMatrix();
    _states.push(_states.top());
}

void CanvasContext::restore ()
{
    glPopMatrix();
    _states.pop();
}

void CanvasContext::scale (float x, float y)
{
    glScalef(x, y, 0);
}

void CanvasContext::rotate (float angle)
{
    glRotatef(angle, 0, 0, 1);
}

void CanvasContext::translate (float x, float y)
{
    glTranslatef(x, y, 0);
}

void CanvasContext::setAlpha (float alpha)
{
    _states.top().alpha = alpha;
}

void CanvasContext::setBlendMode (int blendMode)
{
}

void CanvasContext::drawImage (const Texture* texture, float dx, float dy)
{
    float w = texture->getWidth();
    float h = texture->getHeight();
    const CanvasState& state = _states.top();

    GLfloat verts[] = {
        dx, dy,
        dx + w, dy,
        dx, dy + h,
        dx + w, dy + h,
    };
    GLfloat uv[] = {
        0, 0,
        1, 0,
        0, 1,
        1, 1,
    };

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture->getId());
    glVertexPointer(2, GL_FLOAT, 0, verts);
    glEnableClientState(GL_VERTEX_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 0, uv);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    //glEnable(GL_BLEND);
    //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
    //glColor4f(1, 1, 1, 0.5);

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

    //glColor4f(1, 1, 1, 1);
    //glDisable(GL_BLEND);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisable(GL_TEXTURE_2D);
}
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Scheduler class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-08-08
 */

#ifndef INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_

#include "distortos/scheduler/ThreadControlBlockList.hpp"
#include "distortos/scheduler/SoftwareTimerControlBlockSupervisor.hpp"

#include <chrono>

namespace distortos
{

/// scheduler namespace has symbols related to scheduling
namespace scheduler
{

/// Scheduler class is a system's scheduler
class Scheduler
{
public:

	/**
	 * \brief Scheduler's constructor
	 */

	Scheduler();

	/**
	 * \brief Adds new ThreadControlBlock to scheduler.
	 *
	 * ThreadControlBlock's state is changed to "runnable".
	 *
	 * \param [in] thread_control_block is a reference to added ThreadControlBlock object
	 */

	void add(ThreadControlBlock &thread_control_block);

	/**
	 * \brief Blocks current thread, transferring it to provided container.
	 *
	 * \param Container is the type of destination container for current thread
	 *
	 * \param [in] container is a reference to destination container to which the thread will be transferred
	 */

	template<typename Container>
	void block(Container &container)
	{
		container.sortedSplice(runnableList_, currentThreadControlBlock_);
		requestContextSwitch_();
	}

	/**
	 * \return reference to currently active ThreadControlBlock
	 */

	ThreadControlBlock & getCurrentThreadControlBlock() const { return *currentThreadControlBlock_; }

	/**
	 * \return reference to internal SoftwareTimerControlBlockSupervisor object
	 */

	SoftwareTimerControlBlockSupervisor & getSoftwareTimerSupervisor()
	{
		return softwareTimerControlBlockSupervisor_;
	}

	/**
	 * \return const reference to internal SoftwareTimerControlBlockSupervisor object
	 */

	const SoftwareTimerControlBlockSupervisor & getSoftwareTimerSupervisor() const
	{
		return softwareTimerControlBlockSupervisor_;
	}

	/**
	 * \return current value of tick count
	 */

	uint64_t getTickCount() const;

	/**
	 * \brief Makes the calling (current) thread sleep for at least given number of ticks.
	 *
	 * Current thread's state is changed to "sleeping".
	 *
	 * \note To fulfill the "at least" requirement, one additional tick is always added to the sleep duration.
	 *
	 * \param [in] ticks is the number of ticks after which the thread will be woken
	 */

	void sleepFor(uint64_t ticks);

	/**
	 * \brief Makes the calling (current) thread sleep until some tick value is reached.
	 *
	 * Current thread's state is changed to "sleeping".
	 *
	 * \param [in] tick_value is the tick value at which the thread will be woken
	 */

	void sleepUntil(uint64_t tick_value);

	/**
	 * \brief Starts scheduling.
	 *
	 * Initializes scheduler and all required hardware/software to perform context switching and starts the scheduling.
	 */

	__attribute__ ((noreturn))
	void start();

	/**
	 * \brief Called by architecture-specific code to do final context switch.
	 *
	 * Current task is suspended and the next available task is started.
	 *
	 * \param [in] stack_pointer is the current value of current thread's stack pointer
	 *
	 * \return new thread's stack pointer
	 */

	void * switchContext(void *stack_pointer);

	/**
	 * \brief Handler of "tick" interrupt.
	 *
	 * \note this must not be called by user code
	 *
	 * \return true if context switch is required, false otherwise
	 */

	bool tickInterruptHandler();

	/**
	 * \brief Unblocks provided thread, transferring it from provided container to "runnable" container.
	 *
	 * \param Container is the type of source container of unblocked thread
	 * \param Iterator is the type of iterator which points to unblocked thread
	 *
	 * \param [in] container is a reference to source container from which the thread will be transferred
	 * \param [in] iterator is the iterator which points to unblocked thread
	 *
	 */

	template<typename Container, typename Iterator>
	void unblock(Container &container, Iterator iterator)
	{
		runnableList_.sortedSplice(container, iterator);
		yield();
	}

	/**
	 * \brief Yields time slot of the scheduler to next thread.
	 */

	void yield() const;

private:

	/// generic iterator for all variants of ThreadControlBlockList
	using Iterator = containers::SortedContainerBase<std::list<ThreadControlBlockListValueType>>::iterator;

	/**
	 * \brief Tests whether context switch is required or not.
	 *
	 * Context switch is required in following situations:
	 * - current thread is no longer in "runnable" state,
	 * - there is a higher-priority thread available,
	 * - current thread used its round-robin quantum and same-priority thread is available.
	 *
	 * \return true if context switch is required
	 */

	bool isContextSwitchRequired_() const;

	/**
	 * \brief Requests unconditional context switch.
	 *
	 * Wrapper for architecture::requestContextSwitch()
	 */

	void requestContextSwitch_() const;

	/// iterator to the currently active ThreadControlBlock
	Iterator currentThreadControlBlock_;

	/// list of ThreadControlBlock elements in "runnable" state, sorted by priority in descending order
	ThreadControlBlockList runnableList_;

	/// internal SoftwareTimerControlBlockSupervisor object
	SoftwareTimerControlBlockSupervisor softwareTimerControlBlockSupervisor_;

	/// tick count
	uint64_t tickCount_;
};

}	// namespace scheduler

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_
<commit_msg>scheduler: disallow any blocks/unblocks from lists of different type<commit_after>/**
 * \file
 * \brief Scheduler class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-08-08
 */

#ifndef INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_

#include "distortos/scheduler/ThreadControlBlockList.hpp"
#include "distortos/scheduler/SoftwareTimerControlBlockSupervisor.hpp"

#include <chrono>

namespace distortos
{

/// scheduler namespace has symbols related to scheduling
namespace scheduler
{

/// Scheduler class is a system's scheduler
class Scheduler
{
public:

	/**
	 * \brief Scheduler's constructor
	 */

	Scheduler();

	/**
	 * \brief Adds new ThreadControlBlock to scheduler.
	 *
	 * ThreadControlBlock's state is changed to "runnable".
	 *
	 * \param [in] thread_control_block is a reference to added ThreadControlBlock object
	 */

	void add(ThreadControlBlock &thread_control_block);

	/**
	 * \brief Blocks current thread, transferring it to provided container.
	 *
	 * \param [in] container is a reference to destination container to which the thread will be transferred
	 */

	void block(ThreadControlBlockList &container)
	{
		container.sortedSplice(runnableList_, currentThreadControlBlock_);
		requestContextSwitch_();
	}

	/**
	 * \return reference to currently active ThreadControlBlock
	 */

	ThreadControlBlock & getCurrentThreadControlBlock() const { return *currentThreadControlBlock_; }

	/**
	 * \return reference to internal SoftwareTimerControlBlockSupervisor object
	 */

	SoftwareTimerControlBlockSupervisor & getSoftwareTimerSupervisor()
	{
		return softwareTimerControlBlockSupervisor_;
	}

	/**
	 * \return const reference to internal SoftwareTimerControlBlockSupervisor object
	 */

	const SoftwareTimerControlBlockSupervisor & getSoftwareTimerSupervisor() const
	{
		return softwareTimerControlBlockSupervisor_;
	}

	/**
	 * \return current value of tick count
	 */

	uint64_t getTickCount() const;

	/**
	 * \brief Makes the calling (current) thread sleep for at least given number of ticks.
	 *
	 * Current thread's state is changed to "sleeping".
	 *
	 * \note To fulfill the "at least" requirement, one additional tick is always added to the sleep duration.
	 *
	 * \param [in] ticks is the number of ticks after which the thread will be woken
	 */

	void sleepFor(uint64_t ticks);

	/**
	 * \brief Makes the calling (current) thread sleep until some tick value is reached.
	 *
	 * Current thread's state is changed to "sleeping".
	 *
	 * \param [in] tick_value is the tick value at which the thread will be woken
	 */

	void sleepUntil(uint64_t tick_value);

	/**
	 * \brief Starts scheduling.
	 *
	 * Initializes scheduler and all required hardware/software to perform context switching and starts the scheduling.
	 */

	__attribute__ ((noreturn))
	void start();

	/**
	 * \brief Called by architecture-specific code to do final context switch.
	 *
	 * Current task is suspended and the next available task is started.
	 *
	 * \param [in] stack_pointer is the current value of current thread's stack pointer
	 *
	 * \return new thread's stack pointer
	 */

	void * switchContext(void *stack_pointer);

	/**
	 * \brief Handler of "tick" interrupt.
	 *
	 * \note this must not be called by user code
	 *
	 * \return true if context switch is required, false otherwise
	 */

	bool tickInterruptHandler();

	/**
	 * \brief Unblocks provided thread, transferring it from provided container to "runnable" container.
	 *
	 * \param [in] container is a reference to source container from which the thread will be transferred
	 * \param [in] iterator is the iterator which points to unblocked thread
	 *
	 */

	void unblock(ThreadControlBlockList &container, const ThreadControlBlockList::iterator iterator)
	{
		runnableList_.sortedSplice(container, iterator);
		yield();
	}

	/**
	 * \brief Yields time slot of the scheduler to next thread.
	 */

	void yield() const;

private:

	/// generic iterator for all variants of ThreadControlBlockList
	using Iterator = containers::SortedContainerBase<std::list<ThreadControlBlockListValueType>>::iterator;

	/**
	 * \brief Tests whether context switch is required or not.
	 *
	 * Context switch is required in following situations:
	 * - current thread is no longer in "runnable" state,
	 * - there is a higher-priority thread available,
	 * - current thread used its round-robin quantum and same-priority thread is available.
	 *
	 * \return true if context switch is required
	 */

	bool isContextSwitchRequired_() const;

	/**
	 * \brief Requests unconditional context switch.
	 *
	 * Wrapper for architecture::requestContextSwitch()
	 */

	void requestContextSwitch_() const;

	/// iterator to the currently active ThreadControlBlock
	Iterator currentThreadControlBlock_;

	/// list of ThreadControlBlock elements in "runnable" state, sorted by priority in descending order
	ThreadControlBlockList runnableList_;

	/// internal SoftwareTimerControlBlockSupervisor object
	SoftwareTimerControlBlockSupervisor softwareTimerControlBlockSupervisor_;

	/// tick count
	uint64_t tickCount_;
};

}	// namespace scheduler

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SCHEDULER_SCHEDULER_HPP_
<|endoftext|>


<commit_before>// Day11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main()
{
	const StringVector Lines = GetFileLines("Input.txt");
	const std::string & Input = Lines[0];
	auto Position = std::make_pair( 0, 0 );

	for (auto It = std::begin(Input); It != std::end(Input);)
	{
		int X = 0;
		int Y = (*(It++) == 'n') ? 2 : -2;

		if(It != std::end(Input) && (*It != ','))
		{
			X = (*(It++) == 'e') ? 1 : -1;
			Y /= 2;
		}

		if (It != std::end(Input))
			++It;

		Position.first += X;
		Position.second += Y;
	}

	std::cout << "Steps: " << ((std::abs(Position.first) + std::abs(Position.second)) / 2 ) << std::endl;

	system("pause");
    return 0;
}

<commit_msg>Day 11 part two<commit_after>// Day11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int StepsAway(const std::pair<int, int> & Position)
{
	return ((std::abs(Position.first) + std::abs(Position.second)) / 2);
}

int main()
{
	const StringVector Lines = GetFileLines("Input.txt");
	const std::string & Input = Lines[0];
	auto Position = std::make_pair( 0, 0 );
	int MaxSteps = 0;

	for (auto It = std::begin(Input); It != std::end(Input);)
	{
		int X = 0;
		int Y = (*(It++) == 'n') ? 2 : -2;

		if(It != std::end(Input) && (*It != ','))
		{
			X = (*(It++) == 'e') ? 1 : -1;
			Y /= 2;
		}

		if (It != std::end(Input))
			++It;

		Position.first += X;
		Position.second += Y;

		MaxSteps = std::max(MaxSteps, StepsAway(Position));
	}

	std::cout << "Steps: " << StepsAway(Position) << std::endl;
	std::cout << "Max steps away: " << MaxSteps << std::endl;

	system("pause");
    return 0;
}

<|endoftext|>


<commit_before>#include "deck-selector.h"

typedef std::vector<CardSelector> CardSelectors;

DeckAbstractSelector::DeckAbstractSelector(const CardSelectors& selectors,
                                           std::size_t from, std::size_t to)
        : cardSelectors(selectors), from(from), to(to) {
}

DeckAbstractSelector::DeckAbstractSelector(CardSelectors&& selectors, std::size_t from,
                                           std::size_t to)
        : cardSelectors(selectors), from(from), to(to) {
}

void DeckSelectors::AddDeckSelector(std::unique_ptr<DeckAbstractSelector>&& selector) {
    deckSelectors.push_back(std::move(selector));
}

bool DeckSelectors::IsEmpty() const {
    return deckSelectors.empty();
}

DeckAllSelector::DeckAllSelector(const CardSelectors& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {
}

DeckAllSelector::DeckAllSelector(CardSelectors&& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {
}

bool DeckAllSelector::CheckPart(const std::vector<Card>& deckPart) const {
    for (auto& selector : cardSelectors) {
        for (auto& card : deckPart) {
            if (!selector.Check(card))
                return false;
        }
    }
    return true;
}

DeckOneSelector::DeckOneSelector(const CardSelectors& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {
}

DeckOneSelector::DeckOneSelector(CardSelectors&& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {
}

bool DeckOneSelector::CheckPart(const std::vector<Card>& deckPart) const {
    for (auto& selector : cardSelectors) {
        for (auto& card : deckPart) {
            if (selector.Check(card))
                return true;
        }
    }
    return false;
}
<commit_msg>Style fixes<commit_after>#include "deck-selector.h"

typedef std::vector<CardSelector> CardSelectors;

DeckAbstractSelector::DeckAbstractSelector(const CardSelectors& selectors,
                                           std::size_t from, std::size_t to)
        : cardSelectors(selectors), from(from), to(to) {}

DeckAbstractSelector::DeckAbstractSelector(CardSelectors&& selectors, std::size_t from,
                                           std::size_t to)
        : cardSelectors(selectors), from(from), to(to) {}

void DeckSelectors::AddDeckSelector(std::unique_ptr<DeckAbstractSelector>&& selector) {
    deckSelectors.push_back(std::move(selector));
}

bool DeckSelectors::IsEmpty() const {
    return deckSelectors.empty();
}

DeckAllSelector::DeckAllSelector(const CardSelectors& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {}

DeckAllSelector::DeckAllSelector(CardSelectors&& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {}

bool DeckAllSelector::CheckPart(const std::vector<Card>& deckPart) const {
    for (auto& selector : cardSelectors) {
        for (auto& card : deckPart) {
            if (!selector.Check(card))
                return false;
        }
    }
    return true;
}

DeckOneSelector::DeckOneSelector(const CardSelectors& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {}

DeckOneSelector::DeckOneSelector(CardSelectors&& selectors, std::size_t from,
                                 std::size_t to)
        : DeckAbstractSelector(selectors, from, to) {}

bool DeckOneSelector::CheckPart(const std::vector<Card>& deckPart) const {
    for (auto& selector : cardSelectors) {
        for (auto& card : deckPart) {
            if (selector.Check(card))
                return true;
        }
    }
    return false;
}
<|endoftext|>


<commit_before>
#pragma once

#include "base/mappable.hpp"
#include "base/not_constructible.hpp"
#include "geometry/barycentre_calculator.hpp"
#include "geometry/point.hpp"
#include "serialization/geometry.pb.h"

namespace principia {

namespace testing_utilities {
FORWARD_DECLARE_FROM(componentwise,
                     TEMPLATE(typename PairType) class,
                     ComponentwiseMatcher2Impl);
}  // namespace testing_utilities

namespace geometry {
namespace internal_pair {

using base::not_constructible;
using base::not_null;
using quantities::Product;
using quantities::Quotient;

template<typename T1, typename T2>
class Pair;

// A template to peel off the affine layer (i.e., the class Point) if any.
template<typename T>
struct vector_of : not_constructible {
  using type = T;
};

template<typename T1, typename T2>
struct vector_of<Pair<T1, T2>> : not_constructible {
  using type = Pair<typename vector_of<T1>::type, typename vector_of<T2>::type>;
};

template<typename T>
struct vector_of<Point<T>> : not_constructible {
  using type = T;
};

// A template to enable declarations on affine pairs (i.e., when one of the
// components is a Point).
template<typename T>
struct enable_if_affine : not_constructible {};

template<typename T1, typename T2>
struct enable_if_affine<Pair<Point<T1>, T2>> : not_constructible {
  using type = Pair<Point<T1>, T2>;
};

template<typename T1, typename T2>
struct enable_if_affine<Pair<T1, Point<T2>>> : not_constructible {
  using type = Pair<T1, Point<T2>>;
};

template<typename T1, typename T2>
struct enable_if_affine<Pair<Point<T1>, Point<T2>>> : not_constructible {
  using type = Pair<Point<T1>, Point<T2>>;
};

// A template to enable declarations on vector pairs (i.e., when none of the
// components is a Point).
template<typename T, typename U = T>
struct enable_if_vector : not_constructible {
  using type = U;
};

template<typename T1, typename T2>
struct enable_if_vector<Pair<Point<T1>, T2>> : not_constructible {};

template<typename T1, typename T2>
struct enable_if_vector<Pair<T1, Point<T2>>> :not_constructible {};

template<typename T1, typename T2>
struct enable_if_vector<Pair<Point<T1>, Point<T2>>> : not_constructible {};

// This class represents a pair of two values which can be members of an affine
// space (i.e., Points) or of a vector space (such as double, Quantity, Vector,
// Bivector or Trivector).  Only the operations that make sense are defined,
// depending on the nature of the parameters T1 and T2.
template<typename T1, typename T2>
class Pair {
 public:
  Pair(T1 const& t1, T2 const& t2);
  virtual ~Pair() = default;

  Pair operator+(typename vector_of<Pair>::type const& right) const;
  Pair operator-(typename vector_of<Pair>::type const& right) const;

  Pair& operator+=(typename vector_of<Pair>::type const& right);
  Pair& operator-=(typename vector_of<Pair>::type const& right);

  bool operator==(Pair const& right) const;
  bool operator!=(Pair const& right) const;

  void WriteToMessage(not_null<serialization::Pair*> message) const;
  template<typename U1 = T1,
           typename U2 = T2,
           typename = std::enable_if_t<base::is_serializable_v<U1> &&
                                       base::is_serializable_v<U2>>>
  static Pair ReadFromMessage(serialization::Pair const& message);

 protected:
  // The subclasses can access the members directly to implement accessors.
  T1 t1_;
  T2 t2_;

 private:
  // This is needed so that different instantiations of Pair can access the
  // members.
  template<typename U1, typename U2>
  friend class Pair;

  // This is needed to specialize BarycentreCalculator.
  template<typename V, typename S>
  friend class geometry::BarycentreCalculator;

  // This is needed to make Pair mappable.
  template<typename Functor, typename T, typename>
  friend struct base::Mappable;

  // This is needed for testing.
  template<typename PairType>
  friend class testing_utilities::internal_componentwise::
      ComponentwiseMatcher2Impl;

  template<typename U1, typename U2>
  friend typename vector_of<Pair<U1, U2>>::type operator-(
      typename enable_if_affine<Pair<U1, U2>>::type const& left,
      Pair<U1, U2> const& right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type operator+(
      Pair<U1, U2> const& right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type operator-(
      Pair<U1, U2> const& right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Product<Scalar, U1>, Product<Scalar, U2>>>::type
  operator*(Scalar left, Pair<U1, U2> const& right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Product<U1, Scalar>, Product<U2, Scalar>>>::type
  operator*(Pair<U1, U2> const& left, Scalar right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Quotient<U1, Scalar>, Quotient<U2, Scalar>>>::type
  operator/(Pair<U1, U2> const& left, Scalar right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type& operator*=(
      Pair<U1, U2>& left,
      double right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type& operator/=(
      Pair<U1, U2>& left,
      double right);

  template<typename U1, typename U2>
  friend std::ostream& operator<<(std::ostream& out, Pair<U1, U2> const& pair);
};

template<typename T1, typename T2>
typename vector_of<Pair<T1, T2>>::type operator-(
    typename enable_if_affine<Pair<T1, T2>>::type const& left,
    Pair<T1, T2> const& right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type operator+(
    Pair<T1, T2> const& right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type operator-(
    Pair<T1, T2> const& right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Product<Scalar, T1>, Product<Scalar, T2>>>::type
operator*(Scalar left, Pair<T1, T2> const& right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Product<T1, Scalar>, Product<T2, Scalar>>>::type
operator*(Pair<T1, T2> const& left, Scalar right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Quotient<T1, Scalar>, Quotient<T2, Scalar>>>::type
operator/(Pair<T1, T2> const& left, Scalar right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type& operator*=(Pair<T1, T2>& left,
                                                          double right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type& operator/=(Pair<T1, T2>& left,
                                                          double right);

template<typename T1, typename T2>
std::ostream& operator<<(std::ostream& out, Pair<T1, T2> const& pair);

}  // namespace internal_pair

using internal_pair::enable_if_vector;
using internal_pair::Pair;
using internal_pair::vector_of;

// Specialize BarycentreCalculator to make it applicable to Pairs.
namespace internal_barycentre_calculator {

template<typename T1, typename T2, typename Weight>
class BarycentreCalculator<Pair<T1, T2>, Weight> final {
 public:
  BarycentreCalculator() = default;

  void Add(Pair<T1, T2> const& pair, Weight const& weight);
  Pair<T1, T2> Get() const;

  Weight const& weight() const;

 private:
  bool empty_ = true;
  Product<typename vector_of<T1>::type, Weight> t1_weighted_sum_;
  Product<typename vector_of<T2>::type, Weight> t2_weighted_sum_;
  Weight weight_;

  // We need reference values to convert points into vectors, if needed.  We
  // pick default-constructed objects as they don't introduce any inaccuracies
  // in the computations.
  static T1 const reference_t1_;
  static T2 const reference_t2_;
};

}  // namespace internal_barycentre_calculator
}  // namespace geometry

// Reopen the base namespace to make Pairs of vectors mappable.
namespace base {

template<typename Functor, typename T1, typename T2>
class Mappable<Functor,
               geometry::Pair<T1, T2>,
               typename geometry::enable_if_vector<
                   geometry::Pair<T1, T2>, void>::type> {
 public:
  using type = geometry::Pair<
                   decltype(std::declval<Functor>()(std::declval<T1>())),
                   decltype(std::declval<Functor>()(std::declval<T2>()))>;

  static type Do(Functor const& functor,
                 geometry::Pair<T1, T2> const& pair);
};

}  // namespace base
}  // namespace principia

#include "geometry/pair_body.hpp"
<commit_msg>enable_if_vector<commit_after>
#pragma once

#include "base/mappable.hpp"
#include "base/not_constructible.hpp"
#include "geometry/barycentre_calculator.hpp"
#include "geometry/point.hpp"
#include "geometry/traits.hpp"
#include "serialization/geometry.pb.h"

namespace principia {

namespace testing_utilities {
FORWARD_DECLARE_FROM(componentwise,
                     TEMPLATE(typename PairType) class,
                     ComponentwiseMatcher2Impl);
}  // namespace testing_utilities

namespace geometry {
namespace internal_pair {

using base::not_constructible;
using base::not_null;
using quantities::Product;
using quantities::Quotient;

template<typename T1, typename T2>
class Pair;

// A template to peel off the affine layer (i.e., the class Point) if any.
template<typename T>
struct vector_of : not_constructible {
  using type = T;
};

template<typename T1, typename T2>
struct vector_of<Pair<T1, T2>> : not_constructible {
  using type = Pair<typename vector_of<T1>::type, typename vector_of<T2>::type>;
};

template<typename T>
struct vector_of<Point<T>> : not_constructible {
  using type = T;
};

// A template to enable declarations on affine pairs (i.e., when one of the
// components is a Point).
template<typename T>
struct enable_if_affine : not_constructible {};

template<typename T1, typename T2>
struct enable_if_affine<Pair<Point<T1>, T2>> : not_constructible {
  using type = Pair<Point<T1>, T2>;
};

template<typename T1, typename T2>
struct enable_if_affine<Pair<T1, Point<T2>>> : not_constructible {
  using type = Pair<T1, Point<T2>>;
};

template<typename T1, typename T2>
struct enable_if_affine<Pair<Point<T1>, Point<T2>>> : not_constructible {
  using type = Pair<Point<T1>, Point<T2>>;
};

// A template to enable declarations on vector pairs (i.e., when both of the
// components are vectors).
template<typename T, typename U = T, typename = void>
struct enable_if_vector;

template<typename T1, typename T2, typename U>
struct enable_if_vector<
    Pair<T1, T2>, U,
    std::enable_if_t<std::conjunction_v<is_vector<T1>, is_vector<T2>>>>
    : not_constructible {
  using type = U;
};

// This class represents a pair of two values which can be members of an affine
// space (i.e., Points) or of a vector space (such as double, Quantity, Vector,
// Bivector or Trivector).  Only the operations that make sense are defined,
// depending on the nature of the parameters T1 and T2.
template<typename T1, typename T2>
class Pair {
 public:
  Pair(T1 const& t1, T2 const& t2);
  virtual ~Pair() = default;

  Pair operator+(typename vector_of<Pair>::type const& right) const;
  Pair operator-(typename vector_of<Pair>::type const& right) const;

  Pair& operator+=(typename vector_of<Pair>::type const& right);
  Pair& operator-=(typename vector_of<Pair>::type const& right);

  bool operator==(Pair const& right) const;
  bool operator!=(Pair const& right) const;

  void WriteToMessage(not_null<serialization::Pair*> message) const;
  template<typename U1 = T1,
           typename U2 = T2,
           typename = std::enable_if_t<base::is_serializable_v<U1> &&
                                       base::is_serializable_v<U2>>>
  static Pair ReadFromMessage(serialization::Pair const& message);

 protected:
  // The subclasses can access the members directly to implement accessors.
  T1 t1_;
  T2 t2_;

 private:
  // This is needed so that different instantiations of Pair can access the
  // members.
  template<typename U1, typename U2>
  friend class Pair;

  // This is needed to specialize BarycentreCalculator.
  template<typename V, typename S>
  friend class geometry::BarycentreCalculator;

  // This is needed to make Pair mappable.
  template<typename Functor, typename T, typename>
  friend struct base::Mappable;

  // This is needed for testing.
  template<typename PairType>
  friend class testing_utilities::internal_componentwise::
      ComponentwiseMatcher2Impl;

  template<typename U1, typename U2>
  friend typename vector_of<Pair<U1, U2>>::type operator-(
      typename enable_if_affine<Pair<U1, U2>>::type const& left,
      Pair<U1, U2> const& right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type operator+(
      Pair<U1, U2> const& right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type operator-(
      Pair<U1, U2> const& right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Product<Scalar, U1>, Product<Scalar, U2>>>::type
  operator*(Scalar left, Pair<U1, U2> const& right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Product<U1, Scalar>, Product<U2, Scalar>>>::type
  operator*(Pair<U1, U2> const& left, Scalar right);

  template<typename Scalar, typename U1, typename U2>
  friend typename enable_if_vector<
      Pair<U1, U2>,
      Pair<Quotient<U1, Scalar>, Quotient<U2, Scalar>>>::type
  operator/(Pair<U1, U2> const& left, Scalar right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type& operator*=(
      Pair<U1, U2>& left,
      double right);

  template<typename U1, typename U2>
  friend typename enable_if_vector<Pair<U1, U2>>::type& operator/=(
      Pair<U1, U2>& left,
      double right);

  template<typename U1, typename U2>
  friend std::ostream& operator<<(std::ostream& out, Pair<U1, U2> const& pair);
};

template<typename T1, typename T2>
typename vector_of<Pair<T1, T2>>::type operator-(
    typename enable_if_affine<Pair<T1, T2>>::type const& left,
    Pair<T1, T2> const& right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type operator+(
    Pair<T1, T2> const& right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type operator-(
    Pair<T1, T2> const& right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Product<Scalar, T1>, Product<Scalar, T2>>>::type
operator*(Scalar left, Pair<T1, T2> const& right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Product<T1, Scalar>, Product<T2, Scalar>>>::type
operator*(Pair<T1, T2> const& left, Scalar right);

template<typename Scalar, typename T1, typename T2>
typename enable_if_vector<
    Pair<T1, T2>,
    Pair<Quotient<T1, Scalar>, Quotient<T2, Scalar>>>::type
operator/(Pair<T1, T2> const& left, Scalar right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type& operator*=(Pair<T1, T2>& left,
                                                          double right);

template<typename T1, typename T2>
typename enable_if_vector<Pair<T1, T2>>::type& operator/=(Pair<T1, T2>& left,
                                                          double right);

template<typename T1, typename T2>
std::ostream& operator<<(std::ostream& out, Pair<T1, T2> const& pair);

}  // namespace internal_pair

using internal_pair::enable_if_vector;
using internal_pair::Pair;
using internal_pair::vector_of;

// Specialize BarycentreCalculator to make it applicable to Pairs.
namespace internal_barycentre_calculator {

template<typename T1, typename T2, typename Weight>
class BarycentreCalculator<Pair<T1, T2>, Weight> final {
 public:
  BarycentreCalculator() = default;

  void Add(Pair<T1, T2> const& pair, Weight const& weight);
  Pair<T1, T2> Get() const;

  Weight const& weight() const;

 private:
  bool empty_ = true;
  Product<typename vector_of<T1>::type, Weight> t1_weighted_sum_;
  Product<typename vector_of<T2>::type, Weight> t2_weighted_sum_;
  Weight weight_;

  // We need reference values to convert points into vectors, if needed.  We
  // pick default-constructed objects as they don't introduce any inaccuracies
  // in the computations.
  static T1 const reference_t1_;
  static T2 const reference_t2_;
};

}  // namespace internal_barycentre_calculator
}  // namespace geometry

// Reopen the base namespace to make Pairs of vectors mappable.
namespace base {

template<typename Functor, typename T1, typename T2>
class Mappable<Functor,
               geometry::Pair<T1, T2>,
               typename geometry::enable_if_vector<
                   geometry::Pair<T1, T2>, void>::type> {
 public:
  using type = geometry::Pair<
                   decltype(std::declval<Functor>()(std::declval<T1>())),
                   decltype(std::declval<Functor>()(std::declval<T2>()))>;

  static type Do(Functor const& functor,
                 geometry::Pair<T1, T2> const& pair);
};

}  // namespace base
}  // namespace principia

#include "geometry/pair_body.hpp"
<|endoftext|>


<commit_before>#include <iostream>
#include "MySpellChecker.h"

using namespace std;

int main () {
	cout<<"==== Part I ====\n";
	MySpellChecker checker;

	//todo: интерактив с пользователем
	string full_path = "input_dictionary_full.txt";
	string document_path = "input.txt";
	checker.readDictionaryFile(full_path);
	checker.readDocumentationFile(document_path);
	checker.compare();
	system("pause");
	return EXIT_SUCCESS;
}

//int main () {
//	AVLtree<int>* test_tree = new AVLtree<int>();
//	for (int i =127; i > 0; i--)
//		test_tree->insert(i);
//
//	for (int i =127; i > 0; i--)
//		test_tree->insert(i);
//
//	for (int i =1; i < 128; i++)
//		test_tree->insert(i);
//	test_tree->print_tree();
//	cout<<"ROOT: "<<test_tree->root->key <<"\tHeight: "<< (int)test_tree->root -> height<<" "<<test_tree->getSize()<<endl;
//
//	delete test_tree;
//
//	system("pause");
//	return EXIT_SUCCESS;
//}<commit_msg>Добавлены сообщения в консоль о ходе выполнения операций<commit_after>#include <iostream>
#include "MySpellChecker.h"

using namespace std;

int main () {
	setlocale(LC_ALL, "Russian");
	cout<<"==== Part I ====\n";
	MySpellChecker checker;

	//todo: интерактив с пользователем
	string full_path = "input_dictionary_full.txt";
	string document_path = "input.txt";
	cout<<"Считывание словаря...\n";
	checker.readDictionaryFile(full_path);
	cout<<"Считывание документа...\n";
	checker.readDocumentationFile(document_path);
	cout<<"Обработка документа...\n";
	checker.compare();
	system("pause");
	return EXIT_SUCCESS;
}

//int main () {
//	AVLtree<int>* test_tree = new AVLtree<int>();
//	for (int i =127; i > 0; i--)
//		test_tree->insert(i);
//
//	for (int i =127; i > 0; i--)
//		test_tree->insert(i);
//
//	for (int i =1; i < 128; i++)
//		test_tree->insert(i);
//	test_tree->print_tree();
//	cout<<"ROOT: "<<test_tree->root->key <<"\tHeight: "<< (int)test_tree->root -> height<<" "<<test_tree->getSize()<<endl;
//
//	delete test_tree;
//
//	system("pause");
//	return EXIT_SUCCESS;
//}<|endoftext|>