text:
/**********************************************************\
Original Author: Richard Bateman (taxilian)

Created:    Oct 15, 2009
License:    Dual license model; choose one of two:
            New BSD License
            http://www.opensource.org/licenses/bsd-license.php
            - or -
            GNU Lesser General Public License, version 2.1
            http://www.gnu.org/licenses/lgpl-2.1.html

Copyright 2009 Richard Bateman, Firebreath development team
\**********************************************************/

#include <memory>
#include <boost/config.hpp>
#include <boost/algorithm/string.hpp>

#include "NpapiTypes.h"
#include "APITypes.h"
#include "NpapiPluginModule.h"
#include "NPJavascriptObject.h"
#include "NPObjectAPI.h"
#include "DOM/Document.h"
#include "DOM/Window.h"
#include "variant_list.h"

#include "NpapiStream.h"
#include "NpapiBrowserHost.h"
#include "precompiled_headers.h" // On windows, everything above this line in PCH

#include "NPVariantUtil.h"
#include "URI.h"

using namespace FB::Npapi;

using boost::algorithm::split;
using boost::algorithm::is_any_of;
using boost::algorithm::istarts_with;
using std::vector;
using std::string;
using std::map;

namespace
{
    struct MethodCallReq
    {
        //FB::variant
    };

    template<class T>
    NPVariantBuilderMap::value_type makeBuilderEntry()
    {
        return NPVariantBuilderMap::value_type(&typeid(T), select_npvariant_builder::select<T>());
    }

    NPVariantBuilderMap makeNPVariantBuilderMap()
    {
        NPVariantBuilderMap tdm;
        tdm.insert(makeBuilderEntry<bool>());
        tdm.insert(makeBuilderEntry<char>());
        tdm.insert(makeBuilderEntry<unsigned char>());
        tdm.insert(makeBuilderEntry<short>());
        tdm.insert(makeBuilderEntry<unsigned short>());
        tdm.insert(makeBuilderEntry<int>());
        tdm.insert(makeBuilderEntry<unsigned int>());
        tdm.insert(makeBuilderEntry<long>());
        tdm.insert(makeBuilderEntry<unsigned long>());

#ifndef BOOST_NO_LONG_LONG
        tdm.insert(makeBuilderEntry<long long>());
        tdm.insert(makeBuilderEntry<unsigned long long>());
#endif

        tdm.insert(makeBuilderEntry<float>());
        tdm.insert(makeBuilderEntry<double>());

        tdm.insert(makeBuilderEntry<std::string>());
        tdm.insert(makeBuilderEntry<std::wstring>());

        tdm.insert(makeBuilderEntry<FB::FBNull>());
        tdm.insert(makeBuilderEntry<FB::FBVoid>());
        //tdm.insert(makeBuilderEntry<FB::FBDateString>());
        tdm.insert(makeBuilderEntry<FB::VariantList>());
        tdm.insert(makeBuilderEntry<FB::VariantMap>());
        tdm.insert(makeBuilderEntry<FB::JSAPIPtr>());
        tdm.insert(makeBuilderEntry<FB::JSAPIWeakPtr>());
        tdm.insert(makeBuilderEntry<FB::JSObjectPtr>());

        return tdm;
    }

    const NPVariantBuilderMap& getNPVariantBuilderMap()
    {
        static const NPVariantBuilderMap tdm = makeNPVariantBuilderMap();
        return tdm;
    }
}

NpapiBrowserHost::NpapiBrowserHost(NpapiPluginModule *module, NPP npp)
    : module(module), m_npp(npp)
{
    assert(module != NULL);
    // Initialize NPNFuncs to NULL values
    memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
}

NpapiBrowserHost::~NpapiBrowserHost(void)
{
}

void NpapiBrowserHost::shutdown() {
    memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
    FB::BrowserHost::shutdown();

    // Release these now as the BrowserHost will be expired when the they go out of scope in the destructor.
    m_htmlWin.reset();
    m_htmlElement.reset();
    m_htmlDoc.reset();
}

bool NpapiBrowserHost::_scheduleAsyncCall(void (*func)(void *), void *userData) const
{
    if (isShutDown())
        return false;
    PluginThreadAsyncCall(func, userData);
    return true;
}

void NpapiBrowserHost::setBrowserFuncs(NPNetscapeFuncs *pFuncs)
{
    copyNPBrowserFuncs(&NPNFuncs, pFuncs, m_npp);

    NPObject *window(NULL);
    NPObject *element(NULL);
    try {
        GetValue(NPNVWindowNPObject, (void**)&window);
        GetValue(NPNVPluginElementNPObject, (void**)&element);

        m_htmlWin = NPObjectAPIPtr(new FB::Npapi::NPObjectAPI(window, ptr_cast<NpapiBrowserHost>(shared_from_this())));
        m_htmlElement = NPObjectAPIPtr(new FB::Npapi::NPObjectAPI(element, ptr_cast<NpapiBrowserHost>(shared_from_this())));
        ReleaseObject(window);
        ReleaseObject(element);
    } catch (...) {
        if (window && !m_htmlWin)
            ReleaseObject(window);
        if (element && !m_htmlElement)
            ReleaseObject(element);
    }
    if (m_htmlWin) {
        m_htmlDoc = ptr_cast<NPObjectAPI>(m_htmlWin->GetProperty("document").cast<FB::JSObjectPtr>());
    }
}

FB::DOM::DocumentPtr NpapiBrowserHost::getDOMDocument()
{
    if (!m_htmlDoc)
        throw std::runtime_error("Cannot find HTML document");

    return FB::DOM::Document::create(m_htmlDoc);
}

FB::DOM::WindowPtr NpapiBrowserHost::getDOMWindow()
{
    if (!m_htmlWin)
        throw std::runtime_error("Cannot find HTML window");

    return FB::DOM::Window::create(m_htmlWin);
}

FB::DOM::ElementPtr FB::Npapi::NpapiBrowserHost::getDOMElement()
{
    if (!m_htmlElement)
        throw std::runtime_error("Cannot find HTML window");

    return FB::DOM::Element::create(m_htmlElement);
}

void FB::Npapi::NpapiBrowserHost::deferred_release( NPObject* obj )
{
    m_deferredObjects.push(obj);
    if (isMainThread()) {
        DoDeferredRelease();
    }
}

bool isExpired(std::pair<void*, FB::Npapi::NPObjectWeakRef> cur) {
    return cur.second.expired();
}

void FB::Npapi::NpapiBrowserHost::DoDeferredRelease() const
{
    assertMainThread();
    NPObject* cur(NULL);
    while (m_deferredObjects.try_pop(cur)) {
        ReleaseObject(cur);
    }
    // Also remove any expired IDispatch WeakReferences
    NPObjectRefMap::iterator iter = m_cachedNPObject.begin();
    NPObjectRefMap::iterator endIter = m_cachedNPObject.end();
    while (iter != endIter) {
        if (isExpired(*iter))
            m_cachedNPObject.erase(iter++);
        else
            ++iter;
    }
}

void NpapiBrowserHost::evaluateJavaScript(const std::string &script)
{
    assertMainThread();
    NPVariant retVal;
    NPVariant tmp;

    this->getNPVariant(&tmp, FB::variant(script));

    if (!m_htmlWin)
        throw std::runtime_error("Cannot find HTML window");

    if (this->Evaluate(m_htmlWin->getNPObject(),
                       &tmp.value.stringValue, &retVal)) {
        this->ReleaseVariantValue(&retVal);
        /* Throw away returned variant. NPN_Evaluate supports returning
           stuff from JS, but ActiveX IHTMLWindow2::execScript does not */
        return;
    } else {
        throw script_error("Error executing JavaScript code");
    }
}

FB::variant NpapiBrowserHost::getVariant(const NPVariant *npVar)
{
    FB::variant retVal;
    switch(npVar->type) {
        case NPVariantType_Null:
            retVal = FB::variant_detail::null();
            break;

        case NPVariantType_Bool:
            retVal = npVar->value.boolValue;
            break;

        case NPVariantType_Int32:
            retVal = npVar->value.intValue;
            break;

        case NPVariantType_Double:
            retVal = npVar->value.doubleValue;
            break;

        case NPVariantType_String:
            retVal = std::string(npVar->value.stringValue.UTF8Characters, npVar->value.stringValue.UTF8Length);
            break;

        case NPVariantType_Object:
            retVal = JSObjectPtr(new NPObjectAPI(npVar->value.objectValue, ptr_cast<NpapiBrowserHost>(shared_from_this())));
            break;

        case NPVariantType_Void:
        default:
            // Do nothing; it's already void =]
            break;
    }

    return retVal;
}

bool NpapiBrowserHost::isSafari() const
{
    // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-us) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
    std::string agent(UserAgent());
    return boost::algorithm::contains(agent, "Safari") && !isChrome();
}

bool NpapiBrowserHost::isFirefox() const
{
    // Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0) Gecko/20100101 Firefox/4.0
    // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15
    std::string agent(UserAgent());
    return boost::algorithm::contains(agent, "Firefox");
}

bool NpapiBrowserHost::isChrome() const
{
    // Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16
    std::string agent(UserAgent());
    return boost::algorithm::contains(agent, "Chrome");
}

void NpapiBrowserHost::getNPVariant(NPVariant *dst, const FB::variant &var)
{
    assertMainThread();

    const NPVariantBuilderMap& builderMap = getNPVariantBuilderMap();
    const std::type_info& type = var.get_type();
    NPVariantBuilderMap::const_iterator it = builderMap.find(&type);

    if (it == builderMap.end()) {
        // unhandled type :(
        return;
    }

    *dst = (it->second)(FB::ptr_cast<NpapiBrowserHost>(shared_from_this()), var);
}

NPError NpapiBrowserHost::GetURLNotify(const char* url, const char* target, void* notifyData) const
{
    assertMainThread();
    if (NPNFuncs.geturlnotify != NULL) {
        return NPNFuncs.geturlnotify(m_npp, url, target, notifyData);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::GetURL(const char* url, const char* target) const
{
    assertMainThread();
    if (NPNFuncs.geturl != NULL) {
        return NPNFuncs.geturl(m_npp, url, target);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::PostURLNotify(const char* url, const char* target, uint32_t len,
                                        const char* buf, NPBool file, void* notifyData) const
{
    assertMainThread();
    if (NPNFuncs.posturlnotify != NULL) {
        return NPNFuncs.posturlnotify(m_npp, url, target, len, buf, file, notifyData);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::PostURL(const char* url, const char* target, uint32_t len,
                                  const char* buf, NPBool file) const
{
    assertMainThread();
    if (NPNFuncs.posturl != NULL) {
        return NPNFuncs.posturl(m_npp, url, target, len, buf, file);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::RequestRead(NPStream* stream, NPByteRange* rangeList) const
{
    assertMainThread();
    if (NPNFuncs.requestread != NULL) {
        return NPNFuncs.requestread(stream, rangeList);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::NewStream(NPMIMEType type, const char* target, NPStream** stream) const
{
    assertMainThread();
    if (NPNFuncs.newstream != NULL) {
        return NPNFuncs.newstream(m_npp, type, target, stream);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

int32_t NpapiBrowserHost::Write(NPStream* stream, int32_t len, void* buffer) const
{
    assertMainThread();
    if (NPNFuncs.write != NULL) {
        return NPNFuncs.write(m_npp, stream, len, buffer);
    } else {
        return 0;
    }
}

NPError NpapiBrowserHost::DestroyStream(NPStream* stream, NPReason reason) const
{
    assertMainThread();
    if (NPNFuncs.destroystream != NULL) {
        return NPNFuncs.destroystream(m_npp, stream, reason);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

void* NpapiBrowserHost::MemAlloc(uint32_t size) const
{
    return module->MemAlloc(size);
}
void NpapiBrowserHost::MemFree(void* ptr) const
{
    module->MemFree(ptr);
}
uint32_t NpapiBrowserHost::MemFlush(uint32_t size) const
{
    return module->MemFlush(size);
}

NPObject *NpapiBrowserHost::RetainObject(NPObject *npobj) const
{
    assertMainThread();
    return module->RetainObject(npobj);
}
void NpapiBrowserHost::ReleaseObject(NPObject *npobj) const
{
    assertMainThread();
    return module->ReleaseObject(npobj);
}
void NpapiBrowserHost::ReleaseVariantValue(NPVariant *variant) const
{
    assertMainThread();
    return module->ReleaseVariantValue(variant);
}

NPIdentifier NpapiBrowserHost::GetStringIdentifier(const NPUTF8 *name) const
{
    assertMainThread();
    return module->GetStringIdentifier(name);
}
void NpapiBrowserHost::GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers) const
{
    assertMainThread();
    return module->GetStringIdentifiers(names, nameCount, identifiers);
}
NPIdentifier NpapiBrowserHost::GetIntIdentifier(int32_t intid) const
{
    assertMainThread();
    return module->GetIntIdentifier(intid);
}
bool NpapiBrowserHost::IdentifierIsString(NPIdentifier identifier) const
{
    assertMainThread();
    return module->IdentifierIsString(identifier);
}
NPUTF8 *NpapiBrowserHost::UTF8FromIdentifier(NPIdentifier identifier) const
{
    assertMainThread();
    return module->UTF8FromIdentifier(identifier);
}
std::string NpapiBrowserHost::StringFromIdentifier(NPIdentifier identifier) const
{
    assertMainThread();
    return module->StringFromIdentifier(identifier);
}
int32_t NpapiBrowserHost::IntFromIdentifier(NPIdentifier identifier) const
{
    assertMainThread();
    return module->IntFromIdentifier(identifier);
}

void NpapiBrowserHost::SetStatus(const char* message) const
{
    assertMainThread();
    if (NPNFuncs.status != NULL) {
        NPNFuncs.status(m_npp, message);
    }
}

const char* NpapiBrowserHost::UserAgent() const
{
    assertMainThread();
    if (NPNFuncs.uagent != NULL) {
        return NPNFuncs.uagent(m_npp);
    } else {
        return NULL;
    }
}

NPError NpapiBrowserHost::GetValue(NPNVariable variable, void *value) const
{
    assertMainThread();
    if (NPNFuncs.getvalue != NULL) {
        return NPNFuncs.getvalue(m_npp, variable, value);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

NPError NpapiBrowserHost::SetValue(NPPVariable variable, void *value) const
{
    assertMainThread();
    if (NPNFuncs.setvalue != NULL) {
        return NPNFuncs.setvalue(m_npp, variable, value);
    } else {
        return NPERR_GENERIC_ERROR;
    }
}

void NpapiBrowserHost::InvalidateRect2(const NPRect& invalidRect) const
{
    NPRect rect = invalidRect;
    return InvalidateRect(&rect);
}

void NpapiBrowserHost::InvalidateRect(NPRect *invalidRect) const
{
    assertMainThread();
    if (NPNFuncs.invalidaterect != NULL) {
        NPNFuncs.invalidaterect(m_npp, invalidRect);
    }
}

void NpapiBrowserHost::InvalidateRegion(NPRegion invalidRegion) const
{
    assertMainThread();
    if (NPNFuncs.invalidateregion != NULL) {
        NPNFuncs.invalidateregion(m_npp, invalidRegion);
    }
}

void NpapiBrowserHost::ForceRedraw() const
{
    assertMainThread();
    if (NPNFuncs.forceredraw != NULL) {
        NPNFuncs.forceredraw(m_npp);
    }
}

void NpapiBrowserHost::PushPopupsEnabledState(NPBool enabled) const
{
    assertMainThread();
    if (NPNFuncs.pushpopupsenabledstate != NULL) {
        NPNFuncs.pushpopupsenabledstate(m_npp, enabled);
    }
}

void NpapiBrowserHost::PopPopupsEnabledState() const
{
    assertMainThread();
    if (NPNFuncs.poppopupsenabledstate != NULL) {
        NPNFuncs.poppopupsenabledstate(m_npp);
    }
}

void NpapiBrowserHost::PluginThreadAsyncCall(void (*func) (void *), void *userData) const
{
    if (NPNFuncs.pluginthreadasynccall != NULL) {
        NPNFuncs.pluginthreadasynccall(m_npp, func, userData);
    }
}

/* npruntime.h definitions */
NPObject *NpapiBrowserHost::CreateObject(NPClass *aClass) const
{
    assertMainThread();
    if (NPNFuncs.createobject != NULL) {
        return NPNFuncs.createobject(m_npp, aClass);
    } else {
        return NULL;
    }
}

bool NpapiBrowserHost::Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args,
                              uint32_t argCount, NPVariant *result) const
{
    assertMainThread();
    if (NPNFuncs.invoke != NULL) {
        return NPNFuncs.invoke(m_npp, npobj, methodName, args, argCount, result);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::InvokeDefault(NPObject *npobj, const NPVariant *args,
                                     uint32_t argCount, NPVariant *result) const
{
    assertMainThread();
    if (NPNFuncs.invokeDefault != NULL) {
        return NPNFuncs.invokeDefault(m_npp, npobj, args, argCount, result);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::Evaluate(NPObject *npobj, NPString *script,
                                NPVariant *result) const
{
    assertMainThread();
    if (NPNFuncs.evaluate != NULL) {
        return NPNFuncs.evaluate(m_npp, npobj, script, result);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::GetProperty(NPObject *npobj, NPIdentifier propertyName,
                                   NPVariant *result) const
{
    assertMainThread();
    if (NPNFuncs.getproperty != NULL) {
        return NPNFuncs.getproperty(m_npp, npobj, propertyName, result);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::SetProperty(NPObject *npobj, NPIdentifier propertyName,
                                   const NPVariant *value) const
{
    assertMainThread();
    if (NPNFuncs.setproperty != NULL) {
        return NPNFuncs.setproperty(m_npp, npobj, propertyName, value);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::RemoveProperty(NPObject *npobj, NPIdentifier propertyName) const
{
    assertMainThread();
    if (NPNFuncs.removeproperty != NULL) {
        return NPNFuncs.removeproperty(m_npp, npobj, propertyName);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::HasProperty(NPObject *npobj, NPIdentifier propertyName) const
{
    assertMainThread();
    if (NPNFuncs.hasproperty != NULL) {
        return NPNFuncs.hasproperty(m_npp, npobj, propertyName);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::HasMethod(NPObject *npobj, NPIdentifier methodName) const
{
    assertMainThread();
    if (NPNFuncs.hasmethod != NULL) {
        return NPNFuncs.hasmethod(m_npp, npobj, methodName);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::Enumerate(NPObject *npobj, NPIdentifier **identifier,
                                 uint32_t *count) const
{
    assertMainThread();
    if (NPNFuncs.enumerate != NULL) {
        return NPNFuncs.enumerate(m_npp, npobj, identifier, count);
    } else {
        return false;
    }
}

bool NpapiBrowserHost::Construct(NPObject *npobj, const NPVariant *args,
                                 uint32_t argCount, NPVariant *result) const
{
    assertMainThread();
    if (NPNFuncs.construct != NULL) {
        return NPNFuncs.construct(m_npp, npobj, args, argCount, result);
    } else {
        return false;
    }
}

void NpapiBrowserHost::SetException(NPObject *npobj, const NPUTF8 *message) const
{
    assertMainThread();
    if (NPNFuncs.setexception != NULL) {
        NPNFuncs.setexception(npobj, message);
    }
}

int NpapiBrowserHost::ScheduleTimer(int interval, bool repeat, void(*func)(NPP npp, uint32_t timerID)) const
{
    if(NPNFuncs.scheduletimer != NULL) {
        return NPNFuncs.scheduletimer(m_npp, interval, repeat, func);
    } else {
        return 0;
    }
}

void NpapiBrowserHost::UnscheduleTimer(int timerId)  const
{
    if(NPNFuncs.unscheduletimer != NULL) {
        NPNFuncs.unscheduletimer(m_npp, timerId);
    }
}

NPError FB::Npapi::NpapiBrowserHost::GetValueForURL( NPNURLVariable variable, const char *url, char **value, uint32_t *len )
{
    if(NPNFuncs.getvalueforurl != NULL) {
        return NPNFuncs.getvalueforurl(m_npp, variable, url, value, len);
    } else {
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
    }
}

NPError FB::Npapi::NpapiBrowserHost::SetValueForURL( NPNURLVariable variable, const char *url, const char *value, uint32_t len )
{
    if(NPNFuncs.setvalueforurl != NULL) {
        return NPNFuncs.setvalueforurl(m_npp, variable, url, value, len);
    } else {
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
    }
}

NPError FB::Npapi::NpapiBrowserHost::GetAuthenticationInfo( const char *protocol,
                                                            const char *host, int32_t port,
                                                            const char *scheme, const char *realm,
                                                            char **username, uint32_t *ulen,
                                                            char **password, uint32_t *plen )
{
    if(NPNFuncs.getauthenticationinfo != NULL) {
        return NPNFuncs.getauthenticationinfo(m_npp, protocol, host, port, scheme, realm,
                                              username, ulen, password, plen);
    } else {
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
    }
}

FB::BrowserStreamPtr NpapiBrowserHost::_createStream(const std::string& url, const FB::PluginEventSinkPtr& callback,
                                    bool cache, bool seekable, size_t internalBufferSize ) const
{
    NpapiStreamPtr stream( boost::make_shared<NpapiStream>( url, cache, seekable, internalBufferSize, FB::ptr_cast<const NpapiBrowserHost>(shared_from_this()) ) );
    stream->AttachObserver( callback );

    // always use target = 0 for now
    if ( GetURLNotify( url.c_str(), 0, stream.get() ) == NPERR_NO_ERROR )
    {
        stream->setCreated();
        StreamCreatedEvent ev(stream.get());
        stream->SendEvent( &ev );
    }
    else
    {
        stream.reset();
    }
    return stream;
}

FB::BrowserStreamPtr NpapiBrowserHost::_createPostStream(const std::string& url, const FB::PluginEventSinkPtr& callback,
                                    const std::string& postdata, bool cache, bool seekable, size_t internalBufferSize ) const
{
    NpapiStreamPtr stream( boost::make_shared<NpapiStream>( url, cache, seekable, internalBufferSize, FB::ptr_cast<const NpapiBrowserHost>(shared_from_this()) ) );
    stream->AttachObserver( callback );

    // Add custom headers before data to post!
    std::stringstream headers;
    headers << "Content-type: application/x-www-form-urlencoded\n";
    headers << "Content-Length: " << postdata.length() << "\n\n";
    headers << postdata;

    // always use target = 0 for now
    if ( PostURLNotify( url.c_str(), 0, headers.str().length(), headers.str().c_str(), false, stream.get() ) == NPERR_NO_ERROR )
    {
        stream->setCreated();
        StreamCreatedEvent ev(stream.get());
        stream->SendEvent( &ev );
    }
    else
    {
        stream.reset();
    }
    return stream;
}
NPJavascriptObject* FB::Npapi::NpapiBrowserHost::getJSAPIWrapper( const FB::JSAPIWeakPtr& api, bool autoRelease/* = false*/ )
{
    assertMainThread(); // This should only be called on the main thread
    typedef boost::shared_ptr<FB::ShareableReference<NPJavascriptObject> > SharedNPObjectRef;
    NPJavascriptObject* ret(NULL);
    FB::JSAPIPtr ptr(api.lock());
    if (!ptr)
        return NPJavascriptObject::NewObject(FB::ptr_cast<NpapiBrowserHost>(shared_from_this()), api, false);

    NPObjectRefMap::iterator fnd = m_cachedNPObject.find(ptr.get());
    if (fnd != m_cachedNPObject.end()) {
        SharedNPObjectRef ref(fnd->second.lock());
        if (ref) {
            // Fortunately this doesn't have to be threadsafe since this method only gets called
            // from the main thread and the browser access happens on that thread as well!
            ret = ref->getPtr();
            RetainObject(ret);
        } else {
            m_cachedNPObject.erase(fnd);
        }
    }
    if (!ret) {
        ret = NPJavascriptObject::NewObject(FB::ptr_cast<NpapiBrowserHost>(shared_from_this()), api, true);
        if (ret)
            m_cachedNPObject[ptr.get()] = ret->getWeakReference();
    }
    return ret;
}

bool FB::Npapi::NpapiBrowserHost::DetectProxySettings( std::map<std::string, std::string>& settingsMap, const std::string& URL )
{
    char* retVal;
    uint32_t len;
    NPError err = GetValueForURL(NPNURLVProxy, URL.c_str(), &retVal, &len);
    if (err != NPERR_NO_ERROR) {
        // Only fall back to system proxy detection if NPAPI's API isn't supported on this browser
        if (err == NPERR_INCOMPATIBLE_VERSION_ERROR)
            return FB::BrowserHost::DetectProxySettings(settingsMap, URL);
        else
            return false;
    }
    std::string res(retVal, len);
    MemFree(retVal);

    if (res == "DIRECT") {
        return false;
    } else {
        settingsMap.clear();
        vector<string> params;
        split(params, res, is_any_of(" "));
        vector<string> host;
        split(host, params[1], is_any_of(":"));
        if (params[0] == "PROXY") {
            FB::URI uri = FB::URI::fromString(URL);
            settingsMap["type"] = uri.protocol;
        } else if(params[0] == "SOCKS") {
            settingsMap["type"] = "socks";
        } else {
            settingsMap["type"] = params[0];
        }
        settingsMap["hostname"] = host[0];
        settingsMap["port"] = host[1];
        return true;
    }
}

void FB::Npapi::NpapiBrowserHost::Navigate( const std::string& url, const std::string& target )
{
    PushPopupsEnabledState(true);
    GetURL(url.c_str(), target.c_str());
    PopPopupsEnabledState();
}

max_stars_repo_name: Faham/bric-n-brac

max_issues_repo_name: Faham/bric-n-brac

max_forks_repo_name: Faham/bric-n-brac


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "ConnectionStatistics.h"

#include "Basics/Mutex.h"
#include "Basics/MutexLocker.h"
#include "Rest/CommonDefines.h"

#include <thread>
#include <vector>

#include <boost/lockfree/queue.hpp>

using namespace arangodb;

// -----------------------------------------------------------------------------
// --SECTION--                                                  global variables
// -----------------------------------------------------------------------------

namespace {
// initial amount of empty statistics items to be created in statisticsItems
constexpr size_t kInitialQueueSize = 32;

// protects statisticsItems
Mutex statisticsMutex;

// a container of ConnectionStatistics objects. the vector is populated
// initially with kInitialQueueSize items. It can grow at runtime. The addresses
// of objects in the vector can be stored in freeList, so the objects must not
// be destroyed if they are still in the free list. access to statisticsItems
// must be protected by statisticsMutex
std::vector<std::unique_ptr<ConnectionStatistics>> statisticsItems;

// a free list of ConnectionStatistics objects, not owning them. the free list
// is initially populated with kInitialQueueSize objects.
static boost::lockfree::queue<ConnectionStatistics*> freeList;

bool enqueueItem(ConnectionStatistics* item) noexcept {
  int tries = 0;

  try {
    do {
      bool ok = freeList.push(item);
      if (ok) {
        return true;
      }
      std::this_thread::yield();
    } while (++tries < 1000);
  } catch (...) {
  }

  TRI_ASSERT(false);
  // if for whatever reason the push operation fails, we will
  // have a ConnectionStatistics object in statisticsItems
  // that is not in the queue anymore. this item will be
  // allocated at program end normally, but it becomes useless
  // until then. this should be a very rare case though.
  // each ConnectionStatistics object 24 bytes big.

  return false;
}

}  // namespace

// -----------------------------------------------------------------------------
// --SECTION--                                             static public methods
// -----------------------------------------------------------------------------

void ConnectionStatistics::Item::SET_HTTP() {
  if (_stat != nullptr) {
    _stat->_http = true;

    statistics::HttpConnections.incCounter();
  }
}

void ConnectionStatistics::initialize() {
  MUTEX_LOCKER(guard, ::statisticsMutex);

  ::freeList.reserve(kInitialQueueSize * 2);

  ::statisticsItems.reserve(kInitialQueueSize);
  for (size_t i = 0; i < kInitialQueueSize; ++i) {
    // create a new ConnectionStatistics object on the heap
    ::statisticsItems.emplace_back(std::make_unique<ConnectionStatistics>());
    // add its address to the freelist
    bool ok = ::enqueueItem(::statisticsItems.back().get());
    if (!ok) {
      // for some reason we couldn't push the item to the queue. so there
      // is no further use for it.
      ::statisticsItems.pop_back();
    }
  }
}

ConnectionStatistics::Item ConnectionStatistics::acquire() noexcept {
  ConnectionStatistics* statistics = nullptr;

  // try the happy path first
  if (!::freeList.pop(statistics)) {
    // didn't have any items on the free list. now try the
    // expensive path
    try {
      auto cs = std::make_unique<ConnectionStatistics>();
      // store pointer for just-created item
      statistics = cs.get();

      MUTEX_LOCKER(guard, ::statisticsMutex);
      ::statisticsItems.emplace_back(std::move(cs));
    } catch (...) {
      statistics = nullptr;
    }
  }

  return Item{statistics};
}

void ConnectionStatistics::release() noexcept {
  if (_http) {
    statistics::HttpConnections.decCounter();
  }

  if (_connStart != 0.0 && _connEnd != 0.0) {
    double totalTime = _connEnd - _connStart;
    statistics::ConnectionTimeDistribution.addFigure(totalTime);
  }

  // clear statistics
  reset();

  // put statistics item back onto the freelist
  enqueueItem(this);
}

void ConnectionStatistics::getSnapshot(Snapshot& snapshot) {
  snapshot.httpConnections = statistics::HttpConnections;
  snapshot.totalRequests = statistics::TotalRequests;
  snapshot.totalRequestsSuperuser = statistics::TotalRequestsSuperuser;
  snapshot.totalRequestsUser = statistics::TotalRequestsUser;
  snapshot.methodRequests = statistics::MethodRequests;
  snapshot.asyncRequests = statistics::AsyncRequests;
  snapshot.connectionTime = statistics::ConnectionTimeDistribution;
}

ext: cpp


text:
/*
 * Copyright 2013 Open Source Robotics Foundation
 *
 * 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.
 *
*/

#include <gtest/gtest.h>
#include <boost/filesystem.hpp>

#include "gazebo/common/Exception.hh"
#include "gazebo/common/LogRecord.hh"

/////////////////////////////////////////////////
/// \brief Test LogRecord constructor and a few accessors
TEST(LogRecord_TEST, Constructor)
{
  gazebo::common::LogRecord *recorder = gazebo::common::LogRecord::Instance();

  char *homePath = getenv("HOME");
  EXPECT_TRUE(homePath != NULL);

  boost::filesystem::path logPath = "/tmp/gazebo";
  if (homePath)
    logPath = boost::filesystem::path(homePath);
  logPath /= "/.gazebo/log/";

  // Make sure the log path is correct
  EXPECT_EQ(recorder->GetBasePath(), logPath.string());

  EXPECT_FALSE(recorder->GetPaused());
  EXPECT_FALSE(recorder->GetRunning());
  EXPECT_TRUE(recorder->GetFirstUpdate());

  // Init without a subdirectory
  EXPECT_FALSE(recorder->Init(""));
}

/////////////////////////////////////////////////
/// \brief Test LogRecord Start errors
TEST(LogRecord_TEST, StartErrors)
{
  gazebo::common::LogRecord *recorder = gazebo::common::LogRecord::Instance();

  // Start without an init
  {
    EXPECT_FALSE(recorder->Start("bz2"));
  }

  // Invalid encoding
  {
    EXPECT_TRUE(recorder->Init("test"));
    EXPECT_THROW(recorder->Start("garbage"), gazebo::common::Exception);
  }

  // Double start
  {
    EXPECT_TRUE(recorder->Start("bz2"));
    EXPECT_TRUE(recorder->GetRunning());
    EXPECT_FALSE(recorder->Start("bz2"));
  }
}

/////////////////////////////////////////////////
/// \brief Test LogRecord Init and Start
TEST(LogRecord_TEST, Start)
{
  gazebo::common::LogRecord *recorder = gazebo::common::LogRecord::Instance();
  recorder->Init("test");
  recorder->Start("bz2");

  // Make sure the right flags have been set
  EXPECT_FALSE(recorder->GetPaused());
  EXPECT_TRUE(recorder->GetRunning());
  EXPECT_TRUE(recorder->GetFirstUpdate());

  // Make sure the right encoding is set
  EXPECT_EQ(recorder->GetEncoding(), std::string("bz2"));

  // Make sure the log directories exist
  EXPECT_TRUE(boost::filesystem::exists(recorder->GetBasePath()));
  EXPECT_TRUE(boost::filesystem::is_directory(recorder->GetBasePath()));

  // Run time should be zero since no update has been triggered.
  EXPECT_EQ(recorder->GetRunTime(), gazebo::common::Time());

  // Stop recording.
  recorder->Stop();

  // Make sure everything has reset.
  EXPECT_FALSE(recorder->GetRunning());
  EXPECT_FALSE(recorder->GetPaused());
  EXPECT_EQ(recorder->GetRunTime(), gazebo::common::Time());
}

/////////////////////////////////////////////////
int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

ext: cc

max_stars_repo_name: thomas-moulard/gazebo-deb

max_issues_repo_name: thomas-moulard/gazebo-deb

max_forks_repo_name: thomas-moulard/gazebo-deb


text: #include <boost/shared_container_iterator.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG, www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also tools/license/license.mtl.txt in the distribution.

#ifndef MTL_VEC_EXP_INCLUDE
#define MTL_VEC_EXP_INCLUDE

#include <boost/numeric/mtl/vector/map_view.hpp>
#include <boost/numeric/mtl/matrix/map_view.hpp>

namespace mtl {

    namespace vec {

	/// Exponential of \a v element-wise
	template <typename Vector>
	exp_view<Vector> exp(const Vector& v)
	{
	    return exp_view<Vector>(v);
	}

#      ifdef MTL_WITH_MATH_ELEVEN
	/// Binary exponential of \a v element-wise
	template <typename Vector>
	exp2_view<Vector> exp2(const Vector& v)
	{
	    return exp2_view<Vector>(v);
	}
#      endif

	/// Decimal exponential of \a v element-wise
	template <typename Vector>
	exp10_view<Vector> exp10(const Vector& v)
	{
	    return exp10_view<Vector>(v);
	}

    } // namespace vec

    namespace mat {

	/// Exponential of \a A element-wise
	template <typename Matrix>
	exp_view<Matrix> exp(const Matrix& A)
	{
	    return exp_view<Matrix>(A);
	}

    } // namespace mat

} // namespace mtl

#endif // MTL_VEC_EXP_INCLUDE


text:
#include <boost/python.hpp>
#include <iostream>
#include <frameobject.h>
#include "mymodule.hpp"

using namespace boost::python;

int main(int argc, char** argv)
{
	try {
		Py_Initialize();
		PyImport_AppendInittab((char*)"mymodule", initmymodule);
		object main_module = import("__main__");
		dict main_namespace = extract<dict>(main_module.attr("__dict__"));
		object mymodule = import("mymodule");

		main_namespace["precreated_object"] = Base("created on C++ side");
		exec_file("embedding.py", main_namespace, main_namespace);
	} catch (error_already_set& e) {
		PyErr_PrintEx(0);
		return 1;
	}
	return 0;
}

max_stars_repo_name: MrNiebieski/boost-python-test

max_issues_repo_name: MrNiebieski/boost-python-test

max_forks_repo_name: MrNiebieski/boost-python-test


text:
/*
 *             Copyright Andrey Semashev 2018.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   handles_abi.cpp
 * \author Andrey Semashev
 * \date   10.03.2018
 *
 * \brief  This file contains ABI test for handles.hpp
 */

#include <boost/winapi/handles.hpp>
#include <windows.h>
#include "abi_test_tools.hpp"

int main()
{
    BOOST_WINAPI_TEST_CONSTANT(DUPLICATE_CLOSE_SOURCE);
    BOOST_WINAPI_TEST_CONSTANT(DUPLICATE_SAME_ACCESS);
    BOOST_WINAPI_TEST_CONSTANT(INVALID_HANDLE_VALUE);

    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(CloseHandle);
    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(DuplicateHandle);

#if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN10
    BOOST_WINAPI_TEST_FUNCTION_SIGNATURE(CompareObjectHandles);
#endif

    return boost::report_errors();
}

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text: #include <boost/geometry/strategies/geographic/distance.hpp>


text:
#include <boost/python.hpp>
#include <stdexcept>
#include <stddef.h>
#include <string>
#include "nifty_iterator.hxx"
#include "inf_def_visitor.hxx"
#include "lp_def_suite.hxx"
#include "export_typedes.hxx"

#include <opengm/inference/lp_inference.hxx>
#include <param/lp_inference_param.hxx>

#ifdef WITH_CPLEX
#include <opengm/inference/auxiliary/lp_solver/lp_solver_cplex.hxx>
#endif

#ifdef WITH_GUROBI
#include <opengm/inference/auxiliary/lp_solver/lp_solver_gurobi.hxx>
#endif

// export function
template<class GM, class ACC>
void export_lp_inference() {

   import_array();
   using namespace boost::python;
   std::string srName = semiRingName  <typename GM::OperatorType,ACC >() ;

   #ifdef WITH_CPLEX
   {
      append_subnamespace("solver");

      // setup
      InfSetup setup;
      setup.algType    = "linear-programming";
      setup.guarantees = "global optimal";
      setup.examples   = ">>> parameter = opengm.InfParam(integerConstraint=True)\n\n"
                         ">>> inference = opengm.inference.LpCplex2(gm=gm,accumulator='minimizer',parameter=parameter)\n\n"
                         "\n\n";
      setup.dependencies = "This algorithm needs the IBM CPLEX Optimizer, compile OpenGM with CMake-Flag ``WITH_CPLEX`` set to ``ON`` ";
      // export parameter
      typedef typename GM::ValueType ValueType;
      typedef typename GM::IndexType IndexType;

      typedef opengm::LpSolverCplex LpSolver;
      typedef opengm::LPInference<GM, opengm::Minimizer,LpSolver>    PyLPSolver;

      const std::string enumName1=std::string("_LpCplex2Relaxation")+srName;
      enum_<typename PyLPSolver::Relaxation> (enumName1.c_str())
         .value("firstOrder",  PyLPSolver::FirstOrder)
         .value("firstOrder2",   PyLPSolver::FirstOrder2)
      ;

      exportInfParam<PyLPSolver>("_LpCplex2");
      // export inference
      class_< PyLPSolver>("_LpCplex2",init<const GM & >())
      .def(InfSuite<PyLPSolver,false,true,false>(std::string("LpCplex2"),setup))
      .def(LpInferenceSuite<PyLPSolver>())
      ;

   }
   #endif

   #ifdef WITH_GUROBI
   {
      append_subnamespace("solver");

      // setup
      InfSetup setup;
      setup.algType    = "linear-programming";
      setup.guarantees = "global optimal";
      setup.examples   = ">>> parameter = opengm.InfParam(integerConstraint=True)\n\n"
                         ">>> inference = opengm.inference.LpGurobi(gm=gm,accumulator='minimizer',parameter=parameter)\n\n"
                         "\n\n";
      setup.dependencies = "This algorithm needs the Gurobi Optimizer, compile OpenGM with CMake-Flag ``WITH_GUROBI`` set to ``ON`` ";
      // export parameter
      typedef typename GM::ValueType ValueType;
      typedef typename GM::IndexType IndexType;

      typedef opengm::LpSolverGurobi LpSolver;
      typedef opengm::LPInference<GM, opengm::Minimizer,LpSolver>    PyLPSolver;

      const std::string enumName1=std::string("_LpGurobiRelaxation")+srName;
      enum_<typename PyLPSolver::Relaxation> (enumName1.c_str())
         .value("firstOrder",  PyLPSolver::FirstOrder)
         .value("firstOrder2",   PyLPSolver::FirstOrder2)
      ;

      exportInfParam<PyLPSolver>("_LpGurobi");
      // export inference
      class_< PyLPSolver>("_LpGurobi",init<const GM & >())
      .def(InfSuite<PyLPSolver,false,true,false>(std::string("LpGurobi"),setup))
      .def(LpInferenceSuite<PyLPSolver>())
      ;

   }
   #endif

}
// explicit template instantiation for the supported semi-rings
template void export_lp_inference<opengm::python::GmAdder, opengm::Minimizer>();

ext: cxx

max_stars_repo_name: burcin/opengm

max_issues_repo_name: burcin/opengm

max_forks_repo_name: burcin/opengm


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2014-2017, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Licensed under the Boost Software License version 1.0.
// http://www.boost.org/users/license.html

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_POLYGON_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_POLYGON_HPP

#include <cstddef>
#ifdef BOOST_GEOMETRY_TEST_DEBUG
#include <iostream>
#endif // BOOST_GEOMETRY_TEST_DEBUG

#include <algorithm>
#include <deque>
#include <iterator>
#include <set>
#include <vector>

#include <boost/core/ignore_unused.hpp>
#include <boost/range.hpp>

#include <boost/geometry/core/assert.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/tags.hpp>

#include <boost/geometry/util/condition.hpp>
#include <boost/geometry/util/range.hpp>

#include <boost/geometry/geometries/box.hpp>

#include <boost/geometry/iterators/point_iterator.hpp>

#include <boost/geometry/algorithms/covered_by.hpp>
#include <boost/geometry/algorithms/disjoint.hpp>
#include <boost/geometry/algorithms/expand.hpp>
#include <boost/geometry/algorithms/num_interior_rings.hpp>
#include <boost/geometry/algorithms/validity_failure_type.hpp>
#include <boost/geometry/algorithms/within.hpp>

#include <boost/geometry/algorithms/detail/check_iterator_range.hpp>
#include <boost/geometry/algorithms/detail/partition.hpp>

#include <boost/geometry/algorithms/detail/is_valid/complement_graph.hpp>
#include <boost/geometry/algorithms/detail/is_valid/has_valid_self_turns.hpp>
#include <boost/geometry/algorithms/detail/is_valid/is_acceptable_turn.hpp>
#include <boost/geometry/algorithms/detail/is_valid/ring.hpp>

#include <boost/geometry/algorithms/detail/is_valid/debug_print_turns.hpp>
#include <boost/geometry/algorithms/detail/is_valid/debug_validity_phase.hpp>
#include <boost/geometry/algorithms/detail/is_valid/debug_complement_graph.hpp>

#include <boost/geometry/algorithms/dispatch/is_valid.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace is_valid
{

template <typename Polygon, bool CheckRingValidityOnly = false>
class is_valid_polygon
{
protected:
    typedef debug_validity_phase<Polygon> debug_phase;

    template <typename VisitPolicy, typename Strategy>
    struct per_ring
    {
        per_ring(VisitPolicy& policy, Strategy const& strategy)
            : m_policy(policy)
            , m_strategy(strategy)
        {}

        template <typename Ring>
        inline bool apply(Ring const& ring) const
        {
            return detail::is_valid::is_valid_ring
                <
                    Ring, false, true
                >::apply(ring, m_policy, m_strategy);
        }

        VisitPolicy& m_policy;
        Strategy const& m_strategy;
    };

    template <typename InteriorRings, typename VisitPolicy, typename Strategy>
    static bool has_valid_interior_rings(InteriorRings const& interior_rings,
                                         VisitPolicy& visitor,
                                         Strategy const& strategy)
    {
        return
            detail::check_iterator_range
                <
                    per_ring<VisitPolicy, Strategy>,
                    true // allow for empty interior ring range
                >::apply(boost::begin(interior_rings),
                         boost::end(interior_rings),
                         per_ring<VisitPolicy, Strategy>(visitor, strategy));
    }

    struct has_valid_rings
    {
        template <typename VisitPolicy, typename Strategy>
        static inline bool apply(Polygon const& polygon,
                                 VisitPolicy& visitor,
                                 Strategy const& strategy)
        {
            typedef typename ring_type<Polygon>::type ring_type;

            // check validity of exterior ring
            debug_phase::apply(1);

            if (! detail::is_valid::is_valid_ring
                     <
                         ring_type,
                         false // do not check self intersections
                     >::apply(exterior_ring(polygon), visitor, strategy))
            {
                return false;
            }

            // check validity of interior rings
            debug_phase::apply(2);

            return has_valid_interior_rings(geometry::interior_rings(polygon),
                                            visitor,
                                            strategy);
        }
    };

    // structs for partition -- start
    struct expand_box
    {
        template <typename Box, typename Iterator>
        static inline void apply(Box& total, Iterator const& it)
        {
            geometry::expand(total, geometry::return_envelope<Box>(*it));
        }

    };

    struct overlaps_box
    {
        template <typename Box, typename Iterator>
        static inline bool apply(Box const& box, Iterator const& it)
        {
            return ! geometry::disjoint(*it, box);
        }
    };

    struct item_visitor_type
    {
        bool items_overlap;

        item_visitor_type() : items_overlap(false) {}

        template <typename Item1, typename Item2>
        inline void apply(Item1 const& item1, Item2 const& item2)
        {
            if (! items_overlap
                && (geometry::within(*points_begin(*item1), *item2)
                    || geometry::within(*points_begin(*item2), *item1))
                )
            {
                items_overlap = true;
            }
        }
    };
    // structs for partition -- end

    template
    <
        typename RingIterator,
        typename ExteriorRing,
        typename TurnIterator,
        typename VisitPolicy
    >
    static inline bool are_holes_inside(RingIterator rings_first,
                                        RingIterator rings_beyond,
                                        ExteriorRing const& exterior_ring,
                                        TurnIterator turns_first,
                                        TurnIterator turns_beyond,
                                        VisitPolicy& visitor)
    {
        boost::ignore_unused(visitor);

        // collect the interior ring indices that have turns with the
        // exterior ring
        std::set<signed_size_type> ring_indices;
        for (TurnIterator tit = turns_first; tit != turns_beyond; ++tit)
        {
            if (tit->operations[0].seg_id.ring_index == -1)
            {
                BOOST_GEOMETRY_ASSERT(tit->operations[1].seg_id.ring_index != -1);
                ring_indices.insert(tit->operations[1].seg_id.ring_index);
            }
            else if (tit->operations[1].seg_id.ring_index == -1)
            {
                BOOST_GEOMETRY_ASSERT(tit->operations[0].seg_id.ring_index != -1);
                ring_indices.insert(tit->operations[0].seg_id.ring_index);
            }
        }

        signed_size_type ring_index = 0;
        for (RingIterator it = rings_first; it != rings_beyond;
             ++it, ++ring_index)
        {
            // do not examine interior rings that have turns with the
            // exterior ring
            if (ring_indices.find(ring_index) == ring_indices.end()
                && ! geometry::covered_by(range::front(*it), exterior_ring))
            {
                return visitor.template apply<failure_interior_rings_outside>();
            }
        }

        // collect all rings (exterior and/or interior) that have turns
        for (TurnIterator tit = turns_first; tit != turns_beyond; ++tit)
        {
            ring_indices.insert(tit->operations[0].seg_id.ring_index);
            ring_indices.insert(tit->operations[1].seg_id.ring_index);
        }

        // put iterators for interior rings without turns in a vector
        std::vector<RingIterator> ring_iterators;
        ring_index = 0;
        for (RingIterator it = rings_first; it != rings_beyond;
             ++it, ++ring_index)
        {
            if (ring_indices.find(ring_index) == ring_indices.end())
            {
                ring_iterators.push_back(it);
            }
        }

        // call partition to check is interior rings are disjoint from
        // each other
        item_visitor_type item_visitor;

        geometry::partition
            <
                geometry::model::box<typename point_type<Polygon>::type>
            >::apply(ring_iterators, item_visitor, expand_box(), overlaps_box());

        if (item_visitor.items_overlap)
        {
            return visitor.template apply<failure_nested_interior_rings>();
        }
        else
        {
            return visitor.template apply<no_failure>();
        }
    }

    template
    <
        typename InteriorRings,
        typename ExteriorRing,
        typename TurnIterator,
        typename VisitPolicy
    >
    static inline bool are_holes_inside(InteriorRings const& interior_rings,
                                        ExteriorRing const& exterior_ring,
                                        TurnIterator first,
                                        TurnIterator beyond,
                                        VisitPolicy& visitor)
    {
        return are_holes_inside(boost::begin(interior_rings),
                                boost::end(interior_rings),
                                exterior_ring,
                                first,
                                beyond,
                                visitor);
    }

    struct has_holes_inside
    {
        template <typename TurnIterator, typename VisitPolicy>
        static inline bool apply(Polygon const& polygon,
                                 TurnIterator first,
                                 TurnIterator beyond,
                                 VisitPolicy& visitor)
        {
            return are_holes_inside(geometry::interior_rings(polygon),
                                    geometry::exterior_ring(polygon),
                                    first,
                                    beyond,
                                    visitor);
        }
    };

    struct has_connected_interior
    {
        template <typename TurnIterator, typename VisitPolicy>
        static inline bool apply(Polygon const& polygon,
                                 TurnIterator first,
                                 TurnIterator beyond,
                                 VisitPolicy& visitor)
        {
            boost::ignore_unused(visitor);

            typedef typename std::iterator_traits
                <
                    TurnIterator
                >::value_type turn_type;
            typedef complement_graph<typename turn_type::point_type> graph;

            graph g(geometry::num_interior_rings(polygon) + 1);
            for (TurnIterator tit = first; tit != beyond; ++tit)
            {
                typename graph::vertex_handle v1 = g.add_vertex
                    ( tit->operations[0].seg_id.ring_index + 1 );
                typename graph::vertex_handle v2 = g.add_vertex
                    ( tit->operations[1].seg_id.ring_index + 1 );
                typename graph::vertex_handle vip = g.add_vertex(tit->point);

                g.add_edge(v1, vip);
                g.add_edge(v2, vip);
            }

#ifdef BOOST_GEOMETRY_TEST_DEBUG
            debug_print_complement_graph(std::cout, g);
#endif // BOOST_GEOMETRY_TEST_DEBUG

            if (g.has_cycles())
            {
                return visitor.template apply<failure_disconnected_interior>();
            }
            else
            {
                return visitor.template apply<no_failure>();
            }
        }
    };

public:
    template <typename VisitPolicy, typename Strategy>
    static inline bool apply(Polygon const& polygon,
                             VisitPolicy& visitor,
                             Strategy const& strategy)
    {
        if (! has_valid_rings::apply(polygon, visitor, strategy))
        {
            return false;
        }

        if (BOOST_GEOMETRY_CONDITION(CheckRingValidityOnly))
        {
            return true;
        }

        // compute turns and check if all are acceptable
        debug_phase::apply(3);

        typedef has_valid_self_turns<Polygon> has_valid_turns;

        std::deque<typename has_valid_turns::turn_type> turns;
        bool has_invalid_turns
            = ! has_valid_turns::apply(polygon, turns, visitor, strategy);
        debug_print_turns(turns.begin(), turns.end());

        if (has_invalid_turns)
        {
            return false;
        }

        // check if all interior rings are inside the exterior ring
        debug_phase::apply(4);

        if (! has_holes_inside::apply(polygon,
                                      turns.begin(), turns.end(),
                                      visitor))
        {
            return false;
        }

        // check whether the interior of the polygon is a connected set
        debug_phase::apply(5);

        return has_connected_interior::apply(polygon,
                                             turns.begin(),
                                             turns.end(),
                                             visitor);
    }
};

}} // namespace detail::is_valid
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

// A Polygon is always a simple geometric object provided that it is valid.
//
// Reference (for validity of Polygons): OGC 06-103r4 (6.1.11.1)
template <typename Polygon, bool AllowEmptyMultiGeometries>
struct is_valid
    <
        Polygon, polygon_tag, AllowEmptyMultiGeometries
    > : detail::is_valid::is_valid_polygon<Polygon>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_IS_VALID_POLYGON_HPP


text:
#include "simer_omp.h"
#include <boost/algorithm/string.hpp>
#include <bigmemory/BigMatrix.h>
#include <bigmemory/MatrixAccessor.hpp>

// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::depends(bigmemory, BH)]]
using namespace std;
using namespace Rcpp;

template <typename T>
bool hasNA(XPtr<BigMatrix> pMat, double NA_C, const int threads=0) {

  omp_setup(threads);
  size_t m = pMat->nrow();
  size_t n = pMat->ncol();
  bool HasNA = false;

  MatrixAccessor<T> mat = MatrixAccessor<T>(*pMat);
  #pragma omp parallel for schedule(dynamic) shared(HasNA)
  for (size_t j = 0; j < n; j++) {
    if(HasNA)   continue;
    for (size_t i = 0; i < m; i++) {
      if (mat[j][i] == NA_C) {
        HasNA = true;
      }
    }
  }
  return HasNA;
}

// [[Rcpp::export]]
bool hasNA(SEXP pBigMat, const int threads=0) {
  XPtr<BigMatrix> xpMat(pBigMat);

  switch(xpMat->matrix_type()) {
  case 1:
    return hasNA<char>(xpMat, NA_CHAR, threads);
  case 2:
    return hasNA<short>(xpMat, NA_SHORT, threads);
  case 4:
    return hasNA<int>(xpMat, NA_INTEGER, threads);
  case 8:
    return hasNA<double>(xpMat, NA_REAL, threads);
  default:
    throw Rcpp::exception("unknown type detected for big.matrix object!");
  }
}

// [[Rcpp::export]]
bool hasNABed(std::string bed_file, int ind, long maxLine, int threads=0, bool verbose=true) {
  // check input
  if (!boost::ends_with(bed_file, ".bed")) {
    bed_file += ".bed";
  }

  // define
  omp_setup(threads);
  long n = ind / 4;  // 4 individual = 1 bit
  if (ind % 4 != 0)
    n++;
  char *buffer;
  long buffer_size;
  bool HasNA = false;

  // open file
  FILE *fin;
  fin = fopen(bed_file.c_str(), "rb");
  fseek(fin, 0, SEEK_END);
  long length = ftell(fin);
  rewind(fin);

  // get buffer_size
  buffer_size = maxLine > 0 ? (maxLine * n) : (length - 3);

  // progress bar
  int n_block = (length - 3) / buffer_size;
  if ((length - 3) % buffer_size != 0) { n_block++; }

  // magic number of bfile
  buffer = new char [3];
  size_t n_bytes_read = static_cast<size_t>(fread(buffer, 1, 3, fin));

  // loop file
  size_t cond;
  long block_start;
  for (int i = 0; i < n_block; i++) {
    buffer = new char [buffer_size];
    n_bytes_read = static_cast<size_t>(fread(buffer, 1, buffer_size, fin));

    // i: current block, j: current bit.
    block_start = i * buffer_size;
    cond = min(buffer_size, length - 3 - block_start);
    #pragma omp parallel for schedule(static)
    for (size_t j = 0; j < cond; j++) {
      // bit -> item in matrix
      size_t r = (block_start + j) / n;
      size_t c = (block_start + j) % n * 4;
      uint8_t p = buffer[j];
      if (HasNA) continue;
      for (size_t x = 0; x < 4 && (c + x) < ind; x++) {
        if (1 == ((p >> (2*x)) & 0x03)) {
          HasNA = true;
          break;
        }
      }
    }
  }
  fclose(fin);

  return HasNA;
}

max_stars_repo_name: xiaolei-lab/SIMER

max_issues_repo_name: xiaolei-lab/SIMER

max_forks_repo_name: xiaolei-lab/SIMER


text:
#include "tikpp/tests/fakes/socket.hpp"
#include "tikpp/tests/fixtures/socket.hpp"

#include "tikpp/detail/operations/async_read_word.hpp"
#include "tikpp/request.hpp"

#include "fmt/format.h"
#include "gtest/gtest.h"
#include <boost/asio/buffer.hpp>
#include <boost/asio/write.hpp>

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>

namespace tikpp::tests {

struct AsyncReadWordLengthTest : tikpp::tests::fixtures::SocketTest {};

TEST_F(AsyncReadWordLengthTest, WordTest) {
    static constexpr auto test_iterations    = 100;
    static constexpr auto test_string_format = "test_string_{:X}";

    static auto make_test_str = [](auto format) {
        return fmt::format(format, rand());
    };

    std::vector<std::uint8_t> buf {};
    std::time_t               start_seed {std::time(nullptr)};
    std::srand(start_seed);

    for (std::size_t i {0}; i < test_iterations; ++i) {
        tikpp::detail::encode_word(make_test_str(test_string_format), buf);
    }

    boost::asio::write(sock.input_pipe(), boost::asio::buffer(buf));
    std::srand(start_seed);

    for (std::size_t i {0}; i < test_iterations; ++i) {
        tikpp::detail::operations::async_read_word(
            sock, [](const auto &err, auto &&word) {
                EXPECT_FALSE(err);
                ASSERT_EQ(word, make_test_str(test_string_format));
            });
    }

    io.run();
}

} // namespace tikpp::tests

max_stars_repo_name: aymanalqadhi/tikpp


text: #include <boost/units/static_rational.hpp>


text:
/********************************
 FileName: executor/lxc.cpp
 Version:  0.1
 Description: lxc(Linux Container), inherit from vm
*********************************/

#include <iostream>
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
//#include <sys/unistd.h>
//#include <dirent.h>
#include <fcntl.h> // for func open
//#include <time.h>
//#include <signal.h>

#include <boost/algorithm/string.hpp>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <gflags/gflags.h>

#include "lxc/lxc.h"
#include "lxc/conf.h"

#include "common/clynn/string_utility.h"
#include "common/lxc/confile.h"
#include "executor/hdfs_wrapper.h"
#include "include/proxy.h"
#include "executor/system.h"
#include "executor/lxc.h"
#include "executor/task_entity_pool.h"
#include "executor/resource_manager.h"

using std::cout;
using std::endl;
using std::stringstream;
using std::ifstream;
using std::ofstream;
using boost::trim;
using log4cplus::Logger;
using clynn::WriteLocker;
using clynn::ReadLocker;

DECLARE_string(lxc_dir);
DECLARE_string(lxc_template);
DECLARE_bool(lxc_create);
DECLARE_bool(lxc_relative_path);

static Logger logger = Logger::getInstance("executor");

static const double DEFAULT_CPU_SHARE = 1.0;

string LXC::m_conf_template = "";

/// @brief: public function
// virtual function, from VM
// virtual CreateEnv, include ..
int32_t LXC::Execute() {
    if (CreateVM() != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to create lxc, name:" << GetName() << ", job_id:" << GetID().job_id << ", task_id:" << GetID().task_id);
        return -1;
    }

    if (InstallApp() != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to install app, lxc name:" << GetName() << ", job_id:" << GetID().job_id << ", task_id:" << GetID().task_id);
        return -1;
    }

    if (LXC::StartApp() != 0){
        LOG4CPLUS_ERROR(logger, "Failed to start app, lxc name:" << GetName() << ", job_id:" << GetID().job_id << ", task_id:" << GetID().task_id);
        return -1;
    }

    return 0;

}

int32_t LXC::CreateVM() {
    if (CreateLXC() != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to create lxc, name:" << GetName() << ", job_id:" << GetID().job_id << ", task_id:" << GetID().task_id);
        return -1;
    }
    return 0;
}

// install app from hdfs
int32_t LXC::InstallApp() {
    if (!HDFSMgrI::Instance()->CopyToLocalFile(GetTaskInfo().app_info.app_src_path, m_dir)) {
        LOG4CPLUS_ERROR(logger, "Failed to install app, from hdfs:" << GetTaskInfo().app_info.app_src_path  << ", to local fs:" << m_dir);
        return -1;
    }
    return 0;
}

// execute the task, run the app
int32_t LXC::StartApp() {
    if (ExecuteLXC() != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to execute lxc, name:" << GetName() << ", job_id:" << GetID().job_id << ", task_id:" << GetID().task_id);
        return -1;
    }
    return 0;
}

bool LXC::Stop() {
    //
    string cmd = "lxc-stop -n " + GetName();
    int32_t ret = system(cmd.c_str());
    ret = ret >> 8;
    if (ret != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to stop lxc, name:" << GetName());
        return false;
    }
    return true;
}

bool LXC::Kill() {
    string cmd_stop = "lxc-stop -n " + GetName();
    int32_t ret_stop = system(cmd_stop.c_str());
    ret_stop = ret_stop >> 8;
    if (ret_stop != 0) {
        LOG4CPLUS_ERROR(logger, "Failed to stop lxc, name:" << GetName());
        return false;
    }


text:
#ifndef G2O_TARGET_TYPES_3D_HPP_
#define G2O_TARGET_TYPES_3D_HPP_

#include <g2o/core/base_unary_edge.h>
#include <g2o/core/base_vertex.h>

#include <Eigen/Core>

// This header file specifies a set of types for the different
// tracking examples; note that

class VertexPosition3D : public g2o::BaseVertex<3, Eigen::Vector3d> {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  VertexPosition3D() {}

  virtual void setToOriginImpl() { _estimate.setZero(); }

  virtual void oplusImpl(const double* update) {
    _estimate[0] += update[0];
    _estimate[1] += update[1];
    _estimate[2] += update[2];
  }

  virtual bool read(std::istream& /*is*/) { return false; }

  virtual bool write(std::ostream& /*os*/) const { return false; }
};

// Store velocity separately from position?
class VertexVelocity3D : public g2o::BaseVertex<3, Eigen::Vector3d> {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  VertexVelocity3D() {}

  virtual void setToOriginImpl() { _estimate.setZero(); }

  virtual void oplusImpl(const double* update) {
    _estimate[0] += update[0];
    _estimate[1] += update[1];
    _estimate[2] += update[2];
  }

  virtual bool read(std::istream& /*is*/) { return false; }

  virtual bool write(std::ostream& /*os*/) const { return false; }
};

// The idealised GPS measurement; this is 3D and linear
class GPSObservationPosition3DEdge
    : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPosition3D> {
 public:
  GPSObservationPosition3DEdge() {}

  void computeError() {
    const VertexPosition3D* v =
        static_cast<const VertexPosition3D*>(_vertices[0]);
    _error = v->estimate() - _measurement;
  }

  virtual bool read(std::istream& /*is*/) { return false; }

  virtual bool write(std::ostream& /*os*/) const { return false; }
};

#endif  //  __TARGET_TYPES_3D_HPP__


text:
/*! \file       test_ringbuf.cpp
 *  \brief      Circular buffer data structure testing suite
 *  \author     Brian Reece
 *  \version    v0.3-alpha
 *  \date       01/01/2022
 */

#define BOOST_TEST_MODULE test_ringbuf

#include <string.h>

#include <boost/test/included/unit_test.hpp>

extern "C" {
#define restrict    /** nothing **/
#define STRUCTS_DEF /** nothing **/
#include "structs/error.h"
#include "structs/ringbuf.h"
}

struct ringbuf_empty_fixture {
    ringbuf_empty_fixture() {
        ringbuf = ringbuf_init(sizeof(int), 5);
        BOOST_TEST(ringbuf.elements);
        BOOST_TEST(ringbuf.head == 0);
        BOOST_TEST(ringbuf.tail == 0);
        BOOST_TEST(ringbuf.length == 0);
        BOOST_TEST(ringbuf.size == sizeof(int));
        BOOST_TEST(ringbuf.capacity == 5);
    }

    ~ringbuf_empty_fixture() {
        BOOST_TEST_REQUIRE(ringbuf_deinit(&ringbuf) == ERR_NONE);
    }

    ringbuf_t ringbuf;
};

struct ringbuf_populated_fixture {
    ringbuf_populated_fixture() {
        ringbuf = ringbuf_init(sizeof(int), 5);
        for (int i = 0; i < 5; i++) {
            BOOST_TEST_REQUIRE(ringbuf_write(&ringbuf, (void *)&i) == ERR_NONE);
        }
    }

    ~ringbuf_populated_fixture() {
        BOOST_TEST_REQUIRE(ringbuf_deinit(&ringbuf) == ERR_NONE);
    }

    ringbuf_t ringbuf;
};

/*! \test       test_ringbuf/empty_ops
 *  \brief      Circular buffer empty operations test suite
 *  \details    Asserts proper behavior in error throwing upon
 *              reads from empty circular buffer
 */
BOOST_FIXTURE_TEST_SUITE(empty_ops, ringbuf_empty_fixture)

BOOST_AUTO_TEST_CASE(empty_read) {
    int value;

    BOOST_TEST(ringbuf_read(&ringbuf, (void *)&value) == ERR_EMPTY);
}

BOOST_AUTO_TEST_CASE(empty_get) {
    int value;

    BOOST_TEST(ringbuf_get(&ringbuf, (void *)&value) == ERR_EMPTY);
}

BOOST_AUTO_TEST_CASE(empty_getp) {
    int *value;

    BOOST_TEST(ringbuf_getp(&ringbuf, (void **)&value) == ERR_EMPTY);
}

BOOST_AUTO_TEST_SUITE_END()

/*! \test       test_ringbuf/addition_ops
 *  \brief      Circular buffer addition operations testing suite
 *  \details    Asserts proper behavior in execution of write
 *              operations.
 */
BOOST_AUTO_TEST_SUITE(addition_ops)

BOOST_FIXTURE_TEST_CASE(write_five_elements, ringbuf_empty_fixture) {
    const int values[5] = {1, 2, 3, 4, 5};

    for (long i = 0; i < 5; i++) {
        BOOST_TEST(ringbuf_write(&ringbuf, (const void *)&values[i]) ==
                   ERR_NONE);
        BOOST_TEST(*((int *)ringbuf.elements + i) == i + 1);
        BOOST_TEST(ringbuf_length(&ringbuf) == i + 1);
    }

    BOOST_TEST(ringbuf.head == 0);
    BOOST_TEST(ringbuf.tail == 0);
}

BOOST_AUTO_TEST_SUITE_END()

/*! \test       test_ringbuf/subtraction_ops
 *  \brief      Circular buffer subtraction operations testing suite
 *  \details    Asserts proper behavior in execution of read, clear,
 *              and get operations.
 */
BOOST_AUTO_TEST_SUITE(subtraction_ops)

BOOST_FIXTURE_TEST_CASE(read_five_elements, ringbuf_populated_fixture) {
    int values[5];

    for (long i = 0; i < 5; i++) {
        BOOST_TEST(ringbuf_read(&ringbuf, (void *)&values[i]) == ERR_NONE);
        BOOST_TEST(values[i] == i);
    }

    BOOST_TEST(ringbuf.head == 0);
    BOOST_TEST(ringbuf.tail == 0);
    BOOST_TEST(ringbuf_length(&ringbuf) == 0);
}

BOOST_FIXTURE_TEST_CASE(get_five_elements, ringbuf_populated_fixture) {
    int values[5];

    for (long i = 0; i < 5; i++) {
        BOOST_TEST(ringbuf_get(&ringbuf, (void *)&values[i]) == ERR_NONE);
        BOOST_TEST(values[i] == 0);
    }

    BOOST_TEST(ringbuf.head == 0);
    BOOST_TEST(ringbuf.tail == 0);
    BOOST_TEST(ringbuf_length(&ringbuf) == 5);
}

BOOST_FIXTURE_TEST_CASE(getp_five_elements, ringbuf_populated_fixture) {
    int *values[5];

    for (long i = 0; i < 5; i++) {
        BOOST_TEST(ringbuf_getp(&ringbuf, (void **)&values[i]) == ERR_NONE);
        BOOST_TEST(*values[i] == 0);
    }

    BOOST_TEST(ringbuf.head == 0);
    BOOST_TEST(ringbuf.tail == 0);
    BOOST_TEST(ringbuf_length(&ringbuf) == 5);
}

BOOST_FIXTURE_TEST_CASE(clear_five_elements, ringbuf_populated_fixture) {
    BOOST_TEST(ringbuf_clear(&ringbuf) == ERR_NONE);
    BOOST_TEST(ringbuf.head == 0);
    BOOST_TEST(ringbuf.tail == 0);
    BOOST_TEST(ringbuf_length(&ringbuf) == 0);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: bdreece/libstructs

max_issues_repo_name: bdreece/libstructs

max_forks_repo_name: bdreece/libstructs


text:
// vim: awa:sts=4:ts=4:sw=4:et:cin:fdm=manual:tw=120:ft=cpp
#include "common/assertion/include/assertion.h"
#include "common/assertion/include/throw.h"
#include "common/include/logging.h"
#include "common/include/source_location.h"

#include <exception>
#include <string>

#include <backward.hpp>
#include <boost/core/demangle.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/get_error_info.hpp>
#include <fmt/format.h>
#include <fmt/ostream.h>

using namespace std;
using namespace std::literals;
using mmotd::source_location::SourceLocation;

namespace {

SourceLocation GetExceptionLocation(const boost::exception &ex) noexcept {
    const auto *file_thrown = boost::get_error_info<boost::throw_file>(ex);
    const auto *function_thrown = boost::get_error_info<boost::throw_function>(ex);
    const auto *line_thrown = boost::get_error_info<boost::throw_line>(ex);
    if (file_thrown != nullptr && function_thrown != nullptr && line_thrown != nullptr) {
        return SourceLocation{*file_thrown, *function_thrown, *line_thrown, long{0}};
    } else {
        return SourceLocation{nullptr, nullptr, long{0}, long{0}};
    }
}

string GetExceptionBacktrace(const boost::exception &ex) noexcept {
    const auto *backtrace_thrown = boost::get_error_info<mmotd::assertion::throw_stack_trace>(ex);
    return backtrace_thrown != nullptr ? string{*backtrace_thrown} : string{};
}

string GetExceptionStr(const std::exception &ex) {
    if (const auto *what_msg = ex.what(); what_msg != nullptr) {
        return string{what_msg};
    } else {
        return boost::core::demangle(typeid(ex).name());
    }
}

bool ContainsBacktrace(const string &msg) {
    return msg.find("Stack trace (most recent call last):") != string::npos;
}

bool ContainsSourceLocation(const string &msg) {
    auto source_location = mmotd::source_location::from_string(msg, " at ", "\\n");
    return !empty(source_location);
}

string CreateExceptionMessage(const boost::exception &ex, const std::exception &std_ex) {
    auto msg = fmt::format(FMT_STRING("{}"), std::quoted(GetExceptionStr(std_ex)));
    if (!ContainsSourceLocation(msg)) {
        if (auto throw_location = GetExceptionLocation(ex); !throw_location.empty()) {
            msg += " at "s + to_string(throw_location);
        }
    }
    if (!ContainsBacktrace(msg)) {
        if (auto throw_backtrace = GetExceptionBacktrace(ex); !empty(throw_backtrace)) {
            return msg + "\n"s + throw_backtrace;
        }
    }
    return msg;
}

string CreateExceptionMessage(const std::exception &ex) {
    return GetExceptionStr(ex);
}

string CreateExceptionMessage() {
#if defined(__GLIBCXX__)
    if (auto *info = std::current_exception().__cxa_exception_type(); info != nullptr) {
        return string{boost::core::demangle(info->name())};
    }
#endif
    return "<unknown exception>"s;
}

string GetBoostExceptionMessageImpl(const boost::exception &ex,
                                    std::string_view context,
                                    const SourceLocation &source_location) {
    const auto *std_ex = dynamic_cast<const std::exception *>(&ex);
    CHECKS(std_ex != nullptr, "impossible, all boost::exceptions must inherit from std::exception");
    auto exception_msg = CreateExceptionMessage(ex, *std_ex);
    auto function_name = mmotd::source_location::function_name_to_string(source_location);
    if (empty(context)) {
        return fmt::format(FMT_STRING("caught boost::exception in {}: {}"), function_name, exception_msg);
    } else {
        return fmt::format(FMT_STRING("caught boost::exception {} in {}: {}"), context, function_name, exception_msg);
    }
}

string
GetStdExceptionMessageImpl(const std::exception &ex, std::string_view context, const SourceLocation &source_location) {
    const auto *boost_ex = dynamic_cast<const boost::exception *>(&ex);
    // CHECKS(boost_ex != nullptr, "yeah that's possible, someone didn't use the ThrowException mechanism");
    auto exception_msg = string{};
    if (boost_ex != nullptr) {
        exception_msg = CreateExceptionMessage(*boost_ex, ex);
    } else {
        exception_msg = CreateExceptionMessage(ex);
    }
    auto function_name = mmotd::source_location::function_name_to_string(source_location);
    if (empty(context)) {
        return fmt::format(FMT_STRING("caught std::exception in {}: {}"), function_name, exception_msg);
    } else {
        return fmt::format(FMT_STRING("caught std::exception {} in {}: {}"), context, function_name, exception_msg);
    }
}

string GetUnknownExceptionMessageImpl(std::string_view context, const SourceLocation &source_location) {
    auto exception_type = CreateExceptionMessage();
    auto function_name = mmotd::source_location::function_name_to_string(source_location);
    if (empty(context)) {
        return fmt::format(FMT_STRING("caught unknown exception in {}: {}"), function_name, exception_type);
    } else {
        return fmt::format(FMT_STRING("caught unknown exception {} in {}: {}"), context, function_name, exception_type);
    }
}

} // namespace

namespace mmotd::assertion {

string GetBoostExceptionMessage(const boost::exception &ex,
                                std::string_view context,
                                const SourceLocation &source_location) noexcept {
    try {
        return GetBoostExceptionMessageImpl(ex, context, source_location);
    } catch (...) { return string{}; }
}

string GetStdExceptionMessage(const std::exception &ex,
                              std::string_view context,
                              const SourceLocation &source_location) noexcept {
    try {
        return GetStdExceptionMessageImpl(ex, context, source_location);
    } catch (...) { return string{}; }
}

string GetUnknownExceptionMessage(std::string_view context, const SourceLocation &source_location) noexcept {
    try {
        return GetUnknownExceptionMessageImpl(context, source_location);
    } catch (...) { return string{}; }
}

} // namespace mmotd::assertion

max_stars_repo_name: jasonivey/mmotd

max_issues_repo_name: jasonivey/mmotd

max_forks_repo_name: jasonivey/mmotd


text:
#include <boost/test/unit_test.hpp>

#include "base/bytes.hpp"
#include "base/hash.hpp"

#include <memory>

BOOST_AUTO_TEST_CASE(bytes_storage_check)
{
    base::Bytes bytes(128);
    for (std::size_t i = 0; i < bytes.size(); ++i) {
        bytes[i] = static_cast<base::Byte>(i ^ 3);
    }

    bool all_equal = true;
    for (std::size_t i = 0; i < bytes.size(); ++i) {
        all_equal = all_equal && (static_cast<base::Byte>(i ^ 3) == bytes[i]);
    }

    BOOST_CHECK(all_equal);
}

BOOST_AUTO_TEST_CASE(bytes_constructor_from_array_of_chars)
{
    std::size_t length = 10;
    base::Bytes tmp;
    for (std::size_t i = 0; i < length; i++) {
        tmp.append(static_cast<base::Byte>(i ^ 3));
    }
    auto c_str = tmp.getData();
    base::Bytes bytes(c_str, length);

    BOOST_CHECK(bytes.size() == length);
    bool res = true;
    for (std::size_t i = 0; i < length; i++) {
        res = res && (bytes[i] == c_str[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(bytes_constructor_from_array_of_chars_dynamic)
{
    std::size_t length = 11;
    std::unique_ptr<base::Byte[]> c_str = std::make_unique<base::Byte[]>(length);
    for (std::size_t i = 0; i < length; i++) {
        c_str[i] = static_cast<base::Byte>(i ^ 3);
    }
    base::Bytes bytes(c_str.get(), length);

    BOOST_CHECK(bytes.size() == length);
    bool res = true;
    for (std::size_t i = 0; i < length; i++) {
        res = res && (bytes[i] == c_str[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(bytes_string_ctor)
{
    base::Bytes b1{ 0x4c, 0x49, 0x4b, 0x45, 0x4c, 0x49, 0x42, 0x9, 0x32, 0x2e, 0x30, 0x02 };
    base::Bytes b2("LIKELIB\t2.0\x02");
    BOOST_CHECK(b1 == b2);
}

BOOST_AUTO_TEST_CASE(bytes_size_change)
{
    base::Bytes bytes(128);
    for (std::size_t i = 0; i < bytes.size(); ++i) {
        bytes[i] = static_cast<base::Byte>(i ^ 33);
    }
    bytes.append(0x15);
    BOOST_CHECK_EQUAL(bytes.size(), 129);
    BOOST_CHECK_EQUAL(bytes[bytes.size() - 1], 0x15);
}

BOOST_AUTO_TEST_CASE(bytes_take_part)
{
    base::Bytes bytes(128);
    for (std::size_t i = 0; i < bytes.size(); ++i) {
        bytes[i] = static_cast<base::Byte>(i ^ 12);
    }

    base::Bytes answer;
    for (std::size_t i = 20; i < 30; ++i) {
        answer.append(static_cast<base::Byte>(i ^ 12));
    }

    base::Bytes part = bytes.takePart(20, 30);
    BOOST_CHECK(part == answer);
    BOOST_CHECK(!(part != answer));
}

BOOST_AUTO_TEST_CASE(bytes_take_part_one_symbol)
{
    base::Bytes bytes("eeeaaabbb");
    base::Bytes part = bytes.takePart(7, 8);

    BOOST_CHECK(part.toString() == "b");
}

BOOST_AUTO_TEST_CASE(bytes_append1)
{
    base::Bytes bytes1(234);
    for (std::size_t i = 0; i < bytes1.size(); ++i) {
        bytes1[i] = static_cast<base::Byte>(i ^ 11);
    }

    base::Bytes bytes2(175);
    for (std::size_t i = 0; i < bytes2.size(); ++i) {
        bytes2[i] = static_cast<base::Byte>(i ^ 13);
    }

    base::Bytes bytes_concat;
    bytes_concat.append(bytes1);
    BOOST_CHECK(bytes_concat.size() == bytes1.size());

    bool res = true;
    for (std::size_t i = 0; i < bytes1.size(); ++i) {
        res = res && (bytes_concat[i] == bytes1[i]);
    }
    BOOST_CHECK(res);

    bytes_concat.append(bytes2);
    BOOST_CHECK(bytes_concat.size() == bytes1.size() + bytes2.size());

    res = true;
    for (std::size_t i = 0; i < bytes2.size(); ++i) {
        res = res && (bytes_concat[bytes1.size() + i] == bytes2[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(bytes_append2)
{
    base::Bytes bytes1(333);
    for (std::size_t i = 0; i < bytes1.size(); ++i) {
        bytes1[i] = static_cast<base::Byte>(i ^ 11);
    }

    base::Bytes bytes2(200);
    for (std::size_t i = 0; i < bytes2.size(); i++) {
        bytes2[i] = static_cast<base::Byte>(i ^ 13);
    }

    base::Bytes bytes_concat;
    bytes_concat.append(bytes1);
    std::size_t count_to_concat = bytes2.size() / 2;
    bytes_concat.append(bytes2.getData(), count_to_concat);
    BOOST_CHECK(bytes_concat.size() == bytes1.size() + count_to_concat);

    bool res = true;
    for (std::size_t i = 0; i < bytes1.size(); ++i) {
        res = res && (bytes_concat[i] == bytes1[i]);
    }
    BOOST_CHECK(res);

    res = true;
    for (std::size_t i = 0; i < count_to_concat; ++i) {
        res = res && (bytes_concat[i + bytes1.size()] == bytes2[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(bytes_intializer_list_constructor)
{
    base::Bytes bytes{ 0x1, 0xFF, 0x2, 0xFE };
    BOOST_CHECK_EQUAL(bytes.size(), 4);
    BOOST_CHECK_EQUAL(bytes[0], 0x1);
    BOOST_CHECK_EQUAL(bytes[1], 0xFF);
    BOOST_CHECK_EQUAL(bytes[2], 0x2);
    BOOST_CHECK_EQUAL(bytes[3], 0xFE);
}

BOOST_AUTO_TEST_CASE(bytes_to_hex)
{
    base::Bytes bytes{ 0x01, 0xFF, 0x02, 0xFE, 0x00 };
    BOOST_CHECK_EQUAL(base::toHex<base::Bytes>(bytes), "01ff02fe00");
}

BOOST_AUTO_TEST_CASE(bytes_to_string)
{
    base::Bytes bytes{ 0x4c, 0x49, 0x4b, 0x45, 0x4c, 0x49, 0x42, 0x9, 0x32, 0x2e, 0x30, 0x02 };
    BOOST_CHECK_EQUAL(bytes.toString(), "LIKELIB\t2.0\x02");
}

BOOST_AUTO_TEST_CASE(bytes_from_hex)
{
    base::Bytes target_bytes{ 0x01, 0xFF, 0x02, 0xFE, 0x00 };
    auto target_hex = "01ff02fe00";
    auto hex_view = base::toHex<base::Bytes>(target_bytes);
    BOOST_CHECK_EQUAL(hex_view, target_hex);

    auto from_hex_bytes = base::fromHex<base::Bytes>(target_hex);
    BOOST_CHECK_EQUAL(from_hex_bytes, target_bytes);
}

BOOST_AUTO_TEST_CASE(fixed_bytes_storage_check)
{
    base::FixedBytes<111> fb1;
    for (std::size_t i = 0; i < fb1.size(); ++i) {
        fb1[i] = static_cast<base::Byte>(i ^ 3);
    }

    bool all_equal = true;
    for (std::size_t i = 0; i < fb1.size(); ++i) {
        all_equal = all_equal && (static_cast<base::Byte>(i ^ 3) == fb1[i]);
    }

    BOOST_CHECK(all_equal);
}

BOOST_AUTO_TEST_CASE(fixed_bytes_constructor_from_array_of_chars)
{
    base::FixedBytes<111> fb1;
    for (std::size_t i = 0; i < fb1.size(); i++) {
        fb1[i] = (static_cast<base::Byte>(i ^ 3));
    }
    auto c_str = fb1.getData();
    base::FixedBytes<111> fb2(c_str, fb1.size());

    BOOST_CHECK(fb2.size() == fb1.size());
    bool res = true;
    for (std::size_t i = 0; i < fb1.size(); i++) {
        res = res && (fb2[i] == c_str[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(fixed_bytes_constructor_from_vector)
{
    std::vector<base::Byte> b(111);
    for (std::size_t i = 0; i < b.size(); i++) {
        b[i] = (static_cast<base::Byte>(i ^ 3));
    }

    base::FixedBytes<111> fb(b);

    BOOST_CHECK(fb.size() == b.size());
    bool res = true;
    for (std::size_t i = 0; i < fb.size(); i++) {
        res = res && (b[i] == fb[i]);
    }
    BOOST_CHECK(res);
}

BOOST_AUTO_TEST_CASE(fixed_bytes_string_ctor)
{
    base::FixedBytes<12> b1{ 0x4c, 0x49, 0x4b, 0x45, 0x4c, 0x49, 0x42, 0x9, 0x32, 0x2e, 0x30, 0x02 };
    base::FixedBytes<12> b2("LIKELIB\t2.0\x02");
    BOOST_CHECK(b1 == b2);
    BOOST_CHECK(b1.toString() == b2.toString());
    BOOST_CHECK(b1.toString() == "LIKELIB\t2.0\x02");
}

BOOST_AUTO_TEST_CASE(fixed_bytes_to_hex)
{
    base::FixedBytes<5> bytes{ 0x01, 0xFF, 0x02, 0xFE, 0x00 };
    BOOST_CHECK_EQUAL(base::toHex<base::FixedBytes<5>>(bytes), "01ff02fe00");
}

BOOST_AUTO_TEST_CASE(fixed_bytes_serializatin)
{
    base::FixedBytes<6> fb1{ "Fiasko" };
    base::SerializationOArchive oa;

    oa.serialize(fb1);
    base::SerializationIArchive ia(oa.getBytes());
    auto fb2 = ia.deserialize<base::FixedBytes<6>>();

    BOOST_CHECK(fb1 == fb2);
}

BOOST_AUTO_TEST_CASE(base64_encode_decode)
{
    base::Bytes target_msg("dFM#69356^#-04  @#4-0^\n\n4#0632=-GEJ3dls5s,spi+-5+0");
    auto base64 = base64Encode(target_msg);
    auto decode_base64 = base::base64Decode(base64);

    BOOST_CHECK(base64 == "ZEZNIzY5MzU2XiMtMDQgIEAjNC0wXgoKNCMwNjMyPS1HRUozZGxzNXMsc3BpKy01KzA=");
    BOOST_CHECK(target_msg == decode_base64);
}

BOOST_AUTO_TEST_CASE(base64_encode_fixed_bytes)
{
    base::FixedBytes<50> target_msg("dFM#69356^#-04  @#4-0^\n\n4#0632=-GEJ3dls5s,spi+-5+0");
    auto base64 = base64Encode(target_msg);
    auto decode_base64 = base::base64Decode(base64);

    BOOST_CHECK(base64 == "ZEZNIzY5MzU2XiMtMDQgIEAjNC0wXgoKNCMwNjMyPS1HRUozZGxzNXMsc3BpKy01KzA=");
    BOOST_CHECK(target_msg.toString() == decode_base64.toString());
}

BOOST_AUTO_TEST_CASE(base64_encode_decode_empty)
{
    base::Bytes target_msg("");
    auto base64 = base64Encode(target_msg);
    auto decode_base64 = base::base64Decode(base64);

    BOOST_CHECK(base64 == "");
    BOOST_CHECK(target_msg == decode_base64);
}

BOOST_AUTO_TEST_CASE(base64_encode_decode_one_byte)
{
    base::Bytes target_msg("1");
    auto base64 = base64Encode(target_msg);
    auto decode_base64 = base::base64Decode(base64);

    BOOST_CHECK(base64 == "MQ==");
    BOOST_CHECK(target_msg == decode_base64);
}

BOOST_AUTO_TEST_CASE(base64_encode_fixed_bytes_one_byte)
{
    base::FixedBytes<1> target_msg("1");
    auto base64 = base64Encode(target_msg);
    auto decode_base64 = base::base64Decode(base64);

    BOOST_CHECK(base64 == "MQ==");
    BOOST_CHECK(target_msg.toString() == decode_base64.toString());
}

BOOST_AUTO_TEST_CASE(base58_encode_decode)
{
    base::Bytes target_msg("dFM#69356^#-04  @#4-0^\n\n4#0632=-GEJ3dls5s,spi+-5+0");
    auto base58 = base::base58Encode(target_msg);
    auto decode_base58 = base::base58Decode(base58);
    BOOST_CHECK(base58 == "2EfFY3oougxD9wQVN97fY9zmUuz3dEFnxDzbG8Xga34ArAY8nvx9hhsdtaUYze8CiDABR");
    BOOST_CHECK(decode_base58 == target_msg);
}

BOOST_AUTO_TEST_CASE(base58_encode_fixed_bytes)
{
    base::FixedBytes<50> target_msg("dFM#69356^#-04  @#4-0^\n\n4#0632=-GEJ3dls5s,spi+-5+0");
    auto base58 = base::base58Encode(target_msg);
    auto decode_base58 = base::base58Decode(base58);
    BOOST_CHECK(base58 == "2EfFY3oougxD9wQVN97fY9zmUuz3dEFnxDzbG8Xga34ArAY8nvx9hhsdtaUYze8CiDABR");
    BOOST_CHECK(decode_base58.toString() == target_msg.toString());
}

BOOST_AUTO_TEST_CASE(base58_encode_decode_empty)
{
    base::Bytes target_msg("");
    auto base64 = base58Encode(target_msg);
    auto decode_base64 = base::base58Decode(base64);

    BOOST_CHECK(base64 == "");
    BOOST_CHECK(target_msg == decode_base64);
}

max_stars_repo_name: heshu-by/likelib-ws

max_issues_repo_name: heshu-by/likelib-ws

max_forks_repo_name: heshu-by/likelib-ws