<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

// interface header
#include "ShotManager.h"

//
// ShotManager
//

/** initialize the singleton */
template <>
ShotManager* Singleton<ShotManager>::_instance = (ShotManager*)0;

ShotManager::ShotManager();
ShotManager::~ShotManager();

  int ShotManager::newShot ( FiringInfo *info, int param );
  void ShotManager::update ( double dt );

  void ShotManager::addEventHandler ( ShotEventCallbacks *cb )
  {
    callbacks.push_back(cb);
  }

  void ShotManager::removeEventHandler ( ShotEventCallbacks *cb )
  {
    for (size_t i = 0; i < callbacks.size(); i++ )
    {
      if (cb == callbacks[i])
      {
	callbacks.erase(callbacks.begin()+i);
	return;
      }
    }
  }

  ShotManager::Shot::Shot(FiringInfo* info, int GUID, int p = 0)
  {
    int param = p;
    int id = GUID;
    if (info)
    {
	startTime = info->timeSent;
    }
    else
	startTime = TimeKeeper::getCurrent().getSeconds();

    team = LastTeam;
    flag = Flags::Null;
    type = NoShot;

    lastUpdateTime = startTime;

    lifetime = 0;
    range = 0;

    for ( size_t i = 0; i < 3 i++)
	pos[i] = vec[i] = 0;
  }

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>stub the stubs don't redefine them<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

// interface header
#include "ShotManager.h"

//
// ShotManager
//

/** initialize the singleton */
template <>
ShotManager* Singleton<ShotManager>::_instance = (ShotManager*)0;

ShotManager::ShotManager()
{

}
ShotManager::~ShotManager()
{

}

  int ShotManager::newShot ( FiringInfo *info, int param )
  {
    return 0;
  }
  void ShotManager::update ( double dt )
  {

  }

  void ShotManager::addEventHandler ( ShotEventCallbacks *cb )
  {
    callbacks.push_back(cb);
  }

  void ShotManager::removeEventHandler ( ShotEventCallbacks *cb )
  {
    for (size_t i = 0; i < callbacks.size(); i++ )
    {
      if (cb == callbacks[i])
      {
	callbacks.erase(callbacks.begin()+i);
	return;
      }
    }
  }

  ShotManager::Shot::Shot(FiringInfo* info, int GUID, int p = 0)
  {
    int param = p;
    int id = GUID;
    if (info)
    {
	startTime = info->timeSent;
    }
    else
	startTime = TimeKeeper::getCurrent().getSeconds();

   // team = LastTeam;
    flag = Flags::Null;
    type = NoShot;

    lastUpdateTime = startTime;

    lifetime = 0;
    range = 0;

    for ( size_t i = 0; i < 3 i++)
	pos[i] = vec[i] = 0;
  }

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include "mbc1.h"

namespace gameboy {
namespace mbc {
MBC1::MBC1(uint8_t **romBanks, uint8_t num) :
    romBanks(romBanks),
    numOfROMBanks(num),
    currentROMBank(1) {
        ram = new uint8_t[8192];
}

MBC1::~MBC1() {
    delete[] ram;
}

uint8_t* MBC1::getExternalRAM() {
    return ram;
}

uint8_t* MBC1::getROMBank() {
    return romBanks[currentROMBank-1];
}

void MBC1::write(uint16_t address, uint8_t value) {
    if (address >= 0x2000 && address <= 0x3FFF) { // Lower 5 Bits of ROM Bank Number
        uint8_t lowerFiveBits = value & 0x1F;

        currentROMBank = (currentROMBank & 0xE0) | lowerFiveBits;
    } else if (address >= 0x4000 && address <= 0x5FFF) { // Upper 2 Bits of ROM Bank Number
        uint8_t upperTwoBits = value & 0x60;

        currentROMBank = (currentROMBank & 0x1F) | upperTwoBits;
    }

    if (currentROMBank == 0x00
        || currentROMBank == 0x20
        || currentROMBank == 0x40
        || currentROMBank == 0x60) {
        currentROMBank++;
    }
}
}
}<commit_msg>Fixed memory leak<commit_after>#include "mbc1.h"

namespace gameboy {
namespace mbc {
MBC1::MBC1(uint8_t **romBanks, uint8_t num) :
    romBanks(romBanks),
    numOfROMBanks(num),
    currentROMBank(1) {
        ram = new uint8_t[8192];
}

MBC1::~MBC1() {
    delete[] ram;

    for (int i = 0; i < numOfROMBanks; ++i) {
        delete[] romBanks[i];
    }
    delete[] romBanks;
}

uint8_t* MBC1::getExternalRAM() {
    return ram;
}

uint8_t* MBC1::getROMBank() {
    return romBanks[currentROMBank-1];
}

void MBC1::write(uint16_t address, uint8_t value) {
    if (address >= 0x2000 && address <= 0x3FFF) { // Lower 5 Bits of ROM Bank Number
        uint8_t lowerFiveBits = value & 0x1F;

        currentROMBank = (currentROMBank & 0xE0) | lowerFiveBits;
    } else if (address >= 0x4000 && address <= 0x5FFF) { // Upper 2 Bits of ROM Bank Number
        uint8_t upperTwoBits = value & 0x60;

        currentROMBank = (currentROMBank & 0x1F) | upperTwoBits;
    }

    if (currentROMBank == 0x00
        || currentROMBank == 0x20
        || currentROMBank == 0x40
        || currentROMBank == 0x60) {
        currentROMBank++;
    }
}
}
}<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/gpu/GrContext.h"
#include "src/core/SkLRUCache.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrProgramDesc.h"
#include "src/gpu/GrProgramInfo.h"
#include "src/gpu/effects/GrSkSLFP.h"

/**
 * The DDL Context is the one in effect during DDL Recording. It isn't backed by a GrGPU and
 * cannot allocate any GPU resources.
 */
class GrDDLContext final : public GrContext {
public:
    GrDDLContext(sk_sp<GrContextThreadSafeProxy> proxy)
            : INHERITED(proxy->backend(), proxy->priv().options(), proxy->priv().contextID()) {
        fThreadSafeProxy = std::move(proxy);
    }

    ~GrDDLContext() override {}

    void abandonContext() override {
        SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::abandonContext();
    }

    void releaseResourcesAndAbandonContext() override {
        SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::releaseResourcesAndAbandonContext();
    }

    void freeGpuResources() override {
        SkASSERT(0); // freeing resources in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::freeGpuResources();
    }

private:
    // TODO: Here we're pretending this isn't derived from GrContext. Switch this to be derived from
    // GrRecordingContext!
    GrContext* asDirectContext() override { return nullptr; }

    bool init(sk_sp<const GrCaps> caps) override {
        SkASSERT(caps);
        SkASSERT(fThreadSafeProxy); // should've been set in the ctor

        if (!INHERITED::init(std::move(caps))) {
            return false;
        }

        // DDL contexts/drawing managers always sort the oplists and attempt to reduce opsTask
        // splitting.
        this->setupDrawingManager(true, true);

        SkASSERT(this->caps());

        return true;
    }

    GrAtlasManager* onGetAtlasManager() override {
        SkASSERT(0);   // the DDL Recorders should never invoke this
        return nullptr;
    }

    // Add to the set of unique program infos required by this DDL
    void recordProgramInfo(const GrProgramInfo* programInfo) final {
        if (!programInfo) {
            return;
        }

        const GrCaps* caps = this->caps();

        if (this->backend() == GrBackendApi::kVulkan ||
            this->backend() == GrBackendApi::kMetal) {
            // Currently, both Vulkan and Metal require a live renderTarget to
            // compute the key
            return;
        }

        if (programInfo->requestedFeatures() & GrProcessor::CustomFeatures::kSampleLocations) {
            // Sample locations require a live renderTarget to compute the key
            return;
        }

        GrProgramDesc desc = caps->makeDesc(nullptr, *programInfo);
        if (!desc.isValid()) {
            return;
        }

        fProgramInfoMap.add(desc, programInfo);
    }

    void detachProgramData(SkTArray<ProgramData>* dst) final {
        SkASSERT(dst->empty());

        fProgramInfoMap.toArray(dst);
    }

private:
    class ProgramInfoMap : public ::SkNoncopyable {
        typedef const GrProgramDesc  CacheKey;
        typedef const GrProgramInfo* CacheValue;

    public:
        // All the programInfo data should be stored in the record-time arena so there is no
        // need to ref them here or to delete them in the destructor.
        ProgramInfoMap() : fMap(10) {}
        ~ProgramInfoMap() {}

        // TODO: this is doing a lot of reallocating of the ProgramDesc! Once the program descs
        // are allocated in the record-time area there won't be a problem.
        void add(CacheKey& desc, const GrProgramInfo* programInfo) {
            SkASSERT(desc.isValid());

            const CacheValue* preExisting = fMap.find(desc);
            if (preExisting) {
                return;
            }

            fMap.insert(desc, programInfo);
        }

        void toArray(SkTArray<ProgramData>* dst) {
            fMap.foreach([dst](CacheKey* programDesc, CacheValue* programInfo) {
                             // TODO: remove this allocation once the program descs are stored
                             // in the record-time arena.
                             dst->emplace_back(std::make_unique<const GrProgramDesc>(*programDesc),
                                               *programInfo);
                         });
        }

    private:
        struct DescHash {
            uint32_t operator()(CacheKey& desc) const {
                return SkOpts::hash_fn(desc.asKey(), desc.keyLength(), 0);
            }
        };

        SkLRUCache<CacheKey, CacheValue, DescHash> fMap;
    };

    ProgramInfoMap fProgramInfoMap;

    typedef GrContext INHERITED;
};

sk_sp<GrContext> GrContextPriv::MakeDDL(const sk_sp<GrContextThreadSafeProxy>& proxy) {
    sk_sp<GrContext> context(new GrDDLContext(proxy));

    if (!context->init(proxy->priv().refCaps())) {
        return nullptr;
    }
    return context;
}
<commit_msg>SkiaDawn: Early out in recordProgramInfo<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/gpu/GrContext.h"
#include "src/core/SkLRUCache.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrContextThreadSafeProxyPriv.h"
#include "src/gpu/GrProgramDesc.h"
#include "src/gpu/GrProgramInfo.h"
#include "src/gpu/effects/GrSkSLFP.h"

/**
 * The DDL Context is the one in effect during DDL Recording. It isn't backed by a GrGPU and
 * cannot allocate any GPU resources.
 */
class GrDDLContext final : public GrContext {
public:
    GrDDLContext(sk_sp<GrContextThreadSafeProxy> proxy)
            : INHERITED(proxy->backend(), proxy->priv().options(), proxy->priv().contextID()) {
        fThreadSafeProxy = std::move(proxy);
    }

    ~GrDDLContext() override {}

    void abandonContext() override {
        SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::abandonContext();
    }

    void releaseResourcesAndAbandonContext() override {
        SkASSERT(0); // abandoning in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::releaseResourcesAndAbandonContext();
    }

    void freeGpuResources() override {
        SkASSERT(0); // freeing resources in a DDL Recorder doesn't make a whole lot of sense
        INHERITED::freeGpuResources();
    }

private:
    // TODO: Here we're pretending this isn't derived from GrContext. Switch this to be derived from
    // GrRecordingContext!
    GrContext* asDirectContext() override { return nullptr; }

    bool init(sk_sp<const GrCaps> caps) override {
        SkASSERT(caps);
        SkASSERT(fThreadSafeProxy); // should've been set in the ctor

        if (!INHERITED::init(std::move(caps))) {
            return false;
        }

        // DDL contexts/drawing managers always sort the oplists and attempt to reduce opsTask
        // splitting.
        this->setupDrawingManager(true, true);

        SkASSERT(this->caps());

        return true;
    }

    GrAtlasManager* onGetAtlasManager() override {
        SkASSERT(0);   // the DDL Recorders should never invoke this
        return nullptr;
    }

    // Add to the set of unique program infos required by this DDL
    void recordProgramInfo(const GrProgramInfo* programInfo) final {
        if (!programInfo) {
            return;
        }

        const GrCaps* caps = this->caps();

        if (this->backend() == GrBackendApi::kVulkan ||
            this->backend() == GrBackendApi::kMetal ||
            this->backend() == GrBackendApi::kDawn) {
            // Currently, Vulkan, Metal and Dawn require a live renderTarget to
            // compute the key
            return;
        }

        if (programInfo->requestedFeatures() & GrProcessor::CustomFeatures::kSampleLocations) {
            // Sample locations require a live renderTarget to compute the key
            return;
        }

        GrProgramDesc desc = caps->makeDesc(nullptr, *programInfo);
        if (!desc.isValid()) {
            return;
        }

        fProgramInfoMap.add(desc, programInfo);
    }

    void detachProgramData(SkTArray<ProgramData>* dst) final {
        SkASSERT(dst->empty());

        fProgramInfoMap.toArray(dst);
    }

private:
    class ProgramInfoMap : public ::SkNoncopyable {
        typedef const GrProgramDesc  CacheKey;
        typedef const GrProgramInfo* CacheValue;

    public:
        // All the programInfo data should be stored in the record-time arena so there is no
        // need to ref them here or to delete them in the destructor.
        ProgramInfoMap() : fMap(10) {}
        ~ProgramInfoMap() {}

        // TODO: this is doing a lot of reallocating of the ProgramDesc! Once the program descs
        // are allocated in the record-time area there won't be a problem.
        void add(CacheKey& desc, const GrProgramInfo* programInfo) {
            SkASSERT(desc.isValid());

            const CacheValue* preExisting = fMap.find(desc);
            if (preExisting) {
                return;
            }

            fMap.insert(desc, programInfo);
        }

        void toArray(SkTArray<ProgramData>* dst) {
            fMap.foreach([dst](CacheKey* programDesc, CacheValue* programInfo) {
                             // TODO: remove this allocation once the program descs are stored
                             // in the record-time arena.
                             dst->emplace_back(std::make_unique<const GrProgramDesc>(*programDesc),
                                               *programInfo);
                         });
        }

    private:
        struct DescHash {
            uint32_t operator()(CacheKey& desc) const {
                return SkOpts::hash_fn(desc.asKey(), desc.keyLength(), 0);
            }
        };

        SkLRUCache<CacheKey, CacheValue, DescHash> fMap;
    };

    ProgramInfoMap fProgramInfoMap;

    typedef GrContext INHERITED;
};

sk_sp<GrContext> GrContextPriv::MakeDDL(const sk_sp<GrContextThreadSafeProxy>& proxy) {
    sk_sp<GrContext> context(new GrDDLContext(proxy));

    if (!context->init(proxy->priv().refCaps())) {
        return nullptr;
    }
    return context;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "GraphicsTest.h"
#include "FBOImage.h"
#include "GPUBrightnessFilter.h"
#include "GPUBlurFilter.h"
#include "GPUBandpassFilter.h"
#include "OGLImagingContext.h"

#include "../base/TestSuite.h"

#include <iostream>

using namespace avg;
using namespace std;

class FBOTest: public GraphicsTest {
public:
    FBOTest()
        : GraphicsTest("FBOTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("i8-64x64", GL_UNSIGNED_BYTE, I8);
        runImageTests("rgb24-64x64", GL_UNSIGNED_BYTE);
        runImageTests("rgb24alpha-64x64", GL_UNSIGNED_BYTE);
        runImageTests("i8-64x64", GL_FLOAT, I8);
        runImageTests("rgb24-64x64", GL_FLOAT);
        runImageTests("rgb24alpha-64x64", GL_FLOAT);

        runParameterPBOTest();
    }

private:
    void runImageTests(const string& sFName, int precision, PixelFormat pf = R8G8B8X8)
    {
        BitmapPtr pBmp = loadTestBmp(sFName, pf);
        cerr << "    Testing " << sFName << " (" << pBmp->getPixelFormatString() << ")" << endl;
        cerr << "      PBO:" << endl;
        PBOImage pbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
        runPBOImageTest(pbo, pBmp, string("pbo_")+sFName);
        if (pf != I8) {
            cerr << "      FBO:" << endl;
            FBOImage fbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
            runPBOImageTest(fbo, pBmp, string("fbo_")+sFName);
        }
    }

    void runParameterPBOTest()
    {
        cerr << "    Testing parameter PBO" << endl;
        PBOImage pbo(IntPoint(11, 1), I8, GL_FLOAT, false, false);
        float data[11];
        pbo.setImage(data);
    }

    void runPBOImageTest(PBOImage& pbo, BitmapPtr pBmp, const string& sFName)
    {
        pbo.setImage(pBmp);
        BitmapPtr pNewBmp = pbo.getImage();
        testEqual(*pNewBmp, *pBmp, sFName);
    }

};

class BrightnessFilterTest: public GraphicsTest {
public:
    BrightnessFilterTest()
        : GraphicsTest("BrightnessFilterTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("rgb24-64x64");
        runImageTests("rgb24alpha-64x64");
    }

private:
    void runImageTests(const string& sFName)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName);
        BitmapPtr pDestBmp;
        pDestBmp = GPUBrightnessFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
        testEqual(*pDestBmp, *pBmp, string("brightness_")+sFName);
    }
};

class BlurFilterTest: public GraphicsTest {
public:
    BlurFilterTest()
        : GraphicsTest("BlurFilterTest", 2)
    {
    }

    void runTests()
    {
        BitmapPtr pBmp;
        BitmapPtr pDestBmp;
/*
        // This has the effect of printing out all the brightness differences for different
        // kernel sizes.
        pBmp = loadTestBmp("spike");
        for (double stddev = 0.5; stddev < 5; stddev += 0.25) {
            pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), stddev).apply(pBmp);
            testEqualBrightness(*pDestBmp, *pBmp, 1);
        }
*/
        cerr << "    Testing spike, stddev 0.5" << endl;
        pBmp = loadTestBmp("spike");
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 0.5).apply(pBmp);
        testEqualBrightness(*pDestBmp, *pBmp, 5);
        testEqual(*pDestBmp, "blur05_spike");
        cerr << "    Testing spike, stddev 1" << endl;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
//        testEqualBrightness(*pDestBmp, *pBmp, 5);
        testEqual(*pDestBmp, "blur1_spike");
        cerr << "    Testing spike, stddev 3" << endl;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 3).apply(pBmp);
//        testEqualBrightness(*pDestBmp, *pBmp, 5);
        testEqual(*pDestBmp, "blur5_spike");

        cerr << "    Testing flat, stddev 5" << endl;
        pBmp = loadTestBmp("flat");
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 5).apply(pBmp);
        testEqualBrightness(*pDestBmp, *pBmp, 1);
        testEqual(*pDestBmp, *pBmp, "blur05_flat");

        runImageTests("rgb24-64x64");
        runImageTests("rgb24alpha-64x64");
    }

private:
    void runImageTests(const string& sFName)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName);
        BitmapPtr pDestBmp;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 10).apply(pBmp);
        testEqual(*pDestBmp, string("blur_")+sFName);
    }
};

class BandpassFilterTest: public GraphicsTest {
public:
    BandpassFilterTest()
        : GraphicsTest("BandpassFilterTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("spike", B8G8R8X8);
        runImageTests("i8-64x64", I8);
    }

private:
    void runImageTests(const string& sFName, PixelFormat pf)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName, pf);
        GPUBandpassFilter f(pBmp->getSize(), pf, 0.5, 1.5, 1, false);
        BitmapPtr pDestBmp = f.apply(pBmp);
        cerr << "        " << pDestBmp->avg() << endl;
        TEST(fabs(pDestBmp->avg() -128) < 0.05);
        testEqual(*pDestBmp, "bandpass_"+sFName, pf);
        TEST(pDestBmp->getPixelFormat() == pf);
    }
};

class GPUTestSuite: public TestSuite {
public:
    GPUTestSuite()
        : TestSuite("GPUTestSuite")
    {
        addTest(TestPtr(new FBOTest));
        addTest(TestPtr(new BrightnessFilterTest));
        addTest(TestPtr(new BlurFilterTest));
        addTest(TestPtr(new BandpassFilterTest));
    }
};

int main(int nargs, char** args)
{
    GraphicsTest::createResultImgDir();
    OGLImagingContext context(IntPoint(64, 64));

    bool bOK;
    if (!FBOImage::isFBOSupported()) {
        bOK = true;
        cerr << "  GL_EXT_framebuffer_object not supported. Skipping FBO test." << endl;
    } else {
        GPUTestSuite Suite;
        Suite.runTests();
        bOK = Suite.isOk();
    }

    if (bOK) {
        return 0;
    } else {
        return 1;
    }
}

<commit_msg>More lenient gpu test epsilons due to failures on GeForce 7600.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "GraphicsTest.h"
#include "FBOImage.h"
#include "GPUBrightnessFilter.h"
#include "GPUBlurFilter.h"
#include "GPUBandpassFilter.h"
#include "OGLImagingContext.h"

#include "../base/TestSuite.h"

#include <iostream>

using namespace avg;
using namespace std;

class FBOTest: public GraphicsTest {
public:
    FBOTest()
        : GraphicsTest("FBOTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("i8-64x64", GL_UNSIGNED_BYTE, I8);
        runImageTests("rgb24-64x64", GL_UNSIGNED_BYTE);
        runImageTests("rgb24alpha-64x64", GL_UNSIGNED_BYTE);
        runImageTests("i8-64x64", GL_FLOAT, I8);
        runImageTests("rgb24-64x64", GL_FLOAT);
        runImageTests("rgb24alpha-64x64", GL_FLOAT);

        runParameterPBOTest();
    }

private:
    void runImageTests(const string& sFName, int precision, PixelFormat pf = R8G8B8X8)
    {
        BitmapPtr pBmp = loadTestBmp(sFName, pf);
        cerr << "    Testing " << sFName << " (" << pBmp->getPixelFormatString() << ")" << endl;
        cerr << "      PBO:" << endl;
        PBOImage pbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
        runPBOImageTest(pbo, pBmp, string("pbo_")+sFName);
        if (pf != I8) {
            cerr << "      FBO:" << endl;
            FBOImage fbo(pBmp->getSize(), pBmp->getPixelFormat(), precision, true, true);
            runPBOImageTest(fbo, pBmp, string("fbo_")+sFName);
        }
    }

    void runParameterPBOTest()
    {
        cerr << "    Testing parameter PBO" << endl;
        PBOImage pbo(IntPoint(11, 1), I8, GL_FLOAT, false, false);
        float data[11];
        pbo.setImage(data);
    }

    void runPBOImageTest(PBOImage& pbo, BitmapPtr pBmp, const string& sFName)
    {
        pbo.setImage(pBmp);
        BitmapPtr pNewBmp = pbo.getImage();
        testEqual(*pNewBmp, *pBmp, sFName);
    }

};

class BrightnessFilterTest: public GraphicsTest {
public:
    BrightnessFilterTest()
        : GraphicsTest("BrightnessFilterTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("rgb24-64x64");
        runImageTests("rgb24alpha-64x64");
    }

private:
    void runImageTests(const string& sFName)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName);
        BitmapPtr pDestBmp;
        pDestBmp = GPUBrightnessFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
        testEqual(*pDestBmp, *pBmp, string("brightness_")+sFName);
    }
};

class BlurFilterTest: public GraphicsTest {
public:
    BlurFilterTest()
        : GraphicsTest("BlurFilterTest", 2)
    {
    }

    void runTests()
    {
        BitmapPtr pBmp;
        BitmapPtr pDestBmp;
/*
        // This has the effect of printing out all the brightness differences for different
        // kernel sizes.
        pBmp = loadTestBmp("spike");
        for (double stddev = 0.5; stddev < 5; stddev += 0.25) {
            pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), stddev).apply(pBmp);
            testEqualBrightness(*pDestBmp, *pBmp, 1);
        }
*/
        cerr << "    Testing spike, stddev 0.5" << endl;
        pBmp = loadTestBmp("spike");
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 0.5).apply(pBmp);
        testEqualBrightness(*pDestBmp, *pBmp, 7);
        testEqual(*pDestBmp, "blur05_spike");
        cerr << "    Testing spike, stddev 1" << endl;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 1).apply(pBmp);
//        testEqualBrightness(*pDestBmp, *pBmp, 5);
        testEqual(*pDestBmp, "blur1_spike");
        cerr << "    Testing spike, stddev 3" << endl;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 3).apply(pBmp);
//        testEqualBrightness(*pDestBmp, *pBmp, 5);
        testEqual(*pDestBmp, "blur5_spike");

        cerr << "    Testing flat, stddev 5" << endl;
        pBmp = loadTestBmp("flat");
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 5).apply(pBmp);
        testEqualBrightness(*pDestBmp, *pBmp, 1);
        testEqual(*pDestBmp, *pBmp, "blur05_flat");

        runImageTests("rgb24-64x64");
        runImageTests("rgb24alpha-64x64");
    }

private:
    void runImageTests(const string& sFName)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName);
        BitmapPtr pDestBmp;
        pDestBmp = GPUBlurFilter(pBmp->getSize(), pBmp->getPixelFormat(), 10).apply(pBmp);
        testEqual(*pDestBmp, string("blur_")+sFName);
    }
};

class BandpassFilterTest: public GraphicsTest {
public:
    BandpassFilterTest()
        : GraphicsTest("BandpassFilterTest", 2)
    {
    }

    void runTests()
    {
        runImageTests("spike", B8G8R8X8);
        runImageTests("i8-64x64", I8);
    }

private:
    void runImageTests(const string& sFName, PixelFormat pf)
    {
        cerr << "    Testing " << sFName << endl;
        BitmapPtr pBmp = loadTestBmp(sFName, pf);
        GPUBandpassFilter f(pBmp->getSize(), pf, 0.5, 1.5, 1, false);
        BitmapPtr pDestBmp = f.apply(pBmp);
        cerr << "        " << pDestBmp->avg() << endl;
        TEST(fabs(pDestBmp->avg() -128) < 0.06);
        testEqual(*pDestBmp, "bandpass_"+sFName, pf);
        TEST(pDestBmp->getPixelFormat() == pf);
    }
};

class GPUTestSuite: public TestSuite {
public:
    GPUTestSuite()
        : TestSuite("GPUTestSuite")
    {
        addTest(TestPtr(new FBOTest));
        addTest(TestPtr(new BrightnessFilterTest));
        addTest(TestPtr(new BlurFilterTest));
        addTest(TestPtr(new BandpassFilterTest));
    }
};

int main(int nargs, char** args)
{
    GraphicsTest::createResultImgDir();
    OGLImagingContext context(IntPoint(64, 64));

    bool bOK;
    if (!FBOImage::isFBOSupported()) {
        bOK = true;
        cerr << "  GL_EXT_framebuffer_object not supported. Skipping FBO test." << endl;
    } else {
        GPUTestSuite Suite;
        Suite.runTests();
        bOK = Suite.isOk();
    }

    if (bOK) {
        return 0;
    } else {
        return 1;
    }
}

<|endoftext|>


<commit_before>#include <ap_int.h>
#include "spbits.h"
#define num_levels 4
#include "sort.h"
using namespace std;

ap_uint<bwr> min_elem(ap_uint<bwr> a,
		ap_uint<bwr> b,
		ap_uint<bwr> c,
		ap_uint<bwr> d,
		ap_uint<bpow+1> *index);

void sorter::sort1(
		ap_uint<bwr> 	ret_win[cnr],
		ap_uint<bwr> 	*winner0,
		ap_uint<bpow+1> *winindex0,
		ap_uint<bwr> 	ret_win_next[cnr]){

#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS PIPELINE II=1
#pragma HLS INLINE

	ap_uint<bwr> win_l0[cnr];
#pragma HLS ARRAY_PARTITION variable=win_l0 complete dim=1
	ap_uint<bwr> win_l1[cnr/4];
#pragma HLS ARRAY_PARTITION variable=win_l1 complete dim=1
	ap_uint<bwr> win_l2[cnr/16];
#pragma HLS ARRAY_PARTITION variable=win_l2 complete dim=1

	ap_uint<bwr> win0, win1, win2, win0_t1,win0_t2;
	ap_uint<bpow+1> winid0, winid1, winid2;

	ap_uint<bpow+1> a_winid; ap_uint<bpow+1> a_winid_1; ap_uint<bpow+1> a_winid_2;
	ap_uint<bpow+1> a_winid_t1; ap_uint<bpow+1> a_winid_t2;

	int i,j;
	ap_uint<bpow+1> ranki[cnr];
#pragma HLS ARRAY_PARTITION variable=ranki complete dim=1
	ap_uint<bpow+1> ranki_l1[cnr/4];
#pragma HLS ARRAY_PARTITION variable=ranki_l1 complete dim=1
	ap_uint<bpow+1> ranki_l2[cnr/16];
#pragma HLS ARRAY_PARTITION variable=ranki_l2 complete dim=1

	for(int i=0;i<cnr;i++){
#pragma HLS UNROLL
		ranki[i]=i;
		win_l0[i]=ret_win[i];
	}

	//BUILD COMPARISON TREE
/*****************FIRST LEVEL******************************/
int ncomp=cnr;
	ncomp=ncomp/4;
	for (j = 0; j < ncomp; j = j+1){
#pragma HLS UNROLL
 // comparator loop
		win_l1[j]=min_elem(win_l0[4*(j)],
				win_l0[(4*j)+1],
				win_l0[(4*j)+2],
				win_l0[(4*j)+3],
				&a_winid);
		ranki_l1[j]=ranki[a_winid+(4*j)];
	}

	ncomp=ncomp/4;
/*****************SECOND LEVEL******************************/

	for (j = 0; j < ncomp; j = j+1){
#pragma HLS UNROLL
 // comparator loop
		win_l2[j]=min_elem(win_l1[4*(j)],
				win_l1[(4*j)+1],
				win_l1[(4*j)+2],
				win_l1[(4*j)+3],
				&a_winid_1);
		ranki_l2[j]=ranki_l1[a_winid_1+(4*j)];
	}

/*****************FINAL LEVEL******************************/
	win0_t1=min_elem(win_l2[0],win_l2[1],win_l2[2],win_l2[3],&a_winid_t1);
	win0_t2=min_elem(win_l2[4],win_l2[5],win_l2[6],win_l2[7],&a_winid_t2);

	//calculate winner and winner index
	if(win0_t1 > win0_t2){
		win0= win0_t1; a_winid_2=ranki_l2[a_winid_t1];
	}
	else{
		win0= win0_t2; a_winid_2=ranki_l2[4+a_winid_t2];
	}

	winid0=a_winid_2;
	*winner0= win0 ;//? win0 : 0x7E;
	if(win0==rankr[2*winid0])
		*winindex0= win0 ? ap_uint<bpow+1>((2* winid0)) : ap_uint<bpow+1>(0x7F);
	else
		*winindex0= win0 ? ap_uint<bpow+1>((2*winid0)+1) : ap_uint<bpow+1>(0x7F);

/***********Return the array which excludes MAX element to next stage**********/
	win_l0[winid0]=0;
	sort_label2:for(int h=0;h<cnr;h++)
		ret_win_next[h]=win_l0[h];

}

<commit_msg>Delete sort1.cpp<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "RFProtocolNooLite.h"

static range_type g_timing_pause[7] =
{
	{ 1800, 2300 },
	{ 380, 750 },
	{ 851, 1400 },
	{ 2500, 2700 },
	{ 0,0 }
};  // TODO FIXIT 500us, 1000us

static range_type g_timing_pulse[8] =
{
	{ 1800, 2300 },
	{ 200, 650 },
	{ 700, 1100 },
	{ 2500, 2700 },
	{ 0,0 }
};   // TODO FIXIT 500us, 1000us

CRFProtocolNooLite::CRFProtocolNooLite()
	:CRFProtocol(g_timing_pause, g_timing_pulse, 0, 1, "bBbBbBbBbBbBbBbBbBbBbBa")
{
	m_Debug = true;
}

CRFProtocolNooLite::~CRFProtocolNooLite()
{
}

// The 1-Wire CRC scheme is described in Maxim Application Note 27:
// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products"

uint8_t CRFProtocolNooLite::crc8(uint8_t *addr, uint8_t len)
{
	uint8_t crc = 0;

	for (uint8_t i = 0; i<len; i++)
	{
		uint8_t inbyte = addr[i];
		for (uint8_t j = 0; j<8; j++)
		{
			uint8_t mix = (crc ^ inbyte) & 0x01;
			crc >>= 1;
			if (mix)
				crc ^= 0x8C;

			inbyte >>= 1;
		}
	}
	return crc;
}

unsigned char CRFProtocolNooLite::getByte(const string &bits, size_t first, size_t len)
{
	return (unsigned char)bits2long(reverse(bits.substr(first, len)));
}

bool CRFProtocolNooLite::bits2packet(const string& bits, uint8_t *packet, size_t *packetLen)
{

	size_t bytes = (bits.substr(1).length()+7) / 8;
	size_t extraBits = bits.substr(1).length() % 8;

	if (*packetLen < bytes)
		return false;

	string reverseBits = reverse(bits.substr(1));
	while (reverseBits.length() % 8)
		reverseBits += '0';

	for (unsigned int i = 0; i < bytes; i++)
	{
		packet[bytes - 1 - i] = (uint8_t)bits2long(reverseBits.substr(i * 8, 8));// min(8, reverseBits.length() - i * 8)));
	}

	uint8_t packetCrc = crc8(packet, (uint8_t)bytes);
	*packetLen = bytes;

	return packetCrc==0;

	unsigned char fmt = (unsigned char)bits2long(reverse(bits.substr(bits.length() - 16, 8)));
	*packetLen = 0;
	packet[0] = getByte(bits, 1, 5) << 3;
	size_t len = bits.length();

	switch (fmt)
	{
	case 0:
		if (len != 38)
			return false;
		*packetLen = 5;
		break;

	case 7: //?
 		if (len != 74)
			return false;
		*packetLen = 9;
		break;

	default:
		return false;
	}

	for (unsigned int i = 0; i < *packetLen-1; i++)
	{
		packet[*packetLen-i-1] = getByte(bits, len - 8*(i+1));
	}

	return true;
}

string CRFProtocolNooLite::DecodePacket(const string& raw)
{
	if (raw.length() < 10 )
		return "";

	string_vector v;
	SplitString(raw, 'd', v);

	if (v.size()==1)
		SplitString(raw, 'a', v);   // TODO CheckIT

	string res;

	for_each(string_vector, v, i)
	{
		res = ManchesterDecode('b' + *i, false, 'b', 'c', 'B', 'C');

		if (res.length() >=37)
		{

			uint8_t packet[20];
			size_t packetLen = sizeof(packet);

			if (bits2packet(res, packet, &packetLen))
				return res;
			/*  TODO
			unsigned char packetCrc = crc8(packet, packetLen);
			// check crc;

			if (!packetCrc)
			{
				return res;
			}*/
		}
	}

	return "";
}

string CRFProtocolNooLite::DecodeData(const string& bits) //
{
	uint8_t packet[20];
	size_t packetLen = sizeof(packet);

	if (!bits2packet(bits, packet, &packetLen))
		return bits;

	if (packetLen < 5)
		return bits;

	char buffer[100]="";
	uint8_t fmt = packet[packetLen - 2];
	switch (fmt)
	{
	case 0:
		{
			bool sync = (packet[0] & 8) != 0;
			uint8_t cmd =packet[0] >> 4;
			snprintf(buffer, sizeof(buffer), "flip=%d cmd=%d addr=%04x fmt=%02x crc=%02x", sync, cmd, (uint16_t)((packet[2] << 8) + packet[1]), (uint8_t)packet[3], (uint8_t)packet[4]);
			break;
		}
	case 1:
		{
			uint8_t type = packet[3];
			snprintf(buffer, sizeof(buffer), "cmd=%02x b0=%02x type=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
				type,
				(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
		}
		break;

	case 7:
		if (packet[1]==21)
		{
			uint8_t type = (packet[3] >> 4) & 7;
			int t0 = ((packet[3] & 0x7) << 8) | packet[2];
			float t = (float)0.1*((packet[3]&8)?4096-t0:t0);
			int h = packet[4];
			int s3 = packet[5];
			bool bat = (packet[3] & 0x80) != 0;
			if (type==2)
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%d type=%d t=%.1f h=%d s3=%02x bat=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
					type, t, h, s3, bat,
					(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
			} else if (type==3)
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%d type=%d t=%.1f s3=%02x bat=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
					type, t, s3, bat,
					(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
			} else
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%02x type=%02x b3=%02x b4=%02x b5=%02x addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1], (uint8_t)packet[2], (uint8_t)packet[3], (uint8_t)packet[4], (uint8_t)packet[5], (uint16_t)((packet[7] << 8) + packet[6]), (uint8_t)packet[8], (uint8_t)packet[9]);
			}

		}
		else
		{
			snprintf(buffer, sizeof(buffer), "cmd=%02x b1=%02x b2=%02x b3=%02x b4=%02x b5=%02x addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1], (uint8_t)packet[2], (uint8_t)packet[3], (uint8_t)packet[4], (uint8_t)packet[5], (uint16_t)((packet[7] << 8) + packet[6]), (uint8_t)packet[8], (uint8_t)packet[9]);
		}
		break;

<<<<<<< HEAD
	default:
		m_Log->Printf(3, "len=%d addr=%04x fmt=%02x crc=%02x", packetLen, (uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
		m_Log->PrintBuffer(3, packet, packetLen);
=======
	default:
		m_Log->PrintBuffer(3, packet, packetLen);
		snprintf(buffer, sizeof(buffer), "len=%d,addr=%04x,fmt=%02x,crc=%02x", packetLen, (uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
>>>>>>> master
	}

	return buffer;
}

bool CRFProtocolNooLite::needDump(const string &rawData)
{
	return rawData.find(m_PacketDelimeter) != rawData.npos;
}
<commit_msg>fix conflict<commit_after>#include "stdafx.h"
#include "RFProtocolNooLite.h"

static range_type g_timing_pause[7] =
{
	{ 1800, 2300 },
	{ 380, 750 },
	{ 851, 1400 },
	{ 2500, 2700 },
	{ 0,0 }
};  // TODO FIXIT 500us, 1000us

static range_type g_timing_pulse[8] =
{
	{ 1800, 2300 },
	{ 200, 650 },
	{ 700, 1100 },
	{ 2500, 2700 },
	{ 0,0 }
};   // TODO FIXIT 500us, 1000us

CRFProtocolNooLite::CRFProtocolNooLite()
	:CRFProtocol(g_timing_pause, g_timing_pulse, 0, 1, "bBbBbBbBbBbBbBbBbBbBbBa")
{
	m_Debug = true;
}

CRFProtocolNooLite::~CRFProtocolNooLite()
{
}

// The 1-Wire CRC scheme is described in Maxim Application Note 27:
// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products"

uint8_t CRFProtocolNooLite::crc8(uint8_t *addr, uint8_t len)
{
	uint8_t crc = 0;

	for (uint8_t i = 0; i<len; i++)
	{
		uint8_t inbyte = addr[i];
		for (uint8_t j = 0; j<8; j++)
		{
			uint8_t mix = (crc ^ inbyte) & 0x01;
			crc >>= 1;
			if (mix)
				crc ^= 0x8C;

			inbyte >>= 1;
		}
	}
	return crc;
}

unsigned char CRFProtocolNooLite::getByte(const string &bits, size_t first, size_t len)
{
	return (unsigned char)bits2long(reverse(bits.substr(first, len)));
}

bool CRFProtocolNooLite::bits2packet(const string& bits, uint8_t *packet, size_t *packetLen)
{

	size_t bytes = (bits.substr(1).length()+7) / 8;
	size_t extraBits = bits.substr(1).length() % 8;

	if (*packetLen < bytes)
		return false;

	string reverseBits = reverse(bits.substr(1));
	while (reverseBits.length() % 8)
		reverseBits += '0';

	for (unsigned int i = 0; i < bytes; i++)
	{
		packet[bytes - 1 - i] = (uint8_t)bits2long(reverseBits.substr(i * 8, 8));// min(8, reverseBits.length() - i * 8)));
	}

	uint8_t packetCrc = crc8(packet, (uint8_t)bytes);
	*packetLen = bytes;

	return packetCrc==0;

	unsigned char fmt = (unsigned char)bits2long(reverse(bits.substr(bits.length() - 16, 8)));
	*packetLen = 0;
	packet[0] = getByte(bits, 1, 5) << 3;
	size_t len = bits.length();

	switch (fmt)
	{
	case 0:
		if (len != 38)
			return false;
		*packetLen = 5;
		break;

	case 7: //?
 		if (len != 74)
			return false;
		*packetLen = 9;
		break;

	default:
		return false;
	}

	for (unsigned int i = 0; i < *packetLen-1; i++)
	{
		packet[*packetLen-i-1] = getByte(bits, len - 8*(i+1));
	}

	return true;
}

string CRFProtocolNooLite::DecodePacket(const string& raw)
{
	if (raw.length() < 10 )
		return "";

	string_vector v;
	SplitString(raw, 'd', v);

	if (v.size()==1)
		SplitString(raw, 'a', v);   // TODO CheckIT

	string res;

	for_each(string_vector, v, i)
	{
		res = ManchesterDecode('b' + *i, false, 'b', 'c', 'B', 'C');

		if (res.length() >=37)
		{

			uint8_t packet[20];
			size_t packetLen = sizeof(packet);

			if (bits2packet(res, packet, &packetLen))
				return res;
			/*  TODO
			unsigned char packetCrc = crc8(packet, packetLen);
			// check crc;

			if (!packetCrc)
			{
				return res;
			}*/
		}
	}

	return "";
}

string CRFProtocolNooLite::DecodeData(const string& bits) //
{
	uint8_t packet[20];
	size_t packetLen = sizeof(packet);

	if (!bits2packet(bits, packet, &packetLen))
		return bits;

	if (packetLen < 5)
		return bits;

	char buffer[100]="";
	uint8_t fmt = packet[packetLen - 2];
	switch (fmt)
	{
	case 0:
		{
			bool sync = (packet[0] & 8) != 0;
			uint8_t cmd =packet[0] >> 4;
			snprintf(buffer, sizeof(buffer), "flip=%d cmd=%d addr=%04x fmt=%02x crc=%02x", sync, cmd, (uint16_t)((packet[2] << 8) + packet[1]), (uint8_t)packet[3], (uint8_t)packet[4]);
			break;
		}
	case 1:
		{
			uint8_t type = packet[3];
			snprintf(buffer, sizeof(buffer), "cmd=%02x b0=%02x type=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
				type,
				(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
		}
		break;

	case 7:
		if (packet[1]==21)
		{
			uint8_t type = (packet[3] >> 4) & 7;
			int t0 = ((packet[3] & 0x7) << 8) | packet[2];
			float t = (float)0.1*((packet[3]&8)?4096-t0:t0);
			int h = packet[4];
			int s3 = packet[5];
			bool bat = (packet[3] & 0x80) != 0;
			if (type==2)
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%d type=%d t=%.1f h=%d s3=%02x bat=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
					type, t, h, s3, bat,
					(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
			} else if (type==3)
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%d type=%d t=%.1f s3=%02x bat=%d addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1],
					type, t, s3, bat,
					(uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
			} else
			{
				snprintf(buffer, sizeof(buffer), "flip=%02x cmd=%02x type=%02x b3=%02x b4=%02x b5=%02x addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1], (uint8_t)packet[2], (uint8_t)packet[3], (uint8_t)packet[4], (uint8_t)packet[5], (uint16_t)((packet[7] << 8) + packet[6]), (uint8_t)packet[8], (uint8_t)packet[9]);
			}

		}
		else
		{
			snprintf(buffer, sizeof(buffer), "cmd=%02x b1=%02x b2=%02x b3=%02x b4=%02x b5=%02x addr=%04x fmt=%02x crc=%02x", (uint8_t)packet[0], (uint8_t)packet[1], (uint8_t)packet[2], (uint8_t)packet[3], (uint8_t)packet[4], (uint8_t)packet[5], (uint16_t)((packet[7] << 8) + packet[6]), (uint8_t)packet[8], (uint8_t)packet[9]);
		}
		break;

	default:
		m_Log->Printf(3, "len=%d addr=%04x fmt=%02x crc=%02x", packetLen, (uint16_t)((packet[packetLen - 3] << 8) + packet[packetLen - 4]), (uint8_t)fmt, (uint8_t)packet[packetLen - 1]);
		m_Log->PrintBuffer(3, packet, packetLen);
	}

	return buffer;
}

bool CRFProtocolNooLite::needDump(const string &rawData)
{
	return rawData.find(m_PacketDelimeter) != rawData.npos;
}
<|endoftext|>


<commit_before>#include "client_http.hpp"
#include "server_http.hpp"

#include <cassert>

using namespace std;

#ifndef USE_STANDALONE_ASIO
namespace asio = boost::asio;
#endif

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>;

int main() {
  // Test ScopeRunner
  {
    SimpleWeb::ScopeRunner scope_runner;
    std::thread cancel_thread;
    {
      assert(scope_runner.count == 0);
      auto lock = scope_runner.continue_lock();
      assert(lock);
      assert(scope_runner.count == 1);
      {
        auto lock = scope_runner.continue_lock();
        assert(lock);
        assert(scope_runner.count == 2);
      }
      assert(scope_runner.count == 1);
      cancel_thread = thread([&scope_runner] {
        scope_runner.stop();
        assert(scope_runner.count == -1);
      });
      this_thread::sleep_for(chrono::milliseconds(500));
      assert(scope_runner.count == 1);
    }
    cancel_thread.join();
    assert(scope_runner.count == -1);
    auto lock = scope_runner.continue_lock();
    assert(!lock);
    scope_runner.stop();
    assert(scope_runner.count == -1);

    scope_runner.count = 0;

    vector<thread> threads;
    for(size_t c = 0; c < 100; ++c) {
      threads.emplace_back([&scope_runner] {
        auto lock = scope_runner.continue_lock();
        assert(scope_runner.count > 0);
      });
    }
    for(auto &thread : threads)
      thread.join();
    assert(scope_runner.count == 0);
  }

  HttpServer server;
  server.config.port = 8080;

  server.resource["^/string$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    auto content = request->content.string();

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
              << content;
  };

  server.resource["^/string2$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    response->write(request->content.string());
  };

  server.resource["^/string3$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    stringstream stream;
    stream << request->content.rdbuf();
    response->write(stream);
  };

  server.resource["^/string4$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
    response->write(SimpleWeb::StatusCode::client_error_forbidden, {{"Test1", "test2"}, {"tesT3", "test4"}});
  };

  server.resource["^/info$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    stringstream content_stream;
    content_stream << request->method << " " << request->path << " " << request->http_version << " ";
    content_stream << request->header.find("test parameter")->second;

    content_stream.seekp(0, ios::end);

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n"
              << content_stream.rdbuf();
  };

  server.resource["^/work$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
    thread work_thread([response] {
      this_thread::sleep_for(chrono::seconds(5));
      response->write("Work done");
    });
    work_thread.detach();
  };

  server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    string number = request->path_match[1];
    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n"
              << number;
  };

  server.resource["^/header$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    auto content = request->header.find("test1")->second + request->header.find("test2")->second;

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
              << content;
  };

  server.resource["^/query_string$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    assert(request->path == "/query_string");
    assert(request->query_string == "testing");
    auto queries = request->parse_query_string();
    auto it = queries.find("Testing");
    assert(it != queries.end() && it->first == "testing" && it->second == "");
    response->write(request->query_string);
  };

  thread server_thread([&server]() {
    // Start server
    server.start();
  });

  this_thread::sleep_for(chrono::seconds(1));

  server.stop();
  server_thread.join();

  server_thread = thread([&server]() {
    // Start server
    server.start();
  });

  this_thread::sleep_for(chrono::seconds(1));

  // Test various request types
  {
    HttpClient client("localhost:8080");
    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string2", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string3", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string4", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::client_error_forbidden);
      assert(r->header.size() == 3);
      assert(r->header.find("test1")->second == "test2");
      assert(r->header.find("tEst3")->second == "test4");
      assert(r->header.find("content-length")->second == "0");
      output << r->content.rdbuf();
      assert(output.str() == "");
    }

    {
      stringstream output;
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("GET", "/info", "", {{"Test Parameter", "test value"}});
      output << r->content.rdbuf();
      assert(output.str() == "GET /info 1.1 test value");
    }

    {
      stringstream output;
      auto r = client.request("GET", "/match/123");
      output << r->content.rdbuf();
      assert(output.str() == "123");
    }
  }
  {
    HttpClient client("localhost:8080");

    HttpClient::Connection *connection;
    {
      // test performing the stream version of the request methods first
      stringstream output;
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
      assert(client.connections.size() == 1);
      connection = client.connections.begin()->get();
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      output << r->content.rdbuf();
      assert(output.str() == "A string");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }

    {
      stringstream output;
      auto r = client.request("GET", "/header", "", {{"test1", "test"}, {"test2", "ing"}});
      output << r->content.rdbuf();
      assert(output.str() == "testing");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }

    {
      stringstream output;
      auto r = client.request("GET", "/query_string?testing");
      assert(r->content.string() == "testing");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }
  }

  // Test asynchronous requests
  {
    HttpClient client("localhost:8080");
    bool call = false;
    client.request("GET", "/match/123", [&call](shared_ptr<HttpClient::Response> response, const SimpleWeb::error_code &ec) {
      assert(!ec);
      stringstream output;
      output << response->content.rdbuf();
      assert(output.str() == "123");
      call = true;
    });
    client.io_service->run();
    assert(call);

    {
      vector<int> calls(100, 0);
      vector<thread> threads;
      for(size_t c = 0; c < 100; ++c) {
        threads.emplace_back([c, &client, &calls] {
          client.request("GET", "/match/123", [c, &calls](shared_ptr<HttpClient::Response> response, const SimpleWeb::error_code &ec) {
            assert(!ec);
            stringstream output;
            output << response->content.rdbuf();
            assert(output.str() == "123");
            calls[c] = 1;
          });
        });
      }
      for(auto &thread : threads)
        thread.join();
      assert(client.connections.size() == 100);
      client.io_service->reset();
      client.io_service->run();
      assert(client.connections.size() == 1);
      for(auto call : calls)
        assert(call);
    }
  }

  // Test concurrent synchronous request calls
  {
    HttpClient client("localhost:8080");
    {
      vector<int> calls(2, 0);
      vector<thread> threads;
      for(size_t c = 0; c < 2; ++c) {
        threads.emplace_back([c, &client, &calls] {
          try {
            auto r = client.request("GET", "/match/123");
            assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
            assert(r->content.string() == "123");
            calls[c] = 1;
          }
          catch(...) {
            assert(false);
          }
        });
      }
      for(auto &thread : threads)
        thread.join();
      assert(client.connections.size() == 1);
      for(auto call : calls)
        assert(call);
    }
  }

  // Test multiple requests through a persistent connection
  {
    HttpClient client("localhost:8080");
    assert(client.connections.size() == 0);
    for(size_t c = 0; c < 5000; ++c) {
      auto r1 = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r1->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r1->content.string() == "A string");
      assert(client.connections.size() == 1);

      stringstream content("A string");
      auto r2 = client.request("POST", "/string", content);
      assert(SimpleWeb::status_code(r2->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r2->content.string() == "A string");
      assert(client.connections.size() == 1);
    }
  }

  // Test multiple requests through new several client objects
  for(size_t c = 0; c < 100; ++c) {
    {
      HttpClient client("localhost:8080");
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
      assert(client.connections.size() == 1);
    }

    {
      HttpClient client("localhost:8080");
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
      assert(client.connections.size() == 1);
    }
  }

  // Test Client client's stop()
  for(size_t c = 0; c < 40; ++c) {
    auto io_service = make_shared<asio::io_service>();
    bool call = false;
    HttpClient client("localhost:8080");
    client.io_service = io_service;
    client.request("GET", "/work", [&call](shared_ptr<HttpClient::Response> /*response*/, const SimpleWeb::error_code &ec) {
      call = true;
      assert(ec);
    });
    thread thread([io_service] {
      io_service->run();
    });
    this_thread::sleep_for(chrono::milliseconds(100));
    client.stop();
    this_thread::sleep_for(chrono::milliseconds(100));
    thread.join();
    assert(call);
  }

  // Test Client destructor that should cancel the client's request
  for(size_t c = 0; c < 40; ++c) {
    auto io_service = make_shared<asio::io_service>();
    {
      HttpClient client("localhost:8080");
      client.io_service = io_service;
      client.request("GET", "/work", [](shared_ptr<HttpClient::Response> /*response*/, const SimpleWeb::error_code & /*ec*/) {
        assert(false);
      });
      thread thread([io_service] {
        io_service->run();
      });
      thread.detach();
      this_thread::sleep_for(chrono::milliseconds(100));
    }
    this_thread::sleep_for(chrono::milliseconds(100));
  }

  server.stop();
  server_thread.join();

  // Test server destructor
  {
    auto io_service = make_shared<asio::io_service>();
    bool call = false;
    bool client_catch = false;
    {
      HttpServer server;
      server.config.port = 8081;
      server.io_service = io_service;
      server.resource["^/test$"]["GET"] = [&call](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
        call = true;
        thread sleep_thread([response] {
          this_thread::sleep_for(chrono::seconds(5));
          response->write(SimpleWeb::StatusCode::success_ok, "test");
          response->send([](const SimpleWeb::error_code & /*ec*/) {
            assert(false);
          });
        });
        sleep_thread.detach();
      };
      server.start();
      thread server_thread([io_service] {
        io_service->run();
      });
      server_thread.detach();
      this_thread::sleep_for(chrono::seconds(1));
      thread client_thread([&client_catch] {
        HttpClient client("localhost:8081");
        try {
          auto r = client.request("GET", "/test");
          assert(false);
        }
        catch(...) {
          client_catch = true;
        }
      });
      client_thread.detach();
      this_thread::sleep_for(chrono::seconds(1));
    }
    this_thread::sleep_for(chrono::seconds(5));
    assert(call);
    assert(client_catch);
    io_service->stop();
  }
}
<commit_msg>Added Request::remote_endpoint tests to io_test<commit_after>#include "client_http.hpp"
#include "server_http.hpp"

#include <cassert>

using namespace std;

#ifndef USE_STANDALONE_ASIO
namespace asio = boost::asio;
#endif

using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>;

int main() {
  // Test ScopeRunner
  {
    SimpleWeb::ScopeRunner scope_runner;
    std::thread cancel_thread;
    {
      assert(scope_runner.count == 0);
      auto lock = scope_runner.continue_lock();
      assert(lock);
      assert(scope_runner.count == 1);
      {
        auto lock = scope_runner.continue_lock();
        assert(lock);
        assert(scope_runner.count == 2);
      }
      assert(scope_runner.count == 1);
      cancel_thread = thread([&scope_runner] {
        scope_runner.stop();
        assert(scope_runner.count == -1);
      });
      this_thread::sleep_for(chrono::milliseconds(500));
      assert(scope_runner.count == 1);
    }
    cancel_thread.join();
    assert(scope_runner.count == -1);
    auto lock = scope_runner.continue_lock();
    assert(!lock);
    scope_runner.stop();
    assert(scope_runner.count == -1);

    scope_runner.count = 0;

    vector<thread> threads;
    for(size_t c = 0; c < 100; ++c) {
      threads.emplace_back([&scope_runner] {
        auto lock = scope_runner.continue_lock();
        assert(scope_runner.count > 0);
      });
    }
    for(auto &thread : threads)
      thread.join();
    assert(scope_runner.count == 0);
  }

  HttpServer server;
  server.config.port = 8080;

  server.resource["^/string$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    auto content = request->content.string();

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
              << content;

    assert(!request->remote_endpoint_address().empty());
    assert(request->remote_endpoint_port() != 0);
  };

  server.resource["^/string2$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    response->write(request->content.string());
  };

  server.resource["^/string3$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    stringstream stream;
    stream << request->content.rdbuf();
    response->write(stream);
  };

  server.resource["^/string4$"]["POST"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
    response->write(SimpleWeb::StatusCode::client_error_forbidden, {{"Test1", "test2"}, {"tesT3", "test4"}});
  };

  server.resource["^/info$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    stringstream content_stream;
    content_stream << request->method << " " << request->path << " " << request->http_version << " ";
    content_stream << request->header.find("test parameter")->second;

    content_stream.seekp(0, ios::end);

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content_stream.tellp() << "\r\n\r\n"
              << content_stream.rdbuf();
  };

  server.resource["^/work$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
    thread work_thread([response] {
      this_thread::sleep_for(chrono::seconds(5));
      response->write("Work done");
    });
    work_thread.detach();
  };

  server.resource["^/match/([0-9]+)$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    string number = request->path_match[1];
    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << number.length() << "\r\n\r\n"
              << number;
  };

  server.resource["^/header$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    auto content = request->header.find("test1")->second + request->header.find("test2")->second;

    *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"
              << content;
  };

  server.resource["^/query_string$"]["GET"] = [](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> request) {
    assert(request->path == "/query_string");
    assert(request->query_string == "testing");
    auto queries = request->parse_query_string();
    auto it = queries.find("Testing");
    assert(it != queries.end() && it->first == "testing" && it->second == "");
    response->write(request->query_string);
  };

  thread server_thread([&server]() {
    // Start server
    server.start();
  });

  this_thread::sleep_for(chrono::seconds(1));

  server.stop();
  server_thread.join();

  server_thread = thread([&server]() {
    // Start server
    server.start();
  });

  this_thread::sleep_for(chrono::seconds(1));

  // Test various request types
  {
    HttpClient client("localhost:8080");
    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string2", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string3", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string4", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::client_error_forbidden);
      assert(r->header.size() == 3);
      assert(r->header.find("test1")->second == "test2");
      assert(r->header.find("tEst3")->second == "test4");
      assert(r->header.find("content-length")->second == "0");
      output << r->content.rdbuf();
      assert(output.str() == "");
    }

    {
      stringstream output;
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
    }

    {
      stringstream output;
      auto r = client.request("GET", "/info", "", {{"Test Parameter", "test value"}});
      output << r->content.rdbuf();
      assert(output.str() == "GET /info 1.1 test value");
    }

    {
      stringstream output;
      auto r = client.request("GET", "/match/123");
      output << r->content.rdbuf();
      assert(output.str() == "123");
    }
  }
  {
    HttpClient client("localhost:8080");

    HttpClient::Connection *connection;
    {
      // test performing the stream version of the request methods first
      stringstream output;
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      output << r->content.rdbuf();
      assert(output.str() == "A string");
      assert(client.connections.size() == 1);
      connection = client.connections.begin()->get();
    }

    {
      stringstream output;
      auto r = client.request("POST", "/string", "A string");
      output << r->content.rdbuf();
      assert(output.str() == "A string");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }

    {
      stringstream output;
      auto r = client.request("GET", "/header", "", {{"test1", "test"}, {"test2", "ing"}});
      output << r->content.rdbuf();
      assert(output.str() == "testing");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }

    {
      stringstream output;
      auto r = client.request("GET", "/query_string?testing");
      assert(r->content.string() == "testing");
      assert(client.connections.size() == 1);
      assert(connection == client.connections.begin()->get());
    }
  }

  // Test asynchronous requests
  {
    HttpClient client("localhost:8080");
    bool call = false;
    client.request("GET", "/match/123", [&call](shared_ptr<HttpClient::Response> response, const SimpleWeb::error_code &ec) {
      assert(!ec);
      stringstream output;
      output << response->content.rdbuf();
      assert(output.str() == "123");
      call = true;
    });
    client.io_service->run();
    assert(call);

    {
      vector<int> calls(100, 0);
      vector<thread> threads;
      for(size_t c = 0; c < 100; ++c) {
        threads.emplace_back([c, &client, &calls] {
          client.request("GET", "/match/123", [c, &calls](shared_ptr<HttpClient::Response> response, const SimpleWeb::error_code &ec) {
            assert(!ec);
            stringstream output;
            output << response->content.rdbuf();
            assert(output.str() == "123");
            calls[c] = 1;
          });
        });
      }
      for(auto &thread : threads)
        thread.join();
      assert(client.connections.size() == 100);
      client.io_service->reset();
      client.io_service->run();
      assert(client.connections.size() == 1);
      for(auto call : calls)
        assert(call);
    }
  }

  // Test concurrent synchronous request calls
  {
    HttpClient client("localhost:8080");
    {
      vector<int> calls(2, 0);
      vector<thread> threads;
      for(size_t c = 0; c < 2; ++c) {
        threads.emplace_back([c, &client, &calls] {
          try {
            auto r = client.request("GET", "/match/123");
            assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
            assert(r->content.string() == "123");
            calls[c] = 1;
          }
          catch(...) {
            assert(false);
          }
        });
      }
      for(auto &thread : threads)
        thread.join();
      assert(client.connections.size() == 1);
      for(auto call : calls)
        assert(call);
    }
  }

  // Test multiple requests through a persistent connection
  {
    HttpClient client("localhost:8080");
    assert(client.connections.size() == 0);
    for(size_t c = 0; c < 5000; ++c) {
      auto r1 = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r1->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r1->content.string() == "A string");
      assert(client.connections.size() == 1);

      stringstream content("A string");
      auto r2 = client.request("POST", "/string", content);
      assert(SimpleWeb::status_code(r2->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r2->content.string() == "A string");
      assert(client.connections.size() == 1);
    }
  }

  // Test multiple requests through new several client objects
  for(size_t c = 0; c < 100; ++c) {
    {
      HttpClient client("localhost:8080");
      auto r = client.request("POST", "/string", "A string");
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
      assert(client.connections.size() == 1);
    }

    {
      HttpClient client("localhost:8080");
      stringstream content("A string");
      auto r = client.request("POST", "/string", content);
      assert(SimpleWeb::status_code(r->status_code) == SimpleWeb::StatusCode::success_ok);
      assert(r->content.string() == "A string");
      assert(client.connections.size() == 1);
    }
  }

  // Test Client client's stop()
  for(size_t c = 0; c < 40; ++c) {
    auto io_service = make_shared<asio::io_service>();
    bool call = false;
    HttpClient client("localhost:8080");
    client.io_service = io_service;
    client.request("GET", "/work", [&call](shared_ptr<HttpClient::Response> /*response*/, const SimpleWeb::error_code &ec) {
      call = true;
      assert(ec);
    });
    thread thread([io_service] {
      io_service->run();
    });
    this_thread::sleep_for(chrono::milliseconds(100));
    client.stop();
    this_thread::sleep_for(chrono::milliseconds(100));
    thread.join();
    assert(call);
  }

  // Test Client destructor that should cancel the client's request
  for(size_t c = 0; c < 40; ++c) {
    auto io_service = make_shared<asio::io_service>();
    {
      HttpClient client("localhost:8080");
      client.io_service = io_service;
      client.request("GET", "/work", [](shared_ptr<HttpClient::Response> /*response*/, const SimpleWeb::error_code & /*ec*/) {
        assert(false);
      });
      thread thread([io_service] {
        io_service->run();
      });
      thread.detach();
      this_thread::sleep_for(chrono::milliseconds(100));
    }
    this_thread::sleep_for(chrono::milliseconds(100));
  }

  server.stop();
  server_thread.join();

  // Test server destructor
  {
    auto io_service = make_shared<asio::io_service>();
    bool call = false;
    bool client_catch = false;
    {
      HttpServer server;
      server.config.port = 8081;
      server.io_service = io_service;
      server.resource["^/test$"]["GET"] = [&call](shared_ptr<HttpServer::Response> response, shared_ptr<HttpServer::Request> /*request*/) {
        call = true;
        thread sleep_thread([response] {
          this_thread::sleep_for(chrono::seconds(5));
          response->write(SimpleWeb::StatusCode::success_ok, "test");
          response->send([](const SimpleWeb::error_code & /*ec*/) {
            assert(false);
          });
        });
        sleep_thread.detach();
      };
      server.start();
      thread server_thread([io_service] {
        io_service->run();
      });
      server_thread.detach();
      this_thread::sleep_for(chrono::seconds(1));
      thread client_thread([&client_catch] {
        HttpClient client("localhost:8081");
        try {
          auto r = client.request("GET", "/test");
          assert(false);
        }
        catch(...) {
          client_catch = true;
        }
      });
      client_thread.detach();
      this_thread::sleep_for(chrono::seconds(1));
    }
    this_thread::sleep_for(chrono::seconds(5));
    assert(call);
    assert(client_catch);
    io_service->stop();
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "Minikin"

#include <cutils/log.h>
#include <stdlib.h>
#include <stdint.h>
#include <utils/UniquePtr.h>
#include <minikin/MinikinFont.h>
#include <minikin/AnalyzeStyle.h>
#include <minikin/FontFamily.h>

using std::vector;

namespace android {

bool FontFamily::addFont(MinikinFont* typeface) {
    const uint32_t os2Tag = MinikinFont::MakeTag('O', 'S', '/', '2');
    size_t os2Size = 0;
    bool ok = typeface->GetTable(os2Tag, NULL, &os2Size);
    if (!ok) return false;
    UniquePtr<uint8_t[]> os2Data(new uint8_t[os2Size]);
    ok = typeface->GetTable(os2Tag, os2Data.get(), &os2Size);
    if (!ok) return false;
    int weight;
    bool italic;
    if (analyzeStyle(os2Data.get(), os2Size, &weight, &italic)) {
        //ALOGD("analyzed weight = %d, italic = %s", weight, italic ? "true" : "false");
        FontStyle style(weight, italic);
        addFont(typeface, style);
        return true;
    } else {
        ALOGD("failed to analyze style");
    }
    return false;
}

void FontFamily::addFont(MinikinFont* typeface, FontStyle style) {
    mFonts.push_back(Font(typeface, style));
    ALOGD("added font, mFonts.size() = %d", mFonts.size());
}

// Compute a matching metric between two styles - 0 is an exact match
int computeMatch(FontStyle style1, FontStyle style2) {
    if (style1 == style2) return 0;
    int score = abs(style1.getWeight() - style2.getWeight());
    if (style1.getItalic() != style2.getItalic()) {
        score += 2;
    }
    return score;
}

MinikinFont* FontFamily::getClosestMatch(FontStyle style) const {
    const Font* bestFont = NULL;
    int bestMatch = 0;
    for (size_t i = 0; i < mFonts.size(); i++) {
        const Font& font = mFonts[i];
        int match = computeMatch(font.style, style);
        if (i == 0 || match < bestMatch) {
            bestFont = &font;
            bestMatch = match;
        }
    }
    return bestFont == NULL ? NULL : bestFont->typeface;
}

size_t FontFamily::getNumFonts() const {
    return mFonts.size();
}

MinikinFont* FontFamily::getFont(size_t index) const {
    return mFonts[index].typeface;
}

FontStyle FontFamily::getStyle(size_t index) const {
    return mFonts[index].style;
}

}  // namespace android
<commit_msg>Use canonical UniquePtr.h header<commit_after>/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define LOG_TAG "Minikin"

#include <cutils/log.h>
#include <stdlib.h>
#include <stdint.h>
#include <minikin/MinikinFont.h>
#include <minikin/AnalyzeStyle.h>
#include <minikin/FontFamily.h>
#include <UniquePtr.h>

using std::vector;

namespace android {

bool FontFamily::addFont(MinikinFont* typeface) {
    const uint32_t os2Tag = MinikinFont::MakeTag('O', 'S', '/', '2');
    size_t os2Size = 0;
    bool ok = typeface->GetTable(os2Tag, NULL, &os2Size);
    if (!ok) return false;
    UniquePtr<uint8_t[]> os2Data(new uint8_t[os2Size]);
    ok = typeface->GetTable(os2Tag, os2Data.get(), &os2Size);
    if (!ok) return false;
    int weight;
    bool italic;
    if (analyzeStyle(os2Data.get(), os2Size, &weight, &italic)) {
        //ALOGD("analyzed weight = %d, italic = %s", weight, italic ? "true" : "false");
        FontStyle style(weight, italic);
        addFont(typeface, style);
        return true;
    } else {
        ALOGD("failed to analyze style");
    }
    return false;
}

void FontFamily::addFont(MinikinFont* typeface, FontStyle style) {
    mFonts.push_back(Font(typeface, style));
    ALOGD("added font, mFonts.size() = %d", mFonts.size());
}

// Compute a matching metric between two styles - 0 is an exact match
int computeMatch(FontStyle style1, FontStyle style2) {
    if (style1 == style2) return 0;
    int score = abs(style1.getWeight() - style2.getWeight());
    if (style1.getItalic() != style2.getItalic()) {
        score += 2;
    }
    return score;
}

MinikinFont* FontFamily::getClosestMatch(FontStyle style) const {
    const Font* bestFont = NULL;
    int bestMatch = 0;
    for (size_t i = 0; i < mFonts.size(); i++) {
        const Font& font = mFonts[i];
        int match = computeMatch(font.style, style);
        if (i == 0 || match < bestMatch) {
            bestFont = &font;
            bestMatch = match;
        }
    }
    return bestFont == NULL ? NULL : bestFont->typeface;
}

size_t FontFamily::getNumFonts() const {
    return mFonts.size();
}

MinikinFont* FontFamily::getFont(size_t index) const {
    return mFonts[index].typeface;
}

FontStyle FontFamily::getStyle(size_t index) const {
    return mFonts[index].style;
}

}  // namespace android
<|endoftext|>


<commit_before>#if defined(PLATFORM_DESKTOP)

#include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
#include "Vajra/Framework/Settings/SettingsHelper.h"

#include <string>

void GetSettingsFileHandleForReading(std::ifstream& file) {
	std::string filePath = FRAMEWORK->GetFileSystemUtils()->GetDeviceSettingsResourcesPath() + SETTINGS_FILE_NAME;
	file.open(filePath);
	ASSERT(file.good(), "Valid file handle for %s", filePath.c_str());
}

void GetSettingsFileHandleForWriting(std::ofstream& file) {
	std::string filePath = FRAMEWORK->GetFileSystemUtils()->GetDeviceSettingsResourcesPath() + SETTINGS_FILE_NAME;
	file.open(filePath);
	ASSERT(file.good(), "Valid file handle for %s", filePath.c_str());
}

#endif
<commit_msg>Fix build.<commit_after>#if defined(PLATFORM_DESKTOP)

#include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
#include "Vajra/Framework/Settings/SettingsHelper.h"

#include <string>

bool DoesSettingsFileExist() {
	// TODO [Hack] Return true we are sure that the settings.xml file will always exist on desktop or the default file will have been copied over from GameResources
	return true;
}

void GetSettingsFileHandleForReading(std::ifstream& file) {
	std::string filePath = FRAMEWORK->GetFileSystemUtils()->GetDeviceSettingsResourcesPath() + SETTINGS_FILE_NAME;
	file.open(filePath);
	ASSERT(file.good(), "Valid file handle for %s", filePath.c_str());
}

void GetSettingsFileHandleForWriting(std::ofstream& file) {
	std::string filePath = FRAMEWORK->GetFileSystemUtils()->GetDeviceSettingsResourcesPath() + SETTINGS_FILE_NAME;
	file.open(filePath);
	ASSERT(file.good(), "Valid file handle for %s", filePath.c_str());
}

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <ncurses.h>

#define N 80

struct TFlake{
    double x;
    double y;
    double v;
};

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

    struct TFlake flake[N];
    const char image[] = {'.', 'o', 'O'};

    initscr();
    if (!has_colors()){
        endwin();
        fprintf(stderr, "Colors not supported.\n");
        return EXIT_FAILURE;
    }

    curs_set(0);
    start_color();
    init_pair(1, COLOR_RED, COLOR_BLACK);
    init_pair(2, COLOR_GREEN, COLOR_BLACK);
    init_pair(3, COLOR_YELLOW, COLOR_BLACK);

    srand(time(NULL));

    /* Initialization */
    for (int i=0; i<N; i++){
        flake[i].y = rand() % LINES;
        flake[i].x = rand() % COLS;
        flake[i].v = rand() % 3 + 1;
    }

    while(1){
        /* Update physics */
        for (int i=0; i<N; i++){
            flake[i].y += flake[i].v;
            flake[i].x += rand() % 3 - 1;
        }

        /* Display data */
        clear();
        for (int i=0; i<N; i++){
            attron(COLOR_PAIR( (int) flake[i].v));
            mvaddch(
                    (int) flake[i].y % LINES,
                    (int) flake[i].x % COLS,
                    image[ (int) flake[i].v - 1] );
            attroff(COLOR_PAIR( (int) flake[i].v));
        }
        refresh();

        usleep(130000);
    }

    curs_set(1);
    endwin();
    return EXIT_SUCCESS;
}
<commit_msg>Delete snow.cpp<commit_after><|endoftext|>