<commit_before>/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"

#include "onlogrotate_job.hxx"
#include "config.hxx"
#include "logpacker.hxx"
#include "logstorage.hxx"
#include "soaprequest.hxx"
#include "soapsender.hxx"

#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <osl/mutex.hxx>
#include <osl/thread.hxx>
#include <osl/time.h>
#include <cppuhelper/implbase1.hxx>
#include <memory>

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::uno;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::frame::XDesktop;
using ::com::sun::star::ucb::XSimpleFileAccess;
using ::rtl::OUString;
using ::std::vector;

namespace
{
    using namespace oooimprovement;

    static void packLogs(const Reference<XMultiServiceFactory>& sf)
    {
        try
        {
            Config config(sf);
            LogPacker log_packer(sf);
            vector<OUString> csvfiles = LogStorage(sf).getUnzippedLogFiles();
            for(
                vector<OUString>::iterator item = csvfiles.begin();
                item!=csvfiles.end();
                item++)
                config.incrementEventCount(log_packer.pack(*item));
        } catch(...) {};
    };

    static void uploadLogs(const Reference<XMultiServiceFactory>& sf)
    {
        try
        {
            Config config(sf);
            Reference<XSimpleFileAccess> file_access(
                sf->createInstance(OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess")),
                UNO_QUERY_THROW);
            SoapSender sender(sf, config.getSoapUrl());
            OUString soap_id = config.getSoapId();
            vector<OUString> zipfiles = LogStorage(sf).getZippedLogFiles();
            for(
                vector<OUString>::iterator item = zipfiles.begin();
                item!=zipfiles.end();
                item++)
            {
                if(config.incrementFailedAttempts(1) > 25)
                {
                    config.giveupUploading();
                    LogStorage(sf).clear();
                    return;
                }
                sender.send(SoapRequest(sf, soap_id, *item));
                config.incrementReportCount(1);
                file_access->kill(*item);
                config.resetFailedAttempts();
            }
        } catch(...) {};
    }

    class OnLogRotateThread : public ::osl::Thread
    {
        public:
            OnLogRotateThread(Reference<XMultiServiceFactory> sf);
            virtual void SAL_CALL run();
            OnLogRotateThread* disposing();

        private:
            Reference<XMultiServiceFactory> m_ServiceFactory;
            ::osl::Mutex m_ServiceFactoryMutex;
    };

    OnLogRotateThread::OnLogRotateThread(Reference<XMultiServiceFactory> sf)
        : m_ServiceFactory(sf)
    { }

    void SAL_CALL OnLogRotateThread::run()
    {
        {
            ::osl::Thread::yield();
            TimeValue wait_intervall = {30,0};
            osl_waitThread(&wait_intervall);
        }
        {
            ::osl::Guard< ::osl::Mutex> service_factory_guard(m_ServiceFactoryMutex);
            try
            {
                if(m_ServiceFactory.is())
                {
                    if(Config(m_ServiceFactory).getInvitationAccepted())
                    {
                        packLogs(m_ServiceFactory);
                        uploadLogs(m_ServiceFactory);
                    }
                    else
                        LogStorage(m_ServiceFactory).clear();
                }
                m_ServiceFactory.clear();
            }
            catch(...) {}
        }
    }

    OnLogRotateThread* OnLogRotateThread::disposing()
    {
        ::osl::Guard< ::osl::Mutex> service_factory_guard(m_ServiceFactoryMutex);
        m_ServiceFactory.clear();
        return this;
    }

    class OnLogRotateThreadWatcher : public ::cppu::WeakImplHelper1<XTerminateListener>
    {
        public:
            OnLogRotateThreadWatcher(Reference<XMultiServiceFactory> sf)
                : m_Thread(new OnLogRotateThread(sf))
            {
                m_Thread->create();
            }
            virtual ~OnLogRotateThreadWatcher()
            {
                m_Thread->disposing()->terminate();
                m_Thread->join();
            };

            // XTerminateListener
            virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException)
                { };
            virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException)
            {
                m_Thread->disposing()->terminate();
                m_Thread->join();
            };
            // XEventListener
            virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException)
            {
                m_Thread->disposing()->terminate();
                m_Thread->join();
            };
        private:
            ::std::auto_ptr<OnLogRotateThread> m_Thread;
    };
}

namespace oooimprovement
{
    OnLogRotateJob::OnLogRotateJob(const Reference<XComponentContext>& context)
        : m_ServiceFactory(Reference<XMultiServiceFactory>(
            context->getServiceManager()->createInstanceWithContext(
                OUString::createFromAscii("com.sun.star.lang.XMultiServiceFactory"), context),
            UNO_QUERY))
    { }

    OnLogRotateJob::OnLogRotateJob(const Reference<XMultiServiceFactory>& sf)
        : m_ServiceFactory(sf)
    { }

    OnLogRotateJob::~OnLogRotateJob()
    { }

    void SAL_CALL OnLogRotateJob::executeAsync(
        const Sequence<NamedValue>&,
        const Reference<XJobListener>& listener)
        throw(RuntimeException)
    {
        Reference<XDesktop> xDesktop(
            m_ServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.frame.Desktop")),
            UNO_QUERY);
        if(xDesktop.is())
            xDesktop->addTerminateListener(Reference<XTerminateListener>(new OnLogRotateThreadWatcher(m_ServiceFactory)));
        Any result;
        listener->jobFinished(Reference<XAsyncJob>(this), result);
    }

    sal_Bool SAL_CALL OnLogRotateJob::supportsService(const OUString& service_name) throw(RuntimeException)
    {
        const Sequence<OUString> service_names(getSupportedServiceNames());
        for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
            if(service_name == service_names[idx]) return sal_True;
        return sal_False;
    }

    OUString SAL_CALL OnLogRotateJob::getImplementationName() throw(RuntimeException)
    { return getImplementationName_static(); }

    Sequence<OUString> SAL_CALL OnLogRotateJob::getSupportedServiceNames() throw(RuntimeException)
    { return getSupportedServiceNames_static(); }

    OUString SAL_CALL OnLogRotateJob::getImplementationName_static()
    { return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovement.OnLogRotateJob"); }

    Sequence<OUString> SAL_CALL OnLogRotateJob::getSupportedServiceNames_static()
    {
        Sequence<OUString> aServiceNames(1);
        aServiceNames[0] = OUString::createFromAscii("com.sun.star.task.AsyncJob");
        return aServiceNames;
    }

    Reference<XInterface> OnLogRotateJob::Create(const Reference<XComponentContext>& context)
    { return *(new OnLogRotateJob(context)); }

    Reference<XInterface> OnLogRotateJob::Create(const Reference<XMultiServiceFactory>& sf)
    { return *(new OnLogRotateJob(sf)); }
}
<commit_msg>CWS-TOOLING: integrate CWS sb138<commit_after>/*************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"

#include "onlogrotate_job.hxx"
#include "config.hxx"
#include "logpacker.hxx"
#include "logstorage.hxx"
#include "soaprequest.hxx"
#include "soapsender.hxx"

#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/frame/XDesktop.hpp>
#include <com/sun/star/frame/XTerminateListener.hpp>
#include <osl/conditn.hxx>
#include <osl/thread.hxx>
#include <osl/time.h>
#include <cppuhelper/implbase1.hxx>
#include <memory>

using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::uno;
using ::com::sun::star::frame::XTerminateListener;
using ::com::sun::star::frame::XDesktop;
using ::com::sun::star::ucb::XSimpleFileAccess;
using ::rtl::OUString;
using ::std::vector;

namespace
{
    using namespace oooimprovement;

    static void packLogs(const Reference<XMultiServiceFactory>& sf)
    {
        try
        {
            Config config(sf);
            LogPacker log_packer(sf);
            vector<OUString> csvfiles = LogStorage(sf).getUnzippedLogFiles();
            for(
                vector<OUString>::iterator item = csvfiles.begin();
                item!=csvfiles.end();
                item++)
                config.incrementEventCount(log_packer.pack(*item));
        } catch(...) {};
    };

    static void uploadLogs(const Reference<XMultiServiceFactory>& sf)
    {
        try
        {
            Config config(sf);
            Reference<XSimpleFileAccess> file_access(
                sf->createInstance(OUString::createFromAscii("com.sun.star.ucb.SimpleFileAccess")),
                UNO_QUERY_THROW);
            SoapSender sender(sf, config.getSoapUrl());
            OUString soap_id = config.getSoapId();
            vector<OUString> zipfiles = LogStorage(sf).getZippedLogFiles();
            for(
                vector<OUString>::iterator item = zipfiles.begin();
                item!=zipfiles.end();
                item++)
            {
                if(config.incrementFailedAttempts(1) > 25)
                {
                    config.giveupUploading();
                    LogStorage(sf).clear();
                    return;
                }
                sender.send(SoapRequest(sf, soap_id, *item));
                config.incrementReportCount(1);
                file_access->kill(*item);
                config.resetFailedAttempts();
            }
        } catch(...) {};
    }

    class OnLogRotateThread : public ::osl::Thread
    {
        public:
            OnLogRotateThread(Reference<XMultiServiceFactory> sf);
            virtual void SAL_CALL run();
            void stop();

        private:
            Reference<XMultiServiceFactory> m_ServiceFactory;
            ::osl::Condition m_Stop;
    };

    OnLogRotateThread::OnLogRotateThread(Reference<XMultiServiceFactory> sf)
        : m_ServiceFactory(sf)
    {
        OSL_ASSERT(sf.is());
    }

    void SAL_CALL OnLogRotateThread::run()
    {
        TimeValue wait_intervall = {30,0};
        if (m_Stop.wait(&wait_intervall) == ::osl::Condition::result_timeout)
        {
            try
            {
                if(Config(m_ServiceFactory).getInvitationAccepted())
                {
                    packLogs(m_ServiceFactory);
                    uploadLogs(m_ServiceFactory);
                }
                else
                    LogStorage(m_ServiceFactory).clear();
            }
            catch(...) {}
        }
    }

    void OnLogRotateThread::stop()
    {
        m_Stop.set();
    }

    class OnLogRotateThreadWatcher : public ::cppu::WeakImplHelper1<XTerminateListener>
    {
        public:
            OnLogRotateThreadWatcher(Reference<XMultiServiceFactory> sf)
                : m_Thread(new OnLogRotateThread(sf))
            {
                m_Thread->create();
            }
            virtual ~OnLogRotateThreadWatcher()
            {
                m_Thread->stop();
                m_Thread->join();
            };

            // XTerminateListener
            virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException)
                { };
            virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException)
            {
                m_Thread->stop();
                m_Thread->join();
            };
            // XEventListener
            virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException)
            {
                m_Thread->stop();
                m_Thread->join();
            };
        private:
            ::std::auto_ptr<OnLogRotateThread> m_Thread;
    };
}

namespace oooimprovement
{
    OnLogRotateJob::OnLogRotateJob(const Reference<XComponentContext>& context)
        : m_ServiceFactory(Reference<XMultiServiceFactory>(
            context->getServiceManager()->createInstanceWithContext(
                OUString::createFromAscii("com.sun.star.lang.XMultiServiceFactory"), context),
            UNO_QUERY))
    { }

    OnLogRotateJob::OnLogRotateJob(const Reference<XMultiServiceFactory>& sf)
        : m_ServiceFactory(sf)
    { }

    OnLogRotateJob::~OnLogRotateJob()
    { }

    void SAL_CALL OnLogRotateJob::executeAsync(
        const Sequence<NamedValue>&,
        const Reference<XJobListener>& listener)
        throw(RuntimeException)
    {
        Reference<XDesktop> xDesktop(
            m_ServiceFactory->createInstance(OUString::createFromAscii("com.sun.star.frame.Desktop")),
            UNO_QUERY);
        if(xDesktop.is())
            xDesktop->addTerminateListener(Reference<XTerminateListener>(new OnLogRotateThreadWatcher(m_ServiceFactory)));
        Any result;
        listener->jobFinished(Reference<XAsyncJob>(this), result);
    }

    sal_Bool SAL_CALL OnLogRotateJob::supportsService(const OUString& service_name) throw(RuntimeException)
    {
        const Sequence<OUString> service_names(getSupportedServiceNames());
        for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)
            if(service_name == service_names[idx]) return sal_True;
        return sal_False;
    }

    OUString SAL_CALL OnLogRotateJob::getImplementationName() throw(RuntimeException)
    { return getImplementationName_static(); }

    Sequence<OUString> SAL_CALL OnLogRotateJob::getSupportedServiceNames() throw(RuntimeException)
    { return getSupportedServiceNames_static(); }

    OUString SAL_CALL OnLogRotateJob::getImplementationName_static()
    { return OUString::createFromAscii("com.sun.star.comp.extensions.oooimprovement.OnLogRotateJob"); }

    Sequence<OUString> SAL_CALL OnLogRotateJob::getSupportedServiceNames_static()
    {
        Sequence<OUString> aServiceNames(1);
        aServiceNames[0] = OUString::createFromAscii("com.sun.star.task.AsyncJob");
        return aServiceNames;
    }

    Reference<XInterface> OnLogRotateJob::Create(const Reference<XComponentContext>& context)
    { return *(new OnLogRotateJob(context)); }

    Reference<XInterface> OnLogRotateJob::Create(const Reference<XMultiServiceFactory>& sf)
    { return *(new OnLogRotateJob(sf)); }
}
<|endoftext|>


<commit_before>// CxxSwizzle
// Copyright (c) 2013, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>

#include <swizzle/glsl/naive/vector.h>
#include <swizzle/glsl/naive/matrix.h>
#include <swizzle/glsl/texture_functions.h>

typedef swizzle::glsl::naive::vector< float, 2 > vec2;
typedef swizzle::glsl::naive::vector< float, 3 > vec3;
typedef swizzle::glsl::naive::vector< float, 4 > vec4;

static_assert(sizeof(vec2) == sizeof(float[2]), "Too big");
static_assert(sizeof(vec3) == sizeof(float[3]), "Too big");
static_assert(sizeof(vec4) == sizeof(float[4]), "Too big");

typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 2, 2> mat2;
typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 3, 3> mat3;
typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 4, 4> mat4;

//! A really, really simplistic sampler using SDLImage
struct SDL_Surface;
class sampler2D : public swizzle::glsl::texture_functions::tag
{
public:
    enum WrapMode
    {
        Clamp,
        Repeat,
        MirrorRepeat
    };

    typedef vec2 tex_coord_type;

    sampler2D(const char* path, WrapMode wrapMode);
    ~sampler2D();
    vec4 sample(vec2 coord);

private:
    SDL_Surface *m_image;
    WrapMode m_wrapMode;

    // do not allow copies to be made
    sampler2D(const sampler2D&);
    sampler2D& operator=(const sampler2D&);
};

// this where the magic happens...
namespace glsl_sandbox
{
    // a nested namespace used when redefining 'inout' and 'out' keywords
    namespace ref
    {
        typedef ::vec2& vec2;
        typedef ::vec3& vec3;
        typedef ::vec4& vec4;
    }

    #include <swizzle/glsl/vector_functions.h>

//    float wtf = clamp(0.0f, 1.0f);
    // constants shaders are using
    float time;
    vec2 mouse;
    vec2 resolution(50.0f, 50.0f);

    // constants some shaders from shader toy are using
    vec2& iResolution = resolution;
    float& iGlobalTime = time;
    vec2& iMouse = mouse;

    sampler2D diffuse("diffuse.png", sampler2D::Repeat);
    sampler2D specular("specular.png", sampler2D::Repeat);

    struct fragment_shader
    {
        vec2 gl_FragCoord;
        vec4 gl_FragColor;
        void operator()(void);
    };

    // change meaning of glsl keywords to match sandbox
    #define uniform extern
    #define in
    #define out ref::
    #define inout ref::
    #define main fragment_shader::operator()

    #pragma warning(push)
    #pragma warning(disable: 4244) // disable return implicit conversion warning
    #pragma warning(disable: 4305) // disable truncation warning

    //#include "shaders/sampler.frag"
    //#include "shaders/leadlight.frag"
    //#include "shaders/terrain.frag"
    //#include "shaders/complex.frag"
    //#include "shaders/road.frag"
    #include "shaders/gears.frag"

    // be a dear a clean up
    #pragma warning(pop)
    #undef main
    #undef in
    #undef out
    #undef inout
    #undef uniform
}

// these headers, especially SDL.h & time.h set up names that are in conflict with sandbox'es;
// sandbox should be moved to a separate h/cpp pair, but out of laziness... including them
// *after* sandbox solves it too

#include <iostream>
#include <sstream>
#include <SDL.h>
#include <SDL_image.h>
#include <time.h>
#if OMP_ENABLED
#include <omp.h>
#endif

extern C_LINKAGE int main(int argc, char* argv[])
{
    using namespace std;

    // initialise SDLImage
    int flags = IMG_INIT_JPG | IMG_INIT_PNG;
    int initted = IMG_Init(flags);
    if ((initted & flags) != flags) {
        cerr << "WARNING: failed to initialise required jpg and png support: " << IMG_GetError() << endl;
    }

    SDL_Surface* screen = nullptr;
    SDL_Surface* bmp = nullptr;

    if (argc == 2)
    {
        vec2 resolution;

        std::stringstream s;
        s << argv[1];
        s >> resolution;
        glsl_sandbox::resolution = resolution;
    }

    if ( glsl_sandbox::resolution.x <= 0.0f || glsl_sandbox::resolution.y <= 0.0f )
    {
        cerr << "ERROR: invalid resolution: " << glsl_sandbox::resolution  << endl;
        return 1;
    }

    cout << "\n";
    cout << "+/-  - increase/decrease time scale\n";
    cout << "lmb  - update glsl_sandbox::mouse\n";
    cout << "esc  - quit\n\n";

    try {

        SDL_Init( SDL_INIT_VIDEO );
        SDL_EnableKeyRepeat(100, 10);
        SDL_WM_SetCaption("SDL/Swizzle", "SDL/Swizzle");
        SDL_Rect rect;
        rect.x = 0;
        rect.y = 0;
        rect.w = static_cast<Uint16>(glsl_sandbox::resolution.x + 0.5f);
        rect.h = static_cast<Uint16>(glsl_sandbox::resolution.y + 0.5f);
        screen = SDL_SetVideoMode( rect.w, rect.h, 24, SDL_SWSURFACE );
        bmp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, rect.h, 24, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 );

        float time = 0;
        float timeScale = 1;
        int frame = 0;

        SDL_Event event;
        bool quit = false;

        clock_t begin = clock();
        double bufferedTimeScale = 0.0f;

        while (!quit) {

            SDL_LockSurface(bmp);

            glsl_sandbox::time = time;

#if OMP_ENABLED
            #pragma omp parallel
            {
                int thredsCount = omp_get_num_threads();
                int threadNum = omp_get_thread_num();

                int heightPerThread = bmp->h / thredsCount;
                int heightStart = threadNum * heightPerThread;
                int heightEnd = (threadNum == thredsCount - 1) ? bmp->h : (heightStart + heightPerThread);
#else
            {
                int heightStart = 0;
                int heightEnd = bmp->h;
#endif

                glsl_sandbox::fragment_shader shader;
                for ( int y = heightStart; y < heightEnd; ++y )
                {
                    uint8_t * ptr = reinterpret_cast<uint8_t*>(bmp->pixels) + y * bmp->pitch;
                    for (int x = 0; x < bmp->w; ++x )
                    {
                        shader.gl_FragCoord = vec2(static_cast<float>(x) , bmp->h - 1.0f - y);

                        shader();

                        auto color = glsl_sandbox::clamp(shader.gl_FragColor, 0.0f, 1.0f);

                        *ptr++ = static_cast<uint8_t>(255 * color.x + 0.5f);
                        *ptr++ = static_cast<uint8_t>(255 * color.y + 0.5f);
                        *ptr++ = static_cast<uint8_t>(255 * color.z + 0.5f);
                    }
                }
            }

            SDL_UnlockSurface(bmp);
            SDL_BlitSurface( bmp, NULL, screen, NULL );
            SDL_Flip( screen );

            // process events
            while (SDL_PollEvent(&event)) {
                switch ( event.type ) {
                case SDL_QUIT:
                    quit = true;
                    break;
                case SDL_KEYDOWN:
                    switch ( event.key.keysym.sym ) {
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    case SDLK_PLUS:
                    case SDLK_EQUALS:
                        timeScale *= 2.0f;
                        break;
                    case SDLK_MINUS:
                        timeScale /= 2.0f;
                        break;
                    default:
                        break;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    glsl_sandbox::mouse.x = static_cast<float>(event.button.x);
                    glsl_sandbox::mouse.y = static_cast<float>(bmp->h - 1 - event.button.y);
                    break;
                default:
                    break;
                }
            }

            cout << "frame: " << frame++ << "\t time: " << time << "\t timescale: " << timeScale << "         \r";
            cout.flush();

            clock_t delta = clock() - begin;
            time += static_cast<float>(delta / double(CLOCKS_PER_SEC) * timeScale);
            begin = clock();
        }
    } catch ( exception& error ) {
        cerr << "ERROR: " << error.what() << endl;
    } catch (...) {
        cerr << "ERROR: Unknown error" << endl;
    }

    if ( bmp ) {
        SDL_FreeSurface(bmp);
    }
    if ( screen ) {
        SDL_FreeSurface(screen);
    }
    SDL_Quit();
    return 0;
}

sampler2D::sampler2D( const char* path, WrapMode wrapMode ) : m_wrapMode(wrapMode)
{
    m_image = IMG_Load(path);
    if (!m_image)
    {
        std::cerr << "WARNING: Failed to load texture " << path << "\n";
        std::cerr << "  SDL_Image message: " << IMG_GetError() << "\n";
    }
}

sampler2D::~sampler2D()
{
    if ( m_image )
    {
        SDL_FreeSurface(m_image);
        m_image = nullptr;
    }
}

vec4 sampler2D::sample( vec2 coord )
{
    using namespace glsl_sandbox;

    switch (m_wrapMode)
    {
    case Repeat:
        coord = mod(coord, 1);
        break;
    case MirrorRepeat:
        coord = abs(mod(coord-1, 2)-1);
        break;
    case Clamp:
    default:
        coord = clamp(coord, 0, 1);
        break;
    }

    // OGL uses left-bottom corner as origin...
    coord.y = 1 - coord.y;

    if ( !m_image )
    {
        // checkers
        if ( coord.x < 0.5 && coord.y < 0.5 || coord.x > 0.5 && coord.y > 0.5 )
        {
            return vec4(1, 0, 0, 1);
        }
        else
        {
            return vec4(0, 1, 0, 1);
        }
    }
    else
    {
        int x = static_cast<int>(coord.x * (m_image->w - 1) + 0.5);
        int y = static_cast<int>(coord.y * (m_image->h - 1) + 0.5);

        auto& format = *m_image->format;
        auto pixelPtr = static_cast<uint8_t*>(m_image->pixels) + (y * m_image->pitch + x * format.BytesPerPixel);
        uint32_t pixel = 0;
        for (size_t i = 0; i < format.BytesPerPixel; ++i )
        {
            pixel |= (pixelPtr[i] << (i*8));
        }

        int r = (pixel & format.Rmask) >> format.Rshift;
        int g = (pixel & format.Gmask) >> format.Gshift;
        int b = (pixel & format.Bmask) >> format.Bshift;
        int a = format.Amask ? ((pixel & format.Amask) >> format.Ashift) : 255;
        return clamp(vec4(r, g, b, a) / 255.0f, 0.0f, 1.0f);
    }
}<commit_msg>Removed commented out code<commit_after>// CxxSwizzle
// Copyright (c) 2013, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com>

#include <swizzle/glsl/naive/vector.h>
#include <swizzle/glsl/naive/matrix.h>
#include <swizzle/glsl/texture_functions.h>

typedef swizzle::glsl::naive::vector< float, 2 > vec2;
typedef swizzle::glsl::naive::vector< float, 3 > vec3;
typedef swizzle::glsl::naive::vector< float, 4 > vec4;

static_assert(sizeof(vec2) == sizeof(float[2]), "Too big");
static_assert(sizeof(vec3) == sizeof(float[3]), "Too big");
static_assert(sizeof(vec4) == sizeof(float[4]), "Too big");

typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 2, 2> mat2;
typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 3, 3> mat3;
typedef swizzle::glsl::naive::matrix< swizzle::glsl::naive::vector, float, 4, 4> mat4;

//! A really, really simplistic sampler using SDLImage
struct SDL_Surface;
class sampler2D : public swizzle::glsl::texture_functions::tag
{
public:
    enum WrapMode
    {
        Clamp,
        Repeat,
        MirrorRepeat
    };

    typedef vec2 tex_coord_type;

    sampler2D(const char* path, WrapMode wrapMode);
    ~sampler2D();
    vec4 sample(vec2 coord);

private:
    SDL_Surface *m_image;
    WrapMode m_wrapMode;

    // do not allow copies to be made
    sampler2D(const sampler2D&);
    sampler2D& operator=(const sampler2D&);
};

// this where the magic happens...
namespace glsl_sandbox
{
    // a nested namespace used when redefining 'inout' and 'out' keywords
    namespace ref
    {
        typedef ::vec2& vec2;
        typedef ::vec3& vec3;
        typedef ::vec4& vec4;
    }

    #include <swizzle/glsl/vector_functions.h>

    // constants shaders are using
    float time;
    vec2 mouse;
    vec2 resolution(50.0f, 50.0f);

    // constants some shaders from shader toy are using
    vec2& iResolution = resolution;
    float& iGlobalTime = time;
    vec2& iMouse = mouse;

    sampler2D diffuse("diffuse.png", sampler2D::Repeat);
    sampler2D specular("specular.png", sampler2D::Repeat);

    struct fragment_shader
    {
        vec2 gl_FragCoord;
        vec4 gl_FragColor;
        void operator()(void);
    };

    // change meaning of glsl keywords to match sandbox
    #define uniform extern
    #define in
    #define out ref::
    #define inout ref::
    #define main fragment_shader::operator()

    #pragma warning(push)
    #pragma warning(disable: 4244) // disable return implicit conversion warning
    #pragma warning(disable: 4305) // disable truncation warning

    //#include "shaders/sampler.frag"
    //#include "shaders/leadlight.frag"
    //#include "shaders/terrain.frag"
    //#include "shaders/complex.frag"
    //#include "shaders/road.frag"
    #include "shaders/gears.frag"

    // be a dear a clean up
    #pragma warning(pop)
    #undef main
    #undef in
    #undef out
    #undef inout
    #undef uniform
}

// these headers, especially SDL.h & time.h set up names that are in conflict with sandbox'es;
// sandbox should be moved to a separate h/cpp pair, but out of laziness... including them
// *after* sandbox solves it too

#include <iostream>
#include <sstream>
#include <SDL.h>
#include <SDL_image.h>
#include <time.h>
#if OMP_ENABLED
#include <omp.h>
#endif

extern C_LINKAGE int main(int argc, char* argv[])
{
    using namespace std;

    // initialise SDLImage
    int flags = IMG_INIT_JPG | IMG_INIT_PNG;
    int initted = IMG_Init(flags);
    if ((initted & flags) != flags) {
        cerr << "WARNING: failed to initialise required jpg and png support: " << IMG_GetError() << endl;
    }

    SDL_Surface* screen = nullptr;
    SDL_Surface* bmp = nullptr;

    if (argc == 2)
    {
        vec2 resolution;

        std::stringstream s;
        s << argv[1];
        s >> resolution;
        glsl_sandbox::resolution = resolution;
    }

    if ( glsl_sandbox::resolution.x <= 0.0f || glsl_sandbox::resolution.y <= 0.0f )
    {
        cerr << "ERROR: invalid resolution: " << glsl_sandbox::resolution  << endl;
        return 1;
    }

    cout << "\n";
    cout << "+/-  - increase/decrease time scale\n";
    cout << "lmb  - update glsl_sandbox::mouse\n";
    cout << "esc  - quit\n\n";

    try {

        SDL_Init( SDL_INIT_VIDEO );
        SDL_EnableKeyRepeat(100, 10);
        SDL_WM_SetCaption("SDL/Swizzle", "SDL/Swizzle");
        SDL_Rect rect;
        rect.x = 0;
        rect.y = 0;
        rect.w = static_cast<Uint16>(glsl_sandbox::resolution.x + 0.5f);
        rect.h = static_cast<Uint16>(glsl_sandbox::resolution.y + 0.5f);
        screen = SDL_SetVideoMode( rect.w, rect.h, 24, SDL_SWSURFACE );
        bmp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, rect.h, 24, 0x000000ff, 0x0000ff00, 0x00ff0000, 0 );

        float time = 0;
        float timeScale = 1;
        int frame = 0;

        SDL_Event event;
        bool quit = false;

        clock_t begin = clock();
        double bufferedTimeScale = 0.0f;

        while (!quit) {

            SDL_LockSurface(bmp);

            glsl_sandbox::time = time;

#if OMP_ENABLED
            #pragma omp parallel
            {
                int thredsCount = omp_get_num_threads();
                int threadNum = omp_get_thread_num();

                int heightPerThread = bmp->h / thredsCount;
                int heightStart = threadNum * heightPerThread;
                int heightEnd = (threadNum == thredsCount - 1) ? bmp->h : (heightStart + heightPerThread);
#else
            {
                int heightStart = 0;
                int heightEnd = bmp->h;
#endif

                glsl_sandbox::fragment_shader shader;
                for ( int y = heightStart; y < heightEnd; ++y )
                {
                    uint8_t * ptr = reinterpret_cast<uint8_t*>(bmp->pixels) + y * bmp->pitch;
                    for (int x = 0; x < bmp->w; ++x )
                    {
                        shader.gl_FragCoord = vec2(static_cast<float>(x) , bmp->h - 1.0f - y);

                        shader();

                        auto color = glsl_sandbox::clamp(shader.gl_FragColor, 0.0f, 1.0f);

                        *ptr++ = static_cast<uint8_t>(255 * color.x + 0.5f);
                        *ptr++ = static_cast<uint8_t>(255 * color.y + 0.5f);
                        *ptr++ = static_cast<uint8_t>(255 * color.z + 0.5f);
                    }
                }
            }

            SDL_UnlockSurface(bmp);
            SDL_BlitSurface( bmp, NULL, screen, NULL );
            SDL_Flip( screen );

            // process events
            while (SDL_PollEvent(&event)) {
                switch ( event.type ) {
                case SDL_QUIT:
                    quit = true;
                    break;
                case SDL_KEYDOWN:
                    switch ( event.key.keysym.sym ) {
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    case SDLK_PLUS:
                    case SDLK_EQUALS:
                        timeScale *= 2.0f;
                        break;
                    case SDLK_MINUS:
                        timeScale /= 2.0f;
                        break;
                    default:
                        break;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    glsl_sandbox::mouse.x = static_cast<float>(event.button.x);
                    glsl_sandbox::mouse.y = static_cast<float>(bmp->h - 1 - event.button.y);
                    break;
                default:
                    break;
                }
            }

            cout << "frame: " << frame++ << "\t time: " << time << "\t timescale: " << timeScale << "         \r";
            cout.flush();

            clock_t delta = clock() - begin;
            time += static_cast<float>(delta / double(CLOCKS_PER_SEC) * timeScale);
            begin = clock();
        }
    } catch ( exception& error ) {
        cerr << "ERROR: " << error.what() << endl;
    } catch (...) {
        cerr << "ERROR: Unknown error" << endl;
    }

    if ( bmp ) {
        SDL_FreeSurface(bmp);
    }
    if ( screen ) {
        SDL_FreeSurface(screen);
    }
    SDL_Quit();
    return 0;
}

sampler2D::sampler2D( const char* path, WrapMode wrapMode ) : m_wrapMode(wrapMode)
{
    m_image = IMG_Load(path);
    if (!m_image)
    {
        std::cerr << "WARNING: Failed to load texture " << path << "\n";
        std::cerr << "  SDL_Image message: " << IMG_GetError() << "\n";
    }
}

sampler2D::~sampler2D()
{
    if ( m_image )
    {
        SDL_FreeSurface(m_image);
        m_image = nullptr;
    }
}

vec4 sampler2D::sample( vec2 coord )
{
    using namespace glsl_sandbox;

    switch (m_wrapMode)
    {
    case Repeat:
        coord = mod(coord, 1);
        break;
    case MirrorRepeat:
        coord = abs(mod(coord-1, 2)-1);
        break;
    case Clamp:
    default:
        coord = clamp(coord, 0, 1);
        break;
    }

    // OGL uses left-bottom corner as origin...
    coord.y = 1 - coord.y;

    if ( !m_image )
    {
        // checkers
        if ( coord.x < 0.5 && coord.y < 0.5 || coord.x > 0.5 && coord.y > 0.5 )
        {
            return vec4(1, 0, 0, 1);
        }
        else
        {
            return vec4(0, 1, 0, 1);
        }
    }
    else
    {
        int x = static_cast<int>(coord.x * (m_image->w - 1) + 0.5);
        int y = static_cast<int>(coord.y * (m_image->h - 1) + 0.5);

        auto& format = *m_image->format;
        auto pixelPtr = static_cast<uint8_t*>(m_image->pixels) + (y * m_image->pitch + x * format.BytesPerPixel);
        uint32_t pixel = 0;
        for (size_t i = 0; i < format.BytesPerPixel; ++i )
        {
            pixel |= (pixelPtr[i] << (i*8));
        }

        int r = (pixel & format.Rmask) >> format.Rshift;
        int g = (pixel & format.Gmask) >> format.Gshift;
        int b = (pixel & format.Bmask) >> format.Bshift;
        int a = format.Amask ? ((pixel & format.Amask) >> format.Ashift) : 255;
        return clamp(vec4(r, g, b, a) / 255.0f, 0.0f, 1.0f);
    }
}<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "std_msgs/Float64"
#include <algorithm>

// Constructor that stores desired gains in class variable
SpeedController::SpeedController(double kp, double ki, double kd){

  _Kp = kp;
  _Ki = ki;
  _Kd = kd;

}

// Gets current wheel velocity in rad/s
// ToDo : implement low pass filter on data?
private double SpeedController::get_wheel_vels(){

  // Get the current time
  enc_time = ros::Time::now().toSec();

  // Calculate unfiltered encoder velocity in pulses per sec
  omega = (enc_count - prev_enc_count)/(enc_time - prev_enc_time);

  // Convert from pulses per sec to rads per sec
  omega /= pulses_per_rev * 2 * PI;

  return omega;

}

// Write value to Pololu motor Driver
// Need to wait until ROS Serial architecture is figured out
private void SpeedController::assign(int val){

}

// Takes a command velocity in rad/s and uses PID to control
// motor to that speed
public double SpeedController::control(double w_cmd){

  // Get current wheel angular velocity
  double w_act = get_wheel_vels();
  // Calculate Current Error
  double cur_error = w_act - w_cmd;

  // Get time difference between now and last control time
  double dt = ros::Time.now().toSec() - last_control_time;

  // Derivative of Error
  double dedt = (cur_error - prev_error) / dt;

  // Calculate PID Output
  output += _Kp * cur_error + _Kd * dedt + _Ki * int_error;

  assign(output);

  // Update Error Values
  int_error += (cur_error + prev_error) / 2.0 * dt;
  int_error = min(int_error, int_error_max);
  last_control_time = ros::Time.now().toSec();

}

<commit_msg>Changes to Speed Controller<commit_after>#include "ros/ros.h"
#include "std_msgs/Float64"
#include <algorithm>

// Constructor that stores desired gains in class variable
SpeedController::SpeedController(double kp, double ki, double kd){

  _Kp = kp;
  _Ki = ki;
  _Kd = kd;

}

// Gets current wheel velocity in rad/s
// ToDo : implement low pass filter on data?
private double SpeedController::get_wheel_vels(){

  // Get the current time
  enc_time = ros::Time::now().toSec();

  // Calculate unfiltered encoder velocity in pulses per sec
  double omega = (enc_count - prev_enc_count) /
                 (enc_time - prev_enc_time);

  // Convert from pulses per sec to rads per sec
  omega /= pulses_per_rev * 2 * PI;

  return omega;

}

// Write value to Pololu motor Driver
// Need to wait until ROS Serial architecture is figured out
private void SpeedController::assign(int val){

}

// Takes a command velocity in rad/s and uses PID to control
// motor to that speed
public double SpeedController::control(double w_cmd){

  // Get current wheel angular velocity
  double w_act = get_wheel_vels();
  // Calculate Current Error
  double cur_error = w_act - w_cmd;

  // Get time difference between now and last control time
  double dt = ros::Time.now().toSec() - last_control_time;

  // Derivative of Error
  double dedt = (cur_error - prev_error) / dt;

  // Calculate PID Output
  output += _Kp * cur_error + _Kd * dedt + _Ki * int_error;

  // Write value to Motor Driver
  assign(output);

  // Update Error Values
  int_error += (cur_error + prev_error) / 2.0 * dt;
  int_error = min(int_error, int_error_max);
  last_control_time = ros::Time.now().toSec();

}

<|endoftext|>


<commit_before>#ifndef __STAN__MCMC__DUALAVERAGE_H__
#define __STAN__MCMC__DUALAVERAGE_H__

#include <cmath>
#include <cstddef>

#include <vector>
#include <cstdio>

#include <iostream>

namespace stan {

  namespace mcmc {

    /**
     * Class implementing Nesterov's dual average algorithm.  Use by
     * repeatedly calling update() with the gradient evaluated at
     * xk(). When finished, use the average value of all the xk's by
     * calling xbar().
     *
     * Iterates are shrunk towards a prespecified point x0. The level
     * of shrinkage is controlled by the parameter gamma and gets
     * weaker with each iteration.
     *
     * Note that this is an algorithm for MINIMIZATION, not MAXIMIZATION.
     */
    class DualAverage {
    protected:
      std::vector<double> _gbar, _xbar, _x0, _lastx;
      int _k;
      double _gamma;

    public:
      /**
       * Constructor.
       *
       * @param gamma Regularization parameter. Higher values mean that
       * iterates will be shrunk towards x0 more strongly.
       * @param x0 Point towards which iterates are shrunk.
       */
      DualAverage(double gamma, const std::vector<double>& x0)
        : _gbar(x0.size(), 0), _xbar(x0.size(), 0), _x0(x0), _lastx(x0),
          _k(0), _gamma(gamma){
      }

      /**
       * Produces the next iterate xk given the current gradient g.
       *
       * @param g The new subgradient/stochastic gradient.
       * @param xk The next iterate produced by the algorithm.
       */
      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        xk.resize(_gbar.size());
        double avgeta = 1.0 / (_k + 10);
        double xbar_avgeta = pow(_k, -0.75);
        double muk = 0.5 * sqrt(_k) / _gamma;
        for (size_t i = 0; i < _gbar.size(); ++i) {
          _gbar[i] = avgeta * g[i] + (1 - avgeta) * _gbar[i];
          xk[i] = _x0[i] - muk * _gbar[i];
//           fprintf(stderr, "DUALAVERAGE update %d: g = %f, gbar = %f, lastx = %f",
//                   _k, g[0], _gbar[0], _lastx[0]);
          _lastx[i] = xk[i];
          _xbar[i] = xbar_avgeta * xk[i] + (1 - xbar_avgeta) * _xbar[i];
        }
//         fprintf(stderr, ", xk = %f\n", xk[0]);
      }

      /**
       * Set the point towards which each iterate is shrunk.
       *
       * @param x0 The point towards each iterate will be shrunk.
       */
      inline void setx0(const std::vector<double>& x0) {
        _x0.assign(x0.begin(), x0.end());
      }

      /**
       * Get the exponentially weighted moving average of all previous
       * iterates.
       *
       * @param xbar Where to return the exponentially weighted moving
       * average of all previous iterates.
       */
      inline void xbar(std::vector<double>& xbar) {
        xbar.assign(_xbar.begin(), _xbar.end());
      }
      /**
       * Get the average of all previous gradients.
       *
       * @param gbar Where to return the average of all previous gradients.
       */
      inline void gbar(std::vector<double>& gbar) {
        gbar.assign(_gbar.begin(), _gbar.end());
      }
      /**
       * Get the current iterate.
       *
       * @param xk Where to return the current iterate.
       */
      inline void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      /**
       * Get the point towards which we're shrinking the iterates.
       *
       * @param x0 Where to return the point towards which we're
       * shrinking the iterates.
       */
      inline void x0(std::vector<double>& x0) {
        x0.assign(_x0.begin(), _x0.end());
      }
      /**
       * Return how many iterations we've run for.
       *
       * @return how many iterations we've run for.
       */
      inline int k() { return _k; }
      /**
       * Return the regularization parameter gamma.
       *
       * @return the regularization parameter gamma.
       */
      inline double gamma() { return _gamma; }
    };

    class GrowingBatches {
    protected:
      std::vector<double> _gbar, _xbar, _x0, _lastx;
      int _k, _lastk, _nextk;
      double _gamma;

    public:
      GrowingBatches(double gamma, const std::vector<double>& x0)
        : _gbar(x0.size(), 0), _xbar(x0.size(), 0), _x0(x0), _lastx(x0),
          _k(0), _lastk(0), _nextk(1), _gamma(gamma){
      }

      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        for (size_t i = 0; i < g.size(); ++i)
          _gbar[i] += g[i];
        if (_k == _nextk) {
          for (size_t i = 0; i < g.size(); ++i) {
            std::cerr << "_lastx[" << i << "]"
                      << " = " << _lastx[i]
                      << ", _gbar[" << i << "]"
                      << " = " << _gbar[i]
                      << std::endl;
            _lastx[i] -= _gamma * _gbar[i] / (_nextk - _lastk);
          }
          _gbar.assign(_gbar.size(), 0);
          int temp = _lastk;
          _lastk = _nextk;
          _nextk = _lastk + (_nextk - temp + 1);
        }
        xk = _lastx;
        _xbar = _lastx;
      }

      void setx0(const std::vector<double>& x0) {
        _x0 = x0;
        _lastx = x0;
        _xbar = x0;
        fprintf(stderr, "_lastx[0] = %f\n", x0[0]);
      }

      inline void xbar(std::vector<double>& xbar) {
        xbar.assign(_xbar.begin(), _xbar.end());
      }
      inline void gbar(std::vector<double>& gbar) {
        gbar.assign(_gbar.begin(), _gbar.end());
      }
      inline void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      inline void x0(std::vector<double>& x0) {
        x0.assign(_x0.begin(), _x0.end());
      }
      inline int k() { return _k; }
      inline double gamma() { return _gamma; }
    };

    class StochasticGradient {
    protected:
      std::vector<double> _lastx;
      int _k;
      double _gamma, _a;

    public:
      StochasticGradient(const std::vector<double>& x0, double gamma = 0.5,
                         double a = 1.0)
        : _lastx(x0), _k(0), _gamma(gamma), _a(a) {
      }

      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        xk.resize(g.size());
        double eta = _a * pow(_k, -_gamma);
        for (size_t i = 0; i < g.size(); ++i) {
          xk[i] = _lastx[i] - eta * g[i];
          _lastx[i] = xk[i];
        }
      }

      void setlastx(const std::vector<double>& lastx) {
        _lastx.assign(lastx.begin(), lastx.end());
      }
      void setx0(const std::vector<double>& lastx) {
        _lastx.assign(lastx.begin(), lastx.end());
      }

      void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      void xbar(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      int k() { return _k; }
      double gamma() { return _gamma; }
    };
  }
}

#endif
<commit_msg>commented out debug prints, removed lib includes in dualaverage<commit_after>#ifndef __STAN__MCMC__DUALAVERAGE_H__
#define __STAN__MCMC__DUALAVERAGE_H__

#include <cmath>
#include <cstddef>

#include <vector>

#include <iostream>

namespace stan {

  namespace mcmc {

    /**
     * Class implementing Nesterov's dual average algorithm.  Use by
     * repeatedly calling update() with the gradient evaluated at
     * xk(). When finished, use the average value of all the xk's by
     * calling xbar().
     *
     * Iterates are shrunk towards a prespecified point x0. The level
     * of shrinkage is controlled by the parameter gamma and gets
     * weaker with each iteration.
     *
     * Note that this is an algorithm for MINIMIZATION, not MAXIMIZATION.
     */
    class DualAverage {
    protected:
      std::vector<double> _gbar, _xbar, _x0, _lastx;
      int _k;
      double _gamma;

    public:
      /**
       * Constructor.
       *
       * @param gamma Regularization parameter. Higher values mean that
       * iterates will be shrunk towards x0 more strongly.
       * @param x0 Point towards which iterates are shrunk.
       */
      DualAverage(double gamma, const std::vector<double>& x0)
        : _gbar(x0.size(), 0), _xbar(x0.size(), 0), _x0(x0), _lastx(x0),
          _k(0), _gamma(gamma){
      }

      /**
       * Produces the next iterate xk given the current gradient g.
       *
       * @param g The new subgradient/stochastic gradient.
       * @param xk The next iterate produced by the algorithm.
       */
      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        xk.resize(_gbar.size());
        double avgeta = 1.0 / (_k + 10);
        double xbar_avgeta = pow(_k, -0.75);
        double muk = 0.5 * sqrt(_k) / _gamma;
        for (size_t i = 0; i < _gbar.size(); ++i) {
          _gbar[i] = avgeta * g[i] + (1 - avgeta) * _gbar[i];
          xk[i] = _x0[i] - muk * _gbar[i];
//           fprintf(stderr, "DUALAVERAGE update %d: g = %f, gbar = %f, lastx = %f",
//                   _k, g[0], _gbar[0], _lastx[0]);
          _lastx[i] = xk[i];
          _xbar[i] = xbar_avgeta * xk[i] + (1 - xbar_avgeta) * _xbar[i];
        }
//         fprintf(stderr, ", xk = %f\n", xk[0]);
      }

      /**
       * Set the point towards which each iterate is shrunk.
       *
       * @param x0 The point towards each iterate will be shrunk.
       */
      inline void setx0(const std::vector<double>& x0) {
        _x0.assign(x0.begin(), x0.end());
      }

      /**
       * Get the exponentially weighted moving average of all previous
       * iterates.
       *
       * @param xbar Where to return the exponentially weighted moving
       * average of all previous iterates.
       */
      inline void xbar(std::vector<double>& xbar) {
        xbar.assign(_xbar.begin(), _xbar.end());
      }
      /**
       * Get the average of all previous gradients.
       *
       * @param gbar Where to return the average of all previous gradients.
       */
      inline void gbar(std::vector<double>& gbar) {
        gbar.assign(_gbar.begin(), _gbar.end());
      }
      /**
       * Get the current iterate.
       *
       * @param xk Where to return the current iterate.
       */
      inline void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      /**
       * Get the point towards which we're shrinking the iterates.
       *
       * @param x0 Where to return the point towards which we're
       * shrinking the iterates.
       */
      inline void x0(std::vector<double>& x0) {
        x0.assign(_x0.begin(), _x0.end());
      }
      /**
       * Return how many iterations we've run for.
       *
       * @return how many iterations we've run for.
       */
      inline int k() { return _k; }
      /**
       * Return the regularization parameter gamma.
       *
       * @return the regularization parameter gamma.
       */
      inline double gamma() { return _gamma; }
    };

    class GrowingBatches {
    protected:
      std::vector<double> _gbar, _xbar, _x0, _lastx;
      int _k, _lastk, _nextk;
      double _gamma;

    public:
      GrowingBatches(double gamma, const std::vector<double>& x0)
        : _gbar(x0.size(), 0), _xbar(x0.size(), 0), _x0(x0), _lastx(x0),
          _k(0), _lastk(0), _nextk(1), _gamma(gamma){
      }

      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        for (size_t i = 0; i < g.size(); ++i)
          _gbar[i] += g[i];
        if (_k == _nextk) {
          for (size_t i = 0; i < g.size(); ++i) {
            // std::cerr << "_lastx[" << i << "]"
            //           << " = " << _lastx[i]
            //           << ", _gbar[" << i << "]"
            //           << " = " << _gbar[i]
            //           << std::endl;
            _lastx[i] -= _gamma * _gbar[i] / (_nextk - _lastk);
          }
          _gbar.assign(_gbar.size(), 0);
          int temp = _lastk;
          _lastk = _nextk;
          _nextk = _lastk + (_nextk - temp + 1);
        }
        xk = _lastx;
        _xbar = _lastx;
      }

      void setx0(const std::vector<double>& x0) {
        _x0 = x0;
        _lastx = x0;
        _xbar = x0;
        // fprintf(stderr, "_lastx[0] = %f\n", x0[0]);
      }

      inline void xbar(std::vector<double>& xbar) {
        xbar.assign(_xbar.begin(), _xbar.end());
      }
      inline void gbar(std::vector<double>& gbar) {
        gbar.assign(_gbar.begin(), _gbar.end());
      }
      inline void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      inline void x0(std::vector<double>& x0) {
        x0.assign(_x0.begin(), _x0.end());
      }
      inline int k() { return _k; }
      inline double gamma() { return _gamma; }
    };

    class StochasticGradient {
    protected:
      std::vector<double> _lastx;
      int _k;
      double _gamma, _a;

    public:
      StochasticGradient(const std::vector<double>& x0, double gamma = 0.5,
                         double a = 1.0)
        : _lastx(x0), _k(0), _gamma(gamma), _a(a) {
      }

      void update(const std::vector<double>& g, std::vector<double>& xk) {
        _k++;
        xk.resize(g.size());
        double eta = _a * pow(_k, -_gamma);
        for (size_t i = 0; i < g.size(); ++i) {
          xk[i] = _lastx[i] - eta * g[i];
          _lastx[i] = xk[i];
        }
      }

      void setlastx(const std::vector<double>& lastx) {
        _lastx.assign(lastx.begin(), lastx.end());
      }
      void setx0(const std::vector<double>& lastx) {
        _lastx.assign(lastx.begin(), lastx.end());
      }

      void xk(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      void xbar(std::vector<double>& xk) {
        xk.assign(_lastx.begin(), _lastx.end());
      }
      int k() { return _k; }
      double gamma() { return _gamma; }
    };
  }
}

#endif
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Mocks of fromCApi() for Semaphore
 *
 * \author Copyright (C) 2017 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/.
 */

#ifndef UNIT_TEST_INCLUDE_MOCKS_FROMCAPI_HPP_SEMAPHORE_DISTORTOS_FROMCAPI_HPP_
#define UNIT_TEST_INCLUDE_MOCKS_FROMCAPI_HPP_SEMAPHORE_DISTORTOS_FROMCAPI_HPP_

#include "unit-test-common.hpp"

extern "C"
{

struct distortos_Semaphore;

}	// extern "C"

namespace distortos
{

class Semaphore;

class FromCApiSemaphoreMock
{
public:

	FromCApiSemaphoreMock()
	{
		REQUIRE(getInstanceInternal() == nullptr);
		getInstanceInternal() = this;
	}

	~FromCApiSemaphoreMock()
	{
		REQUIRE(getInstanceInternal() != nullptr);
		getInstanceInternal() = {};
	}

	MAKE_CONST_MOCK1(getSemaphore, distortos::Semaphore&(distortos_Semaphore&));
	MAKE_CONST_MOCK1(getConstSemaphore, const distortos::Semaphore&(const distortos_Semaphore&));

	static const FromCApiSemaphoreMock& getInstance()
	{
		REQUIRE(getInstanceInternal() != nullptr);
		return *getInstanceInternal();
	}

private:

	static const FromCApiSemaphoreMock*& getInstanceInternal()
	{
		static const FromCApiSemaphoreMock* instance;
		return instance;
	}
};

inline static distortos::Semaphore& fromCApi(distortos_Semaphore& semaphore)
{
	return FromCApiSemaphoreMock::getInstance().getSemaphore(semaphore);
}

inline static const distortos::Semaphore& fromCApi(const distortos_Semaphore& semaphore)
{
	return FromCApiSemaphoreMock::getInstance().getConstSemaphore(semaphore);
}

}	// namespace distortos

#endif	// UNIT_TEST_INCLUDE_MOCKS_FROMCAPI_HPP_SEMAPHORE_DISTORTOS_FROMCAPI_HPP_
<commit_msg>Remove semaphore-only variant of fromCApi() mock<commit_after><|endoftext|>


<commit_before>/*
* Copyright (C) 2008 J-P Nurmi jpnurmi@gmail.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 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.
*
* $Id$
*/

#include "ircutil.h"
#include <QRegExp>

static const int BUFLEN = 256;

static void irc_target_get_nick (const char * target, char *nick, size_t size)
{
	const char *p = strstr (target, "!");
	unsigned int len;

	if ( p )
		len = p - target;
	else
		len = strlen (target);

	if ( len > size-1 )
		len = size - 1;

	memcpy (nick, target, len);
	nick[len] = '\0';
}

static void irc_target_get_host (const char * target, char *host, size_t size)
{
	unsigned int len;
	const char *p = strstr (target, "!");

	if ( !p )
		p = target;

	len = strlen (p);

	if ( len > size-1 )
		len = size - 1;

	memcpy (host, p, len);
	host[len] = '\0';
}

namespace Irc
{
    /*!
        Parses and returns the nick part from target.
    */
    QString Irc::Util::nickFromTarget(const QString& target)
    {
        char buffer[BUFLEN-1];
        irc_target_get_nick(target.toUtf8(), buffer, BUFLEN);
        return QString::fromUtf8(buffer);
    }

    /*!
        Parses and returns the host part from target.
    */
    QString Irc::Util::hostFromTarget(const QString& target)
    {
        char buffer[BUFLEN-1];
        irc_target_get_host(target.toUtf8(), buffer, BUFLEN);
        return QString::fromUtf8(buffer);
    }

    /*
    static QString irc_colorStringHelper(char* message)
    {
        QString value = QString::fromUtf8(message);
        free(message);
        return value;
    }

    QString Irc::Util::colorConvertToHtml(const QString& message)
    {
        QString tmp = colorConvertToMirc(message);
        tmp.replace(QRegExp("\\[([^\\]]+)\\]([^\\[]*)\\(/[^\\]]+)\\]"), "<\\1>\\2<\\3>");
        return tmp;
    }
    */
}
<commit_msg>Util::nickFromTarget() & Util::hostFromTarget().<commit_after>/*
* Copyright (C) 2008 J-P Nurmi jpnurmi@gmail.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 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.
*
* $Id$
*/

#include "ircutil.h"
#include <QRegExp>

namespace Irc
{
    /*!
        Parses and returns the nick part from target.
    */
    QString Irc::Util::nickFromTarget(const QString& target)
    {
        int index = target.indexOf(QLatin1Char('!'));
        return target.left(index);
    }

    /*!
        Parses and returns the host part from target.
    */
    QString Irc::Util::hostFromTarget(const QString& target)
    {
        int index = target.indexOf(QLatin1Char('!'));
        return target.mid(index + 1);
    }

    /*
    static QString irc_colorStringHelper(char* message)
    {
        QString value = QString::fromUtf8(message);
        free(message);
        return value;
    }

    QString Irc::Util::colorConvertToHtml(const QString& message)
    {
        QString tmp = colorConvertToMirc(message);
        tmp.replace(QRegExp("\\[([^\\]]+)\\]([^\\[]*)\\(/[^\\]]+)\\]"), "<\\1>\\2<\\3>");
        return tmp;
    }
    */
}
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A;
string S;
vector<int> V;

int calc(string str) {
  assert(str.size() <= 7);
  int tmp = 1;
  int ans = 0;
  for (auto i = 0; i < (int)str.size(); ++i) {
    ans += tmp * (str[i] - 'a' + 1);
    tmp *= A;
  }
  //cerr << ans << endl;
  return ans;
}

string maximal(int h) {
  string ans = "";
  while (h > 0) {
    for (auto i = 26; i >= 1; --i) {
      if (h - i < 0) continue;
      if ((h - i) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        h = (h - i)/A;
        break;
      }
    }
    //cerr << ans << " " << h << endl;
  }
  return ans;
}

int main () {
  cin >> A >> S;
  if (S.size() <= 7) {
    cout << maximal(calc(S)) << endl;
    return 0;
  }
  string T = S.substr(0, S.size()-7);
  string U = S.substr(S.size()-7, 7);
  assert(S == T + U);
  string ans = 0;
  int kari = 0;
  for (auto i = 0; i < (int)T.size(); ++i) {
    char x = T[i];
    cerr << x << endl;
    int now = x - 'a' + 1;
    now -= kari;
    for (auto i = 26; i >= 1; --i) {
      if ((i - now) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        kari = (i - now)/A;
        break;
      }
    }
    cerr << ans << endl;
  }
  ans += maximal(calc(U) + kari);
  cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int A;
string S;
vector<int> V;

int calc(string str) {
  assert(str.size() <= 7);
  int tmp = 1;
  int ans = 0;
  for (auto i = 0; i < (int)str.size(); ++i) {
    ans += tmp * (str[i] - 'a' + 1);
    tmp *= A;
  }
  //cerr << ans << endl;
  return ans;
}

string maximal(int h) {
  string ans = "";
  while (h > 0) {
    for (auto i = 26; i >= 1; --i) {
      if (h - i < 0) continue;
      if ((h - i) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        h = (h - i)/A;
        break;
      }
    }
    //cerr << ans << " " << h << endl;
  }
  return ans;
}

int main () {
  cin >> A >> S;
  if (S.size() <= 7) {
    cout << maximal(calc(S)) << endl;
    return 0;
  }
  string T = S.substr(0, S.size()-7);
  string U = S.substr(S.size()-7, 7);
  assert(S == T + U);
  string ans = 0;
  int kari = 0;
  for (auto j = 0; j < (int)T.size(); ++j) {
    char x = T[j];
    int now = x - 'a' + 1;
    now -= kari;
    for (auto i = 26; i >= 1; --i) {
      if ((i - now) % A == 0) {
        string t{(char)('a' + i - 1)};
        ans = ans + t;
        kari = (i - now)/A;
        break;
      }
    }
    cerr << ans << endl;
  }
  ans += maximal(calc(U) + kari);
  cout << ans << endl;
}
<|endoftext|>


<commit_before><commit_msg>`EntityFactory`: make 1 parameter constructor `explicit`.<commit_after><|endoftext|>


<commit_before>#include <cassert>
#include <utility>
#include <iostream>
#include <stdexcept>
#include <unordered_set>
#include <set>
#include <stack>
#include <algorithm>
#include <vector>

#include "structures/deductions.h"

#define AS_AFF(a, l) (a.is_true(l) ? l : -l)

// Case 0 inutilisée
Deductions::Deductions(int nb_var) : known_to_deduced(nb_var+1,std::unordered_set<int>()), deduced_to_known(nb_var+1,std::unordered_set<int>()) {
}

Deductions::Deductions(Deductions *that) : known_to_deduced(that->known_to_deduced),deduced_to_known(that->deduced_to_known) {
}

bool Deductions::has_literal(int literal) const  {
    return this->deduced_to_known[literal].size() != 0 ;
}
bool Deductions::has_variable(int var) const  {
    return this->has_literal(var) || this->has_literal(-var) ;
}

std::unordered_set<int> Deductions::get_deduced_from(int literal) const {
    return this->deduced_to_known[abs(literal)];
}

std::unordered_set<int> Deductions::get_deductions(int literal) const {
    return this->known_to_deduced[abs(literal)];
}

void Deductions::add_deduction(int literal, const std::unordered_set<int> &clause) {
    for(auto l : clause) {
        if(abs(l)==abs(literal))
            continue ;
        this->deduced_to_known[abs(literal)].insert(abs(l)) ;
        this->known_to_deduced[abs(l)].insert(abs(literal)) ;
    }
}
void Deductions::add_deduction(int literal, const std::set<int> &clause) {
    std::unordered_set<int> clause2(clause.begin(), clause.end());
    this->add_deduction(literal, clause2);
}

void Deductions::remove_deduction(int literal) {
    this->deduced_to_known[abs(literal)].clear() ;
    this->known_to_deduced[abs(literal)].clear() ;
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        deduced_to_known[i].erase(abs(literal)) ;
        known_to_deduced[i].erase(abs(literal)) ;
    }
}

void Deductions::print() const {
    std::cout << "############################" << std::endl ;
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        if(deduced_to_known[i].size() > 0) {
            std::cout << "# " << i << " deduced with " ;
            for(auto l : deduced_to_known[i]) {
                std::cout << l << " " ;
            }
            std::cout << std::endl ;
        }
    }
    std::cout << "###" << std::endl ;
    for(unsigned i = 1 ; i < known_to_deduced.size() ; i++) {
        if(known_to_deduced[i].size() > 0) {
            std::cout << "# " << i << " implied " ;
            for(auto l : known_to_deduced[i]) {
                std::cout << l << " " ;
            }
            std::cout << std::endl ;
        }
    }
    std::cout << "############################" << std::endl ;
}

void Deductions::print_edges(FILE *graph_file, const satsolver::Affectation &aff) const {
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        for(auto l : deduced_to_known[i]) {
            fprintf(graph_file, "\t\"%d\" -> \"%d\";\n", AS_AFF(aff, l), AS_AFF(aff, i));
        }
    }
}

// Un noeud est un UIP ssi tout chemin de la racine au conflit passe par lui
void Deductions::print_UIP(FILE *graph_file, const satsolver::Affectation &aff, int bet, int conflict) const {
    std::set<int> candidates_UIP ;
    std::set<int> nodes_in_path ;
    std::set<int> nodes_in_level ;
    std::vector<int> parent = std::vector<int>(aff.get_nb_var()+1,0);
    std::stack<int> DFS ;
    int node,tmp ;

    DFS.push(abs(bet)) ;
    parent[abs(bet)] = abs(bet) ;
    for(unsigned i = 1 ; i <= aff.get_nb_var() ; i++) {
        candidates_UIP.insert(i) ;
    }
    while(!DFS.empty()) {
        node = DFS.top() ;
        nodes_in_level.insert(node) ;
        DFS.pop() ;
        if(node == abs(conflict)) {
            nodes_in_path.clear() ;
            tmp = parent[abs(node)] ;
            std::cout << "Path : " << abs(node) << " " << tmp << " " ;
            while(tmp != abs(bet)) {
                if(candidates_UIP.find(tmp)!=candidates_UIP.end())
                    nodes_in_path.insert(AS_AFF(aff,tmp)) ;
                tmp = parent[tmp] ;
                assert(tmp) ;
                std::cout << tmp << " " ;
            }
            std::cout << std::endl ;
            nodes_in_path.insert(abs(bet)) ;
            candidates_UIP.clear() ;
            candidates_UIP.swap(nodes_in_path) ;
        }
        else {
            if(known_to_deduced[node].size() > 0) {
                for(auto l : known_to_deduced[node]) {
                    DFS.push(l) ;
                    parent[l] = node ;
                }
            }
        }
    }
    for(auto l : nodes_in_level)
        if(candidates_UIP.find(l) == candidates_UIP.end())
            fprintf(graph_file, "\t%d [color = \"blue\"];\n", AS_AFF(aff,l));
    for(auto l : candidates_UIP)
        fprintf(graph_file, "\t%d [color = \"yellow\"];\n", AS_AFF(aff,l));
}
<commit_msg>Fix bug in graph display.<commit_after>#include <cassert>
#include <utility>
#include <iostream>
#include <stdexcept>
#include <unordered_set>
#include <set>
#include <stack>
#include <algorithm>
#include <vector>

#define DEBUG false

#include "structures/deductions.h"

#define AS_AFF(a, l) (a.is_true(l) ? l : -l)

// Case 0 inutilisée
Deductions::Deductions(int nb_var) : known_to_deduced(nb_var+1,std::unordered_set<int>()), deduced_to_known(nb_var+1,std::unordered_set<int>()) {
}

Deductions::Deductions(Deductions *that) : known_to_deduced(that->known_to_deduced),deduced_to_known(that->deduced_to_known) {
}

bool Deductions::has_literal(int literal) const  {
    return this->deduced_to_known[literal].size() != 0 ;
}
bool Deductions::has_variable(int var) const  {
    return this->has_literal(var) || this->has_literal(-var) ;
}

std::unordered_set<int> Deductions::get_deduced_from(int literal) const {
    return this->deduced_to_known[abs(literal)];
}

std::unordered_set<int> Deductions::get_deductions(int literal) const {
    return this->known_to_deduced[abs(literal)];
}

void Deductions::add_deduction(int literal, const std::unordered_set<int> &clause) {
    for(auto l : clause) {
        if(abs(l)==abs(literal))
            continue ;
        this->deduced_to_known[abs(literal)].insert(abs(l)) ;
        this->known_to_deduced[abs(l)].insert(abs(literal)) ;
    }
}
void Deductions::add_deduction(int literal, const std::set<int> &clause) {
    std::unordered_set<int> clause2(clause.begin(), clause.end());
    this->add_deduction(literal, clause2);
}

void Deductions::remove_deduction(int literal) {
    this->deduced_to_known[abs(literal)].clear() ;
    this->known_to_deduced[abs(literal)].clear() ;
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        deduced_to_known[i].erase(abs(literal)) ;
        known_to_deduced[i].erase(abs(literal)) ;
    }
}

void Deductions::print() const {
    if(DEBUG) std::cout << "############################" << std::endl ;
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        if(deduced_to_known[i].size() > 0) {
            if(DEBUG) std::cout << "# " << i << " deduced with " ;
            for(auto l : deduced_to_known[i]) {
                if(DEBUG) std::cout << l << " " ;
            }
            if(DEBUG) std::cout << std::endl ;
        }
    }
    if(DEBUG) std::cout << "###" << std::endl ;
    for(unsigned i = 1 ; i < known_to_deduced.size() ; i++) {
        if(known_to_deduced[i].size() > 0) {
            if(DEBUG) std::cout << "# " << i << " implied " ;
            for(auto l : known_to_deduced[i]) {
                if(DEBUG) std::cout << l << " " ;
            }
            if(DEBUG) std::cout << std::endl ;
        }
    }
    if(DEBUG) std::cout << "############################" << std::endl ;
}

void Deductions::print_edges(FILE *graph_file, const satsolver::Affectation &aff) const {
    for(unsigned i = 1 ; i < deduced_to_known.size() ; i++) {
        for(auto l : deduced_to_known[i]) {
            fprintf(graph_file, "\t\"%d\" -> \"%d\";\n", AS_AFF(aff, l), AS_AFF(aff, i));
        }
    }
}

// Un noeud est un UIP ssi tout chemin de la racine au conflit passe par lui
void Deductions::print_UIP(FILE *graph_file, const satsolver::Affectation &aff, int bet, int conflict) const {
    std::set<int> candidates_UIP ;
    std::set<int> nodes_in_path ;
    std::set<int> nodes_in_level ;
    std::vector<int> parent = std::vector<int>(aff.get_nb_var()+1,0);
    std::stack<std::pair<int,int>> DFS ; // pile de (noeud,parent)
    int node,tmp ;
    std::pair<int,int> p ;

    DFS.push(std::pair<int,int>(abs(bet),abs(bet))) ;
    for(unsigned i = 1 ; i <= aff.get_nb_var() ; i++) {
        candidates_UIP.insert(i) ;
    }
    while(!DFS.empty()) {
        p = DFS.top() ;
        DFS.pop() ;
        node = p.first ;
        nodes_in_level.insert(node) ;
        parent[node] = p.second ;
        if(DEBUG) std::cout << "DFS(" << node << ")" << std::endl ;
        if(node == abs(conflict)) {
            nodes_in_path.clear() ;
            tmp = parent[node] ;
            if(DEBUG) std::cout << "Path : " << abs(node) << " " << tmp << " " ;
            while(tmp != abs(bet)) {
                if(candidates_UIP.find(tmp)!=candidates_UIP.end())
                    nodes_in_path.insert(tmp) ;
                tmp = parent[tmp] ;
                assert(tmp) ;
                if(DEBUG) std::cout << tmp << " " ;
            }
            if(DEBUG) std::cout << std::endl ;
            nodes_in_path.insert(abs(bet)) ;
            candidates_UIP.clear() ;
            candidates_UIP.swap(nodes_in_path) ;
        }
        else {
            if(known_to_deduced[node].size() > 0) {
                for(auto l : known_to_deduced[node]) {
                    DFS.push(std::pair<int,int>(l,node)) ;
                }
            }
        }
    }
    for(auto l : nodes_in_level)
        if(candidates_UIP.find(l) == candidates_UIP.end())
            fprintf(graph_file, "\t%d [color = \"blue\"];\n", AS_AFF(aff,l));
    for(auto l : candidates_UIP)
        fprintf(graph_file, "\t%d [color = \"yellow\"];\n", AS_AFF(aff,l));
}
<|endoftext|>