<commit_before>
#include "ofxAppWxWindow.h"
#include <assert.h>

#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "ofBaseApp.h"
#include "ofEvents.h"
#include "ofUtils.h"
#include "ofGraphics.h"
#include "ofAppRunner.h"
#include "ofConstants.h"
#include "ofxWxGLCanvas.h"

#ifndef _WIN32
#ifdef __MACH__
#include <GLUT/GLUT.h>
#else
#include <GL/glut.h>
#endif
#endif

//----------------------------------------------------------
ofxAppWxWindow::ofxAppWxWindow(wxWindow *glCanvasParent)
{
   windowMode			= OF_WINDOW;
   nFramesSinceWindowResized = 0;
   bEnableSetupScreen = true;
   ofAppPtr          = NULL;
   glCanvas          = NULL;
   glCanvasSizer     = NULL;
   glCanvasParentWnd = glCanvasParent;
   topParent         = NULL;
   if(glCanvasParentWnd != NULL)
   {
      topParent = dynamic_cast<wxFrame *>(::wxGetTopLevelParent(glCanvasParentWnd));
   }
}

//------------------------------------------------------------
ofxAppWxWindow::~ofxAppWxWindow()
{
    //! @note wx frame will delete it's childrend when destroy is called.
    destroy();
}

//------------------------------------------------------------
void ofxAppWxWindow::destroy()
{
    //glCanvas->DoEnable(false);
    glCanvas->Destroy();
}

//------------------------------------------------------------
void ofxAppWxWindow::setDoubleBuffering(bool _bDoubleBuffered)
{

}

//------------------------------------------------------------
void ofxAppWxWindow::setupOpenGL(int w, int h, int screenMode)
{
    if(glCanvas != NULL)
    {
        glCanvas->Destroy();
        glCanvas = NULL;
    }

    if((glCanvas == NULL) && (this->glCanvasParentWnd != NULL))
    {
#if defined(TARGET_WIN32) && (WINVER == 0x0701)
        //! @see http://wiki.wxwidgets.org/WxGLCanvas#Multiple_wxGLCanvases
        //! @note Reparent hack that seems necessary on Windoze 7 at the time of testing.
        wxFrame *frame = new wxFrame(NULL, wxID_ANY, wxT("Hack")); //! @note Not supposed to make a frame on the stack.  Mem should be cleaned when frame is destroyed.
        assert(frame != NULL);
        glCanvas = new ofxWxGLCanvas(frame, w, h);
        assert(glCanvas != NULL);
        frame->Show();
        glCanvas->SetCurrent(*this->glCanvas->GetGLContex());
        glCanvas->Reparent(this->glCanvasParentWnd);
        frame->Close();
        frame->Destroy();
        frame = NULL;
#else
        glCanvas = new ofxWxGLCanvas(this->glCanvasParentWnd, w, h);
        assert(glCanvas != NULL);
        glCanvas->SetCurrent(*this->glCanvas->GetGLContex());
#if defined(TARGET_LINUX)
        static bool glutInitialized = false;
        if (!glutInitialized)
        {
          char *myargv [1];
          int myargc=1;
          myargv [0]=strdup ("ofxAppWxWindow");
          glutInit(&myargc, myargv);
        }
#endif

#endif
        // Add sizer.
        this->glCanvasSizer = new wxBoxSizer(wxVERTICAL);
        assert(this->glCanvasSizer != NULL);
        glCanvasSizer->Add(this->glCanvas, 1, wxEXPAND | wxGROW | wxALL, 0);
        this->glCanvasParentWnd->SetSizer(this->glCanvasSizer);
    }// end if
}

//------------------------------------------------------------
void ofxAppWxWindow::initializeWindow()
{
   nFramesSinceWindowResized = 0;

   ofRectangle viewport;
   viewport.x = 0;
   viewport.y = 0;
   viewport.width  = glCanvas->GetClientSize().x;
   viewport.height = glCanvas->GetClientSize().y;

   ofViewport(viewport);
   ofSetupScreen();
   ofFill();
   ofSetColor(220);
}

//------------------------------------------------------------
void ofxAppWxWindow::runAppViaInfiniteLoop(ofBaseApp * appPtr)
{
	ofAppPtr = appPtr;

	ofNotifySetup();
	ofNotifyUpdate();
}

//------------------------------------------------------------
float ofxAppWxWindow::getFrameRate()
{
	return glCanvas->getFrameRate();
}

//------------------------------------------------------------
double ofxAppWxWindow::getLastFrameTime()
{
	return glCanvas->getLastFrameTime();
}

//------------------------------------------------------------
int ofxAppWxWindow::getFrameNum()
{
	return glCanvas->getFrameCount();
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowTitle(string title)
{
    if(topParent != NULL)
    {
        topParent->SetTitle(title);
    }
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getWindowSize()
{
    wxSize size(glCanvas->GetClientSize());
    return ofPoint(size.x, size.y, 0);
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getWindowPosition()
{
    wxRect rect(glCanvas->GetClientRect());
    return ofPoint(rect.x, rect.y, 0);
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getScreenSize()
{
	wxSize size(glCanvas->GetClientSize());
    return ofPoint(size.x, size.y, 0);
}

//------------------------------------------------------------
int ofxAppWxWindow::getWidth()
{
   ofOrientation orientation = glCanvas->GetOrientation();
   if(orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180)
   {
      return ofGetViewportWidth();
   }
   return ofGetViewportHeight();
}

//------------------------------------------------------------
int ofxAppWxWindow::getHeight()
{
   ofOrientation orientation = glCanvas->GetOrientation();
   if(orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180)
   {
      return ofGetViewportHeight();
   }
   return ofGetViewportWidth();
}

//------------------------------------------------------------
void ofxAppWxWindow::setOrientation(ofOrientation orientationIn)
{
	glCanvas->SetOrientation(orientationIn);
}

//------------------------------------------------------------
ofOrientation ofxAppWxWindow::getOrientation()
{
	return glCanvas->GetOrientation();
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowPosition(int x, int y)
{
	wxPoint point(x, y);
    glCanvas->SetPosition(point);
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowShape(int w, int h)
{
    glCanvas->SetClientSize(w, h);
    initializeWindow();
    glCanvas->Fit();
}

//------------------------------------------------------------
void ofxAppWxWindow::hideCursor()
{
    // Does this need to happen when we enter the canvas?
    if (windowMode == OF_FULLSCREEN)
    {
        glCanvas->SetCursor(wxCursor(wxCURSOR_BLANK));
    }
    else
    {
        glCanvas->SetCursor(wxNullCursor);
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::showCursor()
{
    glCanvas->SetCursor(*wxSTANDARD_CURSOR);
}

//------------------------------------------------------------
void ofxAppWxWindow::setFrameRate(float targetRate)
{
    glCanvas->setFrameRate(targetRate);
}

//------------------------------------------------------------
int ofxAppWxWindow::getWindowMode()
{
	return windowMode;
}

//------------------------------------------------------------
void ofxAppWxWindow::toggleFullscreen()
{
	if(windowMode == OF_GAME_MODE)
    {
        return;
    }

	if(windowMode == OF_WINDOW )
    {
		windowMode = OF_FULLSCREEN;
    }
    else
    {
		windowMode = OF_WINDOW;
	}
    if(topParent != NULL)
    {
        topParent->ShowFullScreen(windowMode == OF_FULLSCREEN);
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::setFullscreen(bool fullscreen)
{
    if(windowMode == OF_GAME_MODE)
    {
        return;
    }

    if(topParent != NULL)
    {
        topParent->ShowFullScreen(fullscreen);
    }

    if(fullscreen && windowMode != OF_FULLSCREEN)
    {
        windowMode = OF_FULLSCREEN;
    }
    else if(!fullscreen && windowMode != OF_WINDOW)
    {
        windowMode = OF_WINDOW;
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::enableSetupScreen()
{
	bEnableSetupScreen = true;
}

//------------------------------------------------------------
void ofxAppWxWindow::disableSetupScreen()
{
	bEnableSetupScreen = false;
}
<commit_msg>Set deleted member to NULL.<commit_after>
#include "ofxAppWxWindow.h"
#include <assert.h>

#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#include "ofBaseApp.h"
#include "ofEvents.h"
#include "ofUtils.h"
#include "ofGraphics.h"
#include "ofAppRunner.h"
#include "ofConstants.h"
#include "ofxWxGLCanvas.h"

#ifndef _WIN32
#ifdef __MACH__
#include <GLUT/GLUT.h>
#else
#include <GL/glut.h>
#endif
#endif

//----------------------------------------------------------
ofxAppWxWindow::ofxAppWxWindow(wxWindow *glCanvasParent)
{
   windowMode			= OF_WINDOW;
   nFramesSinceWindowResized = 0;
   bEnableSetupScreen = true;
   ofAppPtr          = NULL;
   glCanvas          = NULL;
   glCanvasSizer     = NULL;
   glCanvasParentWnd = glCanvasParent;
   topParent         = NULL;
   if(glCanvasParentWnd != NULL)
   {
      topParent = dynamic_cast<wxFrame *>(::wxGetTopLevelParent(glCanvasParentWnd));
   }
}

//------------------------------------------------------------
ofxAppWxWindow::~ofxAppWxWindow()
{
    //! @note wx frame will delete it's childrend when destroy is called.
    destroy();
}

//------------------------------------------------------------
void ofxAppWxWindow::destroy()
{
    //glCanvas->DoEnable(false);
    glCanvas->Destroy();
    glCanvas = NULL;
}

//------------------------------------------------------------
void ofxAppWxWindow::setDoubleBuffering(bool _bDoubleBuffered)
{

}

//------------------------------------------------------------
void ofxAppWxWindow::setupOpenGL(int w, int h, int screenMode)
{
    if(glCanvas != NULL)
    {
        glCanvas->Destroy();
        glCanvas = NULL;
    }

    if((glCanvas == NULL) && (this->glCanvasParentWnd != NULL))
    {
#if defined(TARGET_WIN32) && (WINVER == 0x0701)
        //! @see http://wiki.wxwidgets.org/WxGLCanvas#Multiple_wxGLCanvases
        //! @note Reparent hack that seems necessary on Windoze 7 at the time of testing.
        wxFrame *frame = new wxFrame(NULL, wxID_ANY, wxT("Hack")); //! @note Not supposed to make a frame on the stack.  Mem should be cleaned when frame is destroyed.
        assert(frame != NULL);
        glCanvas = new ofxWxGLCanvas(frame, w, h);
        assert(glCanvas != NULL);
        frame->Show();
        glCanvas->SetCurrent(*this->glCanvas->GetGLContex());
        glCanvas->Reparent(this->glCanvasParentWnd);
        frame->Close();
        frame->Destroy();
        frame = NULL;
#else
        glCanvas = new ofxWxGLCanvas(this->glCanvasParentWnd, w, h);
        assert(glCanvas != NULL);
        glCanvas->SetCurrent(*this->glCanvas->GetGLContex());
#if defined(TARGET_LINUX)
        static bool glutInitialized = false;
        if (!glutInitialized)
        {
          char *myargv [1];
          int myargc=1;
          myargv [0]=strdup ("ofxAppWxWindow");
          glutInit(&myargc, myargv);
        }
#endif

#endif
        // Add sizer.
        this->glCanvasSizer = new wxBoxSizer(wxVERTICAL);
        assert(this->glCanvasSizer != NULL);
        glCanvasSizer->Add(this->glCanvas, 1, wxEXPAND | wxGROW | wxALL, 0);
        this->glCanvasParentWnd->SetSizer(this->glCanvasSizer);
    }// end if
}

//------------------------------------------------------------
void ofxAppWxWindow::initializeWindow()
{
   nFramesSinceWindowResized = 0;

   ofRectangle viewport;
   viewport.x = 0;
   viewport.y = 0;
   viewport.width  = glCanvas->GetClientSize().x;
   viewport.height = glCanvas->GetClientSize().y;

   ofViewport(viewport);
   ofSetupScreen();
   ofFill();
   ofSetColor(220);
}

//------------------------------------------------------------
void ofxAppWxWindow::runAppViaInfiniteLoop(ofBaseApp * appPtr)
{
	ofAppPtr = appPtr;

	ofNotifySetup();
	ofNotifyUpdate();
}

//------------------------------------------------------------
float ofxAppWxWindow::getFrameRate()
{
	return glCanvas->getFrameRate();
}

//------------------------------------------------------------
double ofxAppWxWindow::getLastFrameTime()
{
	return glCanvas->getLastFrameTime();
}

//------------------------------------------------------------
int ofxAppWxWindow::getFrameNum()
{
	return glCanvas->getFrameCount();
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowTitle(string title)
{
    if(topParent != NULL)
    {
        topParent->SetTitle(title);
    }
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getWindowSize()
{
    wxSize size(glCanvas->GetClientSize());
    return ofPoint(size.x, size.y, 0);
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getWindowPosition()
{
    wxRect rect(glCanvas->GetClientRect());
    return ofPoint(rect.x, rect.y, 0);
}

//------------------------------------------------------------
ofPoint ofxAppWxWindow::getScreenSize()
{
	wxSize size(glCanvas->GetClientSize());
    return ofPoint(size.x, size.y, 0);
}

//------------------------------------------------------------
int ofxAppWxWindow::getWidth()
{
   ofOrientation orientation = glCanvas->GetOrientation();
   if(orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180)
   {
      return ofGetViewportWidth();
   }
   return ofGetViewportHeight();
}

//------------------------------------------------------------
int ofxAppWxWindow::getHeight()
{
   ofOrientation orientation = glCanvas->GetOrientation();
   if(orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180)
   {
      return ofGetViewportHeight();
   }
   return ofGetViewportWidth();
}

//------------------------------------------------------------
void ofxAppWxWindow::setOrientation(ofOrientation orientationIn)
{
	glCanvas->SetOrientation(orientationIn);
}

//------------------------------------------------------------
ofOrientation ofxAppWxWindow::getOrientation()
{
	return glCanvas->GetOrientation();
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowPosition(int x, int y)
{
	wxPoint point(x, y);
    glCanvas->SetPosition(point);
}

//------------------------------------------------------------
void ofxAppWxWindow::setWindowShape(int w, int h)
{
    glCanvas->SetClientSize(w, h);
    initializeWindow();
    glCanvas->Fit();
}

//------------------------------------------------------------
void ofxAppWxWindow::hideCursor()
{
    // Does this need to happen when we enter the canvas?
    if (windowMode == OF_FULLSCREEN)
    {
        glCanvas->SetCursor(wxCursor(wxCURSOR_BLANK));
    }
    else
    {
        glCanvas->SetCursor(wxNullCursor);
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::showCursor()
{
    glCanvas->SetCursor(*wxSTANDARD_CURSOR);
}

//------------------------------------------------------------
void ofxAppWxWindow::setFrameRate(float targetRate)
{
    glCanvas->setFrameRate(targetRate);
}

//------------------------------------------------------------
int ofxAppWxWindow::getWindowMode()
{
	return windowMode;
}

//------------------------------------------------------------
void ofxAppWxWindow::toggleFullscreen()
{
	if(windowMode == OF_GAME_MODE)
    {
        return;
    }

	if(windowMode == OF_WINDOW )
    {
		windowMode = OF_FULLSCREEN;
    }
    else
    {
		windowMode = OF_WINDOW;
	}
    if(topParent != NULL)
    {
        topParent->ShowFullScreen(windowMode == OF_FULLSCREEN);
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::setFullscreen(bool fullscreen)
{
    if(windowMode == OF_GAME_MODE)
    {
        return;
    }

    if(topParent != NULL)
    {
        topParent->ShowFullScreen(fullscreen);
    }

    if(fullscreen && windowMode != OF_FULLSCREEN)
    {
        windowMode = OF_FULLSCREEN;
    }
    else if(!fullscreen && windowMode != OF_WINDOW)
    {
        windowMode = OF_WINDOW;
    }
}

//------------------------------------------------------------
void ofxAppWxWindow::enableSetupScreen()
{
	bEnableSetupScreen = true;
}

//------------------------------------------------------------
void ofxAppWxWindow::disableSetupScreen()
{
	bEnableSetupScreen = false;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
** Contact: http://www.qt-project.org/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdnslookup_p.h"

#include <QUrl>
#include <QMutex>
#include <QLibrary>

#include <windows.h>
#include <windns.h>

QT_BEGIN_NAMESPACE

static QMutex local_dns_mutex;
typedef DNS_STATUS (*dns_query_utf8_proto)(PCSTR,WORD,DWORD,PIP4_ARRAY,PDNS_RECORD*,PVOID*);
static dns_query_utf8_proto local_dns_query_utf8 = 0;
typedef void (*dns_record_list_free_proto)(PDNS_RECORD,DNS_FREE_TYPE);
static dns_record_list_free_proto local_dns_record_list_free = 0;

static void resolveLibrary()
{
    QLibrary lib(QLatin1String("dnsapi"));
    if (!lib.load())
        return;

    local_dns_query_utf8 = (dns_query_utf8_proto) lib.resolve(QLatin1String("dnsapi"), "DnsQuery_UTF8");
    local_dns_record_list_free = (dns_record_list_free_proto) lib.resolve(QLatin1String("dnsapi"), "DnsRecordListFree");
}

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, QDnsLookupReply *reply)
{
    // Load DnsQuery_UTF8 and DnsRecordListFree on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(&local_dns_mutex);
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If DnsQuery_UTF8 or DnsRecordListFree is missing, fail.
    if (!local_dns_query_utf8 || !local_dns_record_list_free) {
        reply->error = QDnsLookup::ResolverError,
        reply->errorString = tr("Resolver functions not found");
        return;
    }

    // Perform DNS query.
    PDNS_RECORD dns_records;
    const DNS_STATUS status = local_dns_query_utf8(requestName, requestType, DNS_QUERY_STANDARD, NULL, &dns_records, NULL);
    switch (status) {
    case ERROR_SUCCESS:
        break;
    case DNS_ERROR_RCODE_FORMAT_ERROR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case DNS_ERROR_RCODE_SERVER_FAILURE:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case DNS_ERROR_RCODE_NAME_ERROR:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case DNS_ERROR_RCODE_REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = tr("Invalid reply received");
        return;
    }

    // Extract results.
    for (PDNS_RECORD ptr = dns_records; ptr != NULL; ptr = ptr->pNext) {
        const QString name = QUrl::fromAce((char*)ptr->pName);
        if (ptr->wType == QDnsLookup::A) {
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(ntohl(ptr->Data.A.IpAddress));
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::AAAA) {
            Q_IPV6ADDR addr;
            memcpy(&addr, &ptr->Data.AAAA.Ip6Address, sizeof(Q_IPV6ADDR));

            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::CNAME) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Cname.pNameHost);
            reply->canonicalNameRecords.append(record);
        } else if (ptr->wType == QDnsLookup::MX) {
            QDnsMailExchangeRecord record;
            record.d->name = name;
            record.d->exchange = QUrl::fromAce((char*)ptr->Data.Mx.pNameExchange);
            record.d->preference = ptr->Data.Mx.wPreference;
            record.d->timeToLive = ptr->dwTtl;
            reply->mailExchangeRecords.append(record);
        } else if (ptr->wType == QDnsLookup::NS) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Ns.pNameHost);
            reply->nameServerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::PTR) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Ptr.pNameHost);
            reply->pointerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::SRV) {
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce((char*)ptr->Data.Srv.pNameTarget);
            record.d->port = ptr->Data.Srv.wPort;
            record.d->priority = ptr->Data.Srv.wPriority;
            record.d->timeToLive = ptr->dwTtl;
            record.d->weight = ptr->Data.Srv.wWeight;
            reply->serviceRecords.append(record);
        } else if (ptr->wType == QDnsLookup::TXT) {
            QDnsTextRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            for (unsigned int i = 0; i < ptr->Data.Txt.dwStringCount; ++i) {
                record.d->values << QByteArray((char*)ptr->Data.Txt.pStringArray[i]);
            }
            reply->textRecords.append(record);
        }
    }

    local_dns_record_list_free(dns_records, DnsFreeRecordList);
}

QT_END_NAMESPACE
<commit_msg>explicitly include winsock2.h<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
** Contact: http://www.qt-project.org/
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdnslookup_p.h"

#include <QUrl>
#include <QMutex>
#include <QLibrary>

#include <windows.h>
#include <windns.h>
#include <winsock2.h>

QT_BEGIN_NAMESPACE

static QMutex local_dns_mutex;
typedef DNS_STATUS (*dns_query_utf8_proto)(PCSTR,WORD,DWORD,PIP4_ARRAY,PDNS_RECORD*,PVOID*);
static dns_query_utf8_proto local_dns_query_utf8 = 0;
typedef void (*dns_record_list_free_proto)(PDNS_RECORD,DNS_FREE_TYPE);
static dns_record_list_free_proto local_dns_record_list_free = 0;

static void resolveLibrary()
{
    QLibrary lib(QLatin1String("dnsapi"));
    if (!lib.load())
        return;

    local_dns_query_utf8 = (dns_query_utf8_proto) lib.resolve(QLatin1String("dnsapi"), "DnsQuery_UTF8");
    local_dns_record_list_free = (dns_record_list_free_proto) lib.resolve(QLatin1String("dnsapi"), "DnsRecordListFree");
}

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, QDnsLookupReply *reply)
{
    // Load DnsQuery_UTF8 and DnsRecordListFree on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(&local_dns_mutex);
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If DnsQuery_UTF8 or DnsRecordListFree is missing, fail.
    if (!local_dns_query_utf8 || !local_dns_record_list_free) {
        reply->error = QDnsLookup::ResolverError,
        reply->errorString = tr("Resolver functions not found");
        return;
    }

    // Perform DNS query.
    PDNS_RECORD dns_records;
    const DNS_STATUS status = local_dns_query_utf8(requestName, requestType, DNS_QUERY_STANDARD, NULL, &dns_records, NULL);
    switch (status) {
    case ERROR_SUCCESS:
        break;
    case DNS_ERROR_RCODE_FORMAT_ERROR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case DNS_ERROR_RCODE_SERVER_FAILURE:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case DNS_ERROR_RCODE_NAME_ERROR:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case DNS_ERROR_RCODE_REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = tr("Invalid reply received");
        return;
    }

    // Extract results.
    for (PDNS_RECORD ptr = dns_records; ptr != NULL; ptr = ptr->pNext) {
        const QString name = QUrl::fromAce((char*)ptr->pName);
        if (ptr->wType == QDnsLookup::A) {
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(ntohl(ptr->Data.A.IpAddress));
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::AAAA) {
            Q_IPV6ADDR addr;
            memcpy(&addr, &ptr->Data.AAAA.Ip6Address, sizeof(Q_IPV6ADDR));

            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::CNAME) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Cname.pNameHost);
            reply->canonicalNameRecords.append(record);
        } else if (ptr->wType == QDnsLookup::MX) {
            QDnsMailExchangeRecord record;
            record.d->name = name;
            record.d->exchange = QUrl::fromAce((char*)ptr->Data.Mx.pNameExchange);
            record.d->preference = ptr->Data.Mx.wPreference;
            record.d->timeToLive = ptr->dwTtl;
            reply->mailExchangeRecords.append(record);
        } else if (ptr->wType == QDnsLookup::NS) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Ns.pNameHost);
            reply->nameServerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::PTR) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce((char*)ptr->Data.Ptr.pNameHost);
            reply->pointerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::SRV) {
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce((char*)ptr->Data.Srv.pNameTarget);
            record.d->port = ptr->Data.Srv.wPort;
            record.d->priority = ptr->Data.Srv.wPriority;
            record.d->timeToLive = ptr->dwTtl;
            record.d->weight = ptr->Data.Srv.wWeight;
            reply->serviceRecords.append(record);
        } else if (ptr->wType == QDnsLookup::TXT) {
            QDnsTextRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            for (unsigned int i = 0; i < ptr->Data.Txt.dwStringCount; ++i) {
                record.d->values << QByteArray((char*)ptr->Data.Txt.pStringArray[i]);
            }
            reply->textRecords.append(record);
        }
    }

    local_dns_record_list_free(dns_records, DnsFreeRecordList);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>//===--- SILDeclRef.cpp - Implements SILDeclRef ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILDeclRef.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Mangle.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/SILLinkage.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
using namespace swift;

static unsigned getFuncNaturalUncurryLevel(AnyFunctionRef AFR) {
  assert(AFR.getBodyParamPatterns().size() >= 1 && "no arguments for func?!");
  unsigned Level = AFR.getBodyParamPatterns().size() - 1;
  // Functions with captures have an extra uncurry level for the capture
  // context.
  if (AFR.getCaptureInfo().hasLocalCaptures())
    Level += 1;
  return Level;
}

SILDeclRef::SILDeclRef(ValueDecl *vd, SILDeclRef::Kind kind,
                       ResilienceExpansion expansion,
                       unsigned atUncurryLevel, bool isForeign)
  : loc(vd), kind(kind), Expansion(unsigned(expansion)),
    isForeign(isForeign), defaultArgIndex(0)
{
  unsigned naturalUncurryLevel;

  // FIXME: restructure to use a "switch".

  if (auto *func = dyn_cast<FuncDecl>(vd)) {
    assert(kind == Kind::Func &&
           "can only create a Func SILDeclRef for a func decl");
    naturalUncurryLevel = getFuncNaturalUncurryLevel(func);
  } else if (isa<ConstructorDecl>(vd)) {
    assert((kind == Kind::Allocator || kind == Kind::Initializer)
           && "can only create Allocator or Initializer SILDeclRef for ctor");
    naturalUncurryLevel = 1;
  } else if (auto *ed = dyn_cast<EnumElementDecl>(vd)) {
    assert(kind == Kind::EnumElement
           && "can only create EnumElement SILDeclRef for enum element");
    naturalUncurryLevel = ed->hasArgumentType() ? 1 : 0;
  } else if (isa<DestructorDecl>(vd)) {
    assert((kind == Kind::Destroyer || kind == Kind::Deallocator)
           && "can only create destroyer/deallocator SILDeclRef for dtor");
    naturalUncurryLevel = 0;
  } else if (isa<ClassDecl>(vd)) {
    assert((kind == Kind::IVarInitializer || kind == Kind::IVarDestroyer) &&
           "can only create ivar initializer/destroyer SILDeclRef for class");
    naturalUncurryLevel = 1;
  } else if (auto *var = dyn_cast<VarDecl>(vd)) {
    assert(kind == Kind::GlobalAccessor &&
           "can only create GlobalAccessor SILDeclRef for var");

    naturalUncurryLevel = 0;
    assert(!var->getDeclContext()->isLocalContext() &&
           "can't reference local var as global var");
    assert(var->hasStorage() && "can't reference computed var as global var");
    (void)var;
  } else {
    llvm_unreachable("Unhandled ValueDecl for SILDeclRef");
  }

  assert((atUncurryLevel == ConstructAtNaturalUncurryLevel
          || atUncurryLevel <= naturalUncurryLevel)
         && "can't emit SILDeclRef below natural uncurry level");
  uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel
    ? naturalUncurryLevel
    : atUncurryLevel;
  isCurried = uncurryLevel != naturalUncurryLevel;
}

SILDeclRef::SILDeclRef(SILDeclRef::Loc baseLoc,
                       ResilienceExpansion expansion,
                       unsigned atUncurryLevel, bool asForeign)
 : defaultArgIndex(0)
{
  unsigned naturalUncurryLevel;
  if (ValueDecl *vd = baseLoc.dyn_cast<ValueDecl*>()) {
    if (FuncDecl *fd = dyn_cast<FuncDecl>(vd)) {
      // Map FuncDecls directly to Func SILDeclRefs.
      loc = fd;
      kind = Kind::Func;
      naturalUncurryLevel = getFuncNaturalUncurryLevel(fd);
    }
    // Map ConstructorDecls to the Allocator SILDeclRef of the constructor.
    else if (ConstructorDecl *cd = dyn_cast<ConstructorDecl>(vd)) {
      loc = cd;
      kind = Kind::Allocator;
      naturalUncurryLevel = 1;

      // FIXME: Should we require the caller to think about this?
      asForeign = false;
    }
    // Map EnumElementDecls to the EnumElement SILDeclRef of the element.
    else if (EnumElementDecl *ed = dyn_cast<EnumElementDecl>(vd)) {
      loc = ed;
      kind = Kind::EnumElement;
      naturalUncurryLevel = ed->hasArgumentType() ? 1 : 0;
    }
    // VarDecl constants require an explicit kind.
    else if (isa<VarDecl>(vd)) {
      llvm_unreachable("must create SILDeclRef for VarDecl with explicit kind");
    }
    // Map DestructorDecls to the Deallocator of the destructor.
    else if (auto dtor = dyn_cast<DestructorDecl>(vd)) {
      loc = dtor;
      kind = Kind::Deallocator;
      naturalUncurryLevel = 0;
    }
    else {
      llvm_unreachable("invalid loc decl for SILDeclRef!");
    }
  } else if (auto *ACE = baseLoc.dyn_cast<AbstractClosureExpr *>()) {
    loc = ACE;
    kind = Kind::Func;
    assert(ACE->getParamPatterns().size() >= 1 &&
           "no param patterns for function?!");
    naturalUncurryLevel = getFuncNaturalUncurryLevel(ACE);
  } else {
    llvm_unreachable("impossible SILDeclRef loc");
  }

  // Set the uncurry level.
  assert((atUncurryLevel == ConstructAtNaturalUncurryLevel
          || atUncurryLevel <= naturalUncurryLevel)
         && "can't emit SILDeclRef below natural uncurry level");
  uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel
    ? naturalUncurryLevel
    : atUncurryLevel;
  Expansion = (unsigned) expansion;

  isCurried = uncurryLevel != naturalUncurryLevel;
  isForeign = asForeign;
}

static SILLinkage getLinkageForLocalContext(DeclContext *dc) {
  while (!dc->isModuleScopeContext()) {
    // Local definitions in transparent contexts are forced public because
    // external references to them can be exposed by mandatory inlining.
    if (auto fn = dyn_cast<AbstractFunctionDecl>(dc)) {
      if (fn->isTransparent())
        return SILLinkage::Public;
    }
    // Check that this local context is not itself in a local transparent
    // context.
    dc = dc->getParent();
  }

  return SILLinkage::Private;
}

SILLinkage SILDeclRef::getLinkage(ForDefinition_t forDefinition) const {
  // Anonymous functions have local linkage.
  if (auto closure = getAbstractClosureExpr())
    return getLinkageForLocalContext(closure->getParent());

  // Function-local declarations always have internal linkage.
  ValueDecl *d = getDecl();
  DeclContext *dc = d->getDeclContext();
  while (!dc->isModuleScopeContext()) {
    if (dc->isLocalContext())
      return getLinkageForLocalContext(dc);
    dc = dc->getParent();
  }

  // Currying and calling convention thunks have shared linkage.
  if (isCurried || isForeignThunk())
    return SILLinkage::Shared;

  // Declarations imported from Clang modules have shared linkage.
  // FIXME: They shouldn't.
  const SILLinkage ClangLinkage = SILLinkage::Shared;

  if (isa<ClangModuleUnit>(dc)) {
    if (isa<ConstructorDecl>(d) || isa<EnumElementDecl>(d))
      return ClangLinkage;

    if (auto *FD = dyn_cast<FuncDecl>(d))
      if (FD->isGetterOrSetter() || isa<EnumDecl>(d->getDeclContext()) ||
          isa<StructDecl>(d->getDeclContext()))
        return ClangLinkage;
  }
  // Declarations that were derived on behalf of types in Clang modules get
  // shared linkage.
  if (auto *FD = dyn_cast<FuncDecl>(d)) {
    if (auto derivedFor = FD->getDerivedForTypeDecl())
      if (isa<ClangModuleUnit>(derivedFor->getModuleScopeContext()))
        return ClangLinkage;
  }

  // Otherwise, we have external linkage.
  // FIXME: access control
  return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);
}

SILDeclRef SILDeclRef::getDefaultArgGenerator(Loc loc,
                                              unsigned defaultArgIndex) {
  SILDeclRef result;
  result.loc = loc;
  result.kind = Kind::DefaultArgGenerator;
  result.defaultArgIndex = defaultArgIndex;
  return result;
}

/// \brief True if the function should be treated as transparent.
bool SILDeclRef::isTransparent() const {
  if (isEnumElement())
    return true;

  return hasDecl() ? getDecl()->isTransparent() : false;
}

bool SILDeclRef::isForeignThunk() const {
  // Non-decl entry points are never thunks.
  if (!hasDecl())
    return false;
  // Otherwise, match whether we have a clang node with whether we're foreign.
  if (isa<FuncDecl>(getDecl()) && getDecl()->hasClangNode())
    return !isForeign;
  return false;
}

static void mangleConstant(SILDeclRef c, llvm::raw_ostream &buffer) {
  using namespace Mangle;
  Mangler mangler(buffer);

  // Almost everything below gets one of the common prefixes:
  //   mangled-name ::= '_T' global     // Native symbol
  //   mangled-name ::= '_TTo' global   // ObjC interop thunk
  //   mangled-name ::= '_TTO' global   // Foreign function thunk
  StringRef introducer = "_T";
  if (c.isForeign)
    introducer = "_TTo";
  else if (c.isForeignThunk())
    introducer = "_TTO";

  switch (c.kind) {
  //   entity ::= declaration                     // other declaration
  case SILDeclRef::Kind::Func:
    if (!c.hasDecl()) {
      buffer << introducer;
      mangler.mangleClosureEntity(c.getAbstractClosureExpr(),
                                  c.getResilienceExpansion(),
                                  c.uncurryLevel);
      return;
    }

    // As a special case, functions can have external asm names.
    // Use the asm name only for the original non-thunked, non-curried entry
    // point.
    if (auto AsmA = c.getDecl()->getAttrs().getAttribute<AsmnameAttr>())
      if (!c.isForeignThunk() && !c.isCurried) {
        buffer << AsmA->Name;
        return;
      }

    // Otherwise, fall through into the 'other decl' case.
    SWIFT_FALLTHROUGH;

  case SILDeclRef::Kind::EnumElement:
    // As a special case, Clang functions and globals don't get mangled at all.
    // FIXME: When we can import C++, use Clang's mangler.
    if (auto clangDecl = c.getDecl()->getClangDecl()) {
      if (!c.isForeignThunk() && !c.isCurried) {
        if (auto namedClangDecl = dyn_cast<clang::DeclaratorDecl>(clangDecl)) {
          if (auto asmLabel = namedClangDecl->getAttr<clang::AsmLabelAttr>()) {
            buffer << '\01' << asmLabel->getLabel();
          } else {
            buffer << namedClangDecl->getName();
          }
          return;
        }
      }
    }

    buffer << introducer;
    mangler.mangleEntity(c.getDecl(), c.getResilienceExpansion(), c.uncurryLevel);
    return;

  //   entity ::= context 'D'                     // deallocating destructor
  case SILDeclRef::Kind::Deallocator:
    buffer << introducer;
    mangler.mangleDestructorEntity(cast<DestructorDecl>(c.getDecl()),
                                   /*isDeallocating*/ true);
    return;

  //   entity ::= context 'd'                     // destroying destructor
  case SILDeclRef::Kind::Destroyer:
    buffer << introducer;
    mangler.mangleDestructorEntity(cast<DestructorDecl>(c.getDecl()),
                                   /*isDeallocating*/ false);
    return;

  //   entity ::= context 'C' type                // allocating constructor
  case SILDeclRef::Kind::Allocator:
    buffer << introducer;
    mangler.mangleConstructorEntity(cast<ConstructorDecl>(c.getDecl()),
                                    /*allocating*/ true,
                                    c.getResilienceExpansion(),
                                    c.uncurryLevel);
    return;

  //   entity ::= context 'c' type                // initializing constructor
  case SILDeclRef::Kind::Initializer:
    buffer << introducer;
    mangler.mangleConstructorEntity(cast<ConstructorDecl>(c.getDecl()),
                                    /*allocating*/ false,
                                    c.getResilienceExpansion(),
                                    c.uncurryLevel);
    return;

  //   entity ::= declaration 'e'                 // ivar initializer
  //   entity ::= declaration 'E'                 // ivar destroyer
  case SILDeclRef::Kind::IVarInitializer:
  case SILDeclRef::Kind::IVarDestroyer:
    buffer << introducer;
    mangler.mangleIVarInitDestroyEntity(
      cast<ClassDecl>(c.getDecl()),
      c.kind == SILDeclRef::Kind::IVarDestroyer);
    return;

  //   entity ::= declaration 'a'                 // addressor
  case SILDeclRef::Kind::GlobalAccessor:
    buffer << introducer;
    mangler.mangleAddressorEntity(c.getDecl());
    return;

  //   entity ::= context 'e' index           // default arg generator
  case SILDeclRef::Kind::DefaultArgGenerator:
    buffer << introducer;
    mangler.mangleDefaultArgumentEntity(cast<AbstractFunctionDecl>(c.getDecl()),
                                        c.defaultArgIndex);
    return;
  }

  llvm_unreachable("bad entity kind!");
}

StringRef SILDeclRef::mangle(SmallVectorImpl<char> &buffer) const {
  assert(buffer.empty());
  llvm::raw_svector_ostream stream(buffer);
  mangleConstant(*this, stream);
  return stream.str();
}
<commit_msg>Whenever we compute linkage of something with local linkage, if we can't find an abstract func decl, make the linkage shared.<commit_after>//===--- SILDeclRef.cpp - Implements SILDeclRef ---------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILDeclRef.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Mangle.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/SILLinkage.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
using namespace swift;

static unsigned getFuncNaturalUncurryLevel(AnyFunctionRef AFR) {
  assert(AFR.getBodyParamPatterns().size() >= 1 && "no arguments for func?!");
  unsigned Level = AFR.getBodyParamPatterns().size() - 1;
  // Functions with captures have an extra uncurry level for the capture
  // context.
  if (AFR.getCaptureInfo().hasLocalCaptures())
    Level += 1;
  return Level;
}

SILDeclRef::SILDeclRef(ValueDecl *vd, SILDeclRef::Kind kind,
                       ResilienceExpansion expansion,
                       unsigned atUncurryLevel, bool isForeign)
  : loc(vd), kind(kind), Expansion(unsigned(expansion)),
    isForeign(isForeign), defaultArgIndex(0)
{
  unsigned naturalUncurryLevel;

  // FIXME: restructure to use a "switch".

  if (auto *func = dyn_cast<FuncDecl>(vd)) {
    assert(kind == Kind::Func &&
           "can only create a Func SILDeclRef for a func decl");
    naturalUncurryLevel = getFuncNaturalUncurryLevel(func);
  } else if (isa<ConstructorDecl>(vd)) {
    assert((kind == Kind::Allocator || kind == Kind::Initializer)
           && "can only create Allocator or Initializer SILDeclRef for ctor");
    naturalUncurryLevel = 1;
  } else if (auto *ed = dyn_cast<EnumElementDecl>(vd)) {
    assert(kind == Kind::EnumElement
           && "can only create EnumElement SILDeclRef for enum element");
    naturalUncurryLevel = ed->hasArgumentType() ? 1 : 0;
  } else if (isa<DestructorDecl>(vd)) {
    assert((kind == Kind::Destroyer || kind == Kind::Deallocator)
           && "can only create destroyer/deallocator SILDeclRef for dtor");
    naturalUncurryLevel = 0;
  } else if (isa<ClassDecl>(vd)) {
    assert((kind == Kind::IVarInitializer || kind == Kind::IVarDestroyer) &&
           "can only create ivar initializer/destroyer SILDeclRef for class");
    naturalUncurryLevel = 1;
  } else if (auto *var = dyn_cast<VarDecl>(vd)) {
    assert(kind == Kind::GlobalAccessor &&
           "can only create GlobalAccessor SILDeclRef for var");

    naturalUncurryLevel = 0;
    assert(!var->getDeclContext()->isLocalContext() &&
           "can't reference local var as global var");
    assert(var->hasStorage() && "can't reference computed var as global var");
    (void)var;
  } else {
    llvm_unreachable("Unhandled ValueDecl for SILDeclRef");
  }

  assert((atUncurryLevel == ConstructAtNaturalUncurryLevel
          || atUncurryLevel <= naturalUncurryLevel)
         && "can't emit SILDeclRef below natural uncurry level");
  uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel
    ? naturalUncurryLevel
    : atUncurryLevel;
  isCurried = uncurryLevel != naturalUncurryLevel;
}

SILDeclRef::SILDeclRef(SILDeclRef::Loc baseLoc,
                       ResilienceExpansion expansion,
                       unsigned atUncurryLevel, bool asForeign)
 : defaultArgIndex(0)
{
  unsigned naturalUncurryLevel;
  if (ValueDecl *vd = baseLoc.dyn_cast<ValueDecl*>()) {
    if (FuncDecl *fd = dyn_cast<FuncDecl>(vd)) {
      // Map FuncDecls directly to Func SILDeclRefs.
      loc = fd;
      kind = Kind::Func;
      naturalUncurryLevel = getFuncNaturalUncurryLevel(fd);
    }
    // Map ConstructorDecls to the Allocator SILDeclRef of the constructor.
    else if (ConstructorDecl *cd = dyn_cast<ConstructorDecl>(vd)) {
      loc = cd;
      kind = Kind::Allocator;
      naturalUncurryLevel = 1;

      // FIXME: Should we require the caller to think about this?
      asForeign = false;
    }
    // Map EnumElementDecls to the EnumElement SILDeclRef of the element.
    else if (EnumElementDecl *ed = dyn_cast<EnumElementDecl>(vd)) {
      loc = ed;
      kind = Kind::EnumElement;
      naturalUncurryLevel = ed->hasArgumentType() ? 1 : 0;
    }
    // VarDecl constants require an explicit kind.
    else if (isa<VarDecl>(vd)) {
      llvm_unreachable("must create SILDeclRef for VarDecl with explicit kind");
    }
    // Map DestructorDecls to the Deallocator of the destructor.
    else if (auto dtor = dyn_cast<DestructorDecl>(vd)) {
      loc = dtor;
      kind = Kind::Deallocator;
      naturalUncurryLevel = 0;
    }
    else {
      llvm_unreachable("invalid loc decl for SILDeclRef!");
    }
  } else if (auto *ACE = baseLoc.dyn_cast<AbstractClosureExpr *>()) {
    loc = ACE;
    kind = Kind::Func;
    assert(ACE->getParamPatterns().size() >= 1 &&
           "no param patterns for function?!");
    naturalUncurryLevel = getFuncNaturalUncurryLevel(ACE);
  } else {
    llvm_unreachable("impossible SILDeclRef loc");
  }

  // Set the uncurry level.
  assert((atUncurryLevel == ConstructAtNaturalUncurryLevel
          || atUncurryLevel <= naturalUncurryLevel)
         && "can't emit SILDeclRef below natural uncurry level");
  uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel
    ? naturalUncurryLevel
    : atUncurryLevel;
  Expansion = (unsigned) expansion;

  isCurried = uncurryLevel != naturalUncurryLevel;
  isForeign = asForeign;
}

static SILLinkage getLinkageForLocalContext(DeclContext *dc) {
  while (!dc->isModuleScopeContext()) {
    // Local definitions in transparent contexts are forced public because
    // external references to them can be exposed by mandatory inlining.
    if (auto fn = dyn_cast<AbstractFunctionDecl>(dc))
      if (fn->isTransparent())
        return SILLinkage::Public;
    // Check that this local context is not itself in a local transparent
    // context.
    dc = dc->getParent();
  }

  // FIXME: Once we have access control at the AST level, we should not assume
  // shared always, but rather base it off of the local decl context.
  return SILLinkage::Shared;
}

SILLinkage SILDeclRef::getLinkage(ForDefinition_t forDefinition) const {
  // Anonymous functions have local linkage.
  if (auto closure = getAbstractClosureExpr())
    return getLinkageForLocalContext(closure->getParent());

  // Function-local declarations always have internal linkage.
  ValueDecl *d = getDecl();
  DeclContext *dc = d->getDeclContext();
  while (!dc->isModuleScopeContext()) {
    if (dc->isLocalContext())
      return getLinkageForLocalContext(dc);
    dc = dc->getParent();
  }

  // Currying and calling convention thunks have shared linkage.
  if (isCurried || isForeignThunk())
    return SILLinkage::Shared;

  // Declarations imported from Clang modules have shared linkage.
  // FIXME: They shouldn't.
  const SILLinkage ClangLinkage = SILLinkage::Shared;

  if (isa<ClangModuleUnit>(dc)) {
    if (isa<ConstructorDecl>(d) || isa<EnumElementDecl>(d))
      return ClangLinkage;

    if (auto *FD = dyn_cast<FuncDecl>(d))
      if (FD->isGetterOrSetter() || isa<EnumDecl>(d->getDeclContext()) ||
          isa<StructDecl>(d->getDeclContext()))
        return ClangLinkage;
  }
  // Declarations that were derived on behalf of types in Clang modules get
  // shared linkage.
  if (auto *FD = dyn_cast<FuncDecl>(d)) {
    if (auto derivedFor = FD->getDerivedForTypeDecl())
      if (isa<ClangModuleUnit>(derivedFor->getModuleScopeContext()))
        return ClangLinkage;
  }

  // Otherwise, we have external linkage.
  // FIXME: access control
  return (forDefinition ? SILLinkage::Public : SILLinkage::PublicExternal);
}

SILDeclRef SILDeclRef::getDefaultArgGenerator(Loc loc,
                                              unsigned defaultArgIndex) {
  SILDeclRef result;
  result.loc = loc;
  result.kind = Kind::DefaultArgGenerator;
  result.defaultArgIndex = defaultArgIndex;
  return result;
}

/// \brief True if the function should be treated as transparent.
bool SILDeclRef::isTransparent() const {
  if (isEnumElement())
    return true;

  return hasDecl() ? getDecl()->isTransparent() : false;
}

bool SILDeclRef::isForeignThunk() const {
  // Non-decl entry points are never thunks.
  if (!hasDecl())
    return false;
  // Otherwise, match whether we have a clang node with whether we're foreign.
  if (isa<FuncDecl>(getDecl()) && getDecl()->hasClangNode())
    return !isForeign;
  return false;
}

static void mangleConstant(SILDeclRef c, llvm::raw_ostream &buffer) {
  using namespace Mangle;
  Mangler mangler(buffer);

  // Almost everything below gets one of the common prefixes:
  //   mangled-name ::= '_T' global     // Native symbol
  //   mangled-name ::= '_TTo' global   // ObjC interop thunk
  //   mangled-name ::= '_TTO' global   // Foreign function thunk
  StringRef introducer = "_T";
  if (c.isForeign)
    introducer = "_TTo";
  else if (c.isForeignThunk())
    introducer = "_TTO";

  switch (c.kind) {
  //   entity ::= declaration                     // other declaration
  case SILDeclRef::Kind::Func:
    if (!c.hasDecl()) {
      buffer << introducer;
      mangler.mangleClosureEntity(c.getAbstractClosureExpr(),
                                  c.getResilienceExpansion(),
                                  c.uncurryLevel);
      return;
    }

    // As a special case, functions can have external asm names.
    // Use the asm name only for the original non-thunked, non-curried entry
    // point.
    if (auto AsmA = c.getDecl()->getAttrs().getAttribute<AsmnameAttr>())
      if (!c.isForeignThunk() && !c.isCurried) {
        buffer << AsmA->Name;
        return;
      }

    // Otherwise, fall through into the 'other decl' case.
    SWIFT_FALLTHROUGH;

  case SILDeclRef::Kind::EnumElement:
    // As a special case, Clang functions and globals don't get mangled at all.
    // FIXME: When we can import C++, use Clang's mangler.
    if (auto clangDecl = c.getDecl()->getClangDecl()) {
      if (!c.isForeignThunk() && !c.isCurried) {
        if (auto namedClangDecl = dyn_cast<clang::DeclaratorDecl>(clangDecl)) {
          if (auto asmLabel = namedClangDecl->getAttr<clang::AsmLabelAttr>()) {
            buffer << '\01' << asmLabel->getLabel();
          } else {
            buffer << namedClangDecl->getName();
          }
          return;
        }
      }
    }

    buffer << introducer;
    mangler.mangleEntity(c.getDecl(), c.getResilienceExpansion(), c.uncurryLevel);
    return;

  //   entity ::= context 'D'                     // deallocating destructor
  case SILDeclRef::Kind::Deallocator:
    buffer << introducer;
    mangler.mangleDestructorEntity(cast<DestructorDecl>(c.getDecl()),
                                   /*isDeallocating*/ true);
    return;

  //   entity ::= context 'd'                     // destroying destructor
  case SILDeclRef::Kind::Destroyer:
    buffer << introducer;
    mangler.mangleDestructorEntity(cast<DestructorDecl>(c.getDecl()),
                                   /*isDeallocating*/ false);
    return;

  //   entity ::= context 'C' type                // allocating constructor
  case SILDeclRef::Kind::Allocator:
    buffer << introducer;
    mangler.mangleConstructorEntity(cast<ConstructorDecl>(c.getDecl()),
                                    /*allocating*/ true,
                                    c.getResilienceExpansion(),
                                    c.uncurryLevel);
    return;

  //   entity ::= context 'c' type                // initializing constructor
  case SILDeclRef::Kind::Initializer:
    buffer << introducer;
    mangler.mangleConstructorEntity(cast<ConstructorDecl>(c.getDecl()),
                                    /*allocating*/ false,
                                    c.getResilienceExpansion(),
                                    c.uncurryLevel);
    return;

  //   entity ::= declaration 'e'                 // ivar initializer
  //   entity ::= declaration 'E'                 // ivar destroyer
  case SILDeclRef::Kind::IVarInitializer:
  case SILDeclRef::Kind::IVarDestroyer:
    buffer << introducer;
    mangler.mangleIVarInitDestroyEntity(
      cast<ClassDecl>(c.getDecl()),
      c.kind == SILDeclRef::Kind::IVarDestroyer);
    return;

  //   entity ::= declaration 'a'                 // addressor
  case SILDeclRef::Kind::GlobalAccessor:
    buffer << introducer;
    mangler.mangleAddressorEntity(c.getDecl());
    return;

  //   entity ::= context 'e' index           // default arg generator
  case SILDeclRef::Kind::DefaultArgGenerator:
    buffer << introducer;
    mangler.mangleDefaultArgumentEntity(cast<AbstractFunctionDecl>(c.getDecl()),
                                        c.defaultArgIndex);
    return;
  }

  llvm_unreachable("bad entity kind!");
}

StringRef SILDeclRef::mangle(SmallVectorImpl<char> &buffer) const {
  assert(buffer.empty());
  llvm::raw_svector_ostream stream(buffer);
  mangleConstant(*this, stream);
  return stream.str();
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef TAR_READER_HPP
#define TAR_READER_HPP

#include <posix/tar.h>        // Our posix header has the Tar_header struct, which the newlib tar.h does not
#include <util/tinf.h>        // From uzlib (mod)
#include <util/crc32.hpp>

#include <string>
#include <vector>
#include <stdexcept>

extern char _binary_input_bin_start;
extern uintptr_t _binary_input_bin_size;

namespace tar {

const int SECTOR_SIZE = 512;
const int DECOMPRESSION_SIZE = 256;

static bool has_uzlib_init = false;

// --------------------------- Tar_exception ---------------------------

class Tar_exception : public std::runtime_error {
  using runtime_error::runtime_error;
};

// ------------------------------ Element ------------------------------

// Element/file/folder in tarball
class Element {

public:
  Element(Tar_header& header)
    : header_{header} {}

  Element(Tar_header& header, const char* content_start)
    : header_{header}, content_start_{content_start} {}

  const Tar_header& header() const { return header_; }
  void set_header(const Tar_header& header) { header_ = header; }

  const char* content() const { return content_start_; }
  void set_content_start(const char* content_start) { content_start_ = content_start; }

  const char* last_block() { return content_start_ + (SECTOR_SIZE * num_content_blocks()); }

  std::string name() const { return std::string{header_.name}; }
  std::string mode() const { return std::string{header_.mode}; }
  std::string uid() const { return std::string{header_.uid}; }
  std::string gid() const { return std::string{header_.gid}; }
  long int size();
  std::string mod_time() const { return std::string{header_.mod_time, LENGTH_MTIME}; }
  std::string checksum() const { return std::string{header_.checksum}; }
  char typeflag() const { return header_.typeflag; }
  std::string linkname() { return std::string{header_.linkname}; }
  std::string magic() const { return std::string{header_.magic}; }
  std::string version() const { return std::string{header_.version, LENGTH_VERSION}; }
  std::string uname() const { return std::string{header_.uname}; }
  std::string gname() const { return std::string{header_.gname}; }
  std::string devmajor() const { return std::string{header_.devmajor}; }
  std::string devminor() const { return std::string{header_.devminor}; }
  std::string prefix() const { return std::string{header_.prefix}; }
  std::string pad() const { return std::string{header_.pad}; }

  bool is_ustar() const { return header_.magic == TMAGIC; }
  bool is_dir() const { return header_.typeflag == DIRTYPE; }
  bool typeflag_is_set() const { return header_.typeflag not_eq ' '; }
  bool is_empty() { return size() == 0; }

  int num_content_blocks() {
    int num_blocks = 0;

    if (not typeflag_is_set() or not is_dir()) {
      long int sz = size();

      if (sz % SECTOR_SIZE not_eq 0)
        num_blocks = (sz / SECTOR_SIZE) + 1;
      else
        num_blocks = (sz / SECTOR_SIZE);
    }

    return num_blocks;
  }

private:
  Tar_header& header_;
  const char* content_start_ = nullptr;
};

// --------------------------------- Tar ---------------------------------

class Tar {

public:
  Tar() = default;
  int num_elements() const { return elements_.size(); }
  void add_element(const Element& element) { elements_.push_back(element); }
  const Element element(const std::string& path) const;
  const std::vector<Element>& elements() const { return elements_; }
  std::vector<std::string> element_names() const;

private:
  std::vector<Element> elements_;

};  // class Tar

// ------------------------------ Tar_reader ------------------------------

class Tar_reader {

public:
  uint32_t checksum(Element& element) const { return crc32(element.content(), element.size()); }

  unsigned int decompressed_length(const char* data, size_t size) const;

  Tar& read_binary_tar() {
    const char* bin_content   = &_binary_input_bin_start;
    const int   bin_size      = (intptr_t) &_binary_input_bin_size;

    return read_uncompressed(bin_content, bin_size);
  }

  Tar& read_binary_tar_gz() {
    const char* bin_content  = &_binary_input_bin_start;
    const int   bin_size     = (intptr_t) &_binary_input_bin_size;

    return decompress(bin_content, bin_size);
  }

  /**
    dlen is only given if the data is from an Element - see decompress(Element&)
  */
  Tar& decompress(const char* data, size_t size, unsigned int dlen = 0) {
    if (!has_uzlib_init) {
      uzlib_init();
      has_uzlib_init = true;
    }

    // If not decompressing an Element:
    if (dlen == 0)
      dlen = decompressed_length(data, size);

    TINF_DATA d;
    d.source = reinterpret_cast<const unsigned char*>(data);

    int res = uzlib_gzip_parse_header(&d);

    if (res != TINF_OK)
      throw Tar_exception(std::string{"Error parsing header: " + std::to_string(res)});

    uzlib_uncompress_init(&d, NULL, 0);

    auto dest = std::make_unique<unsigned char[]>(dlen);

    d.dest = dest.get();

    // decompress byte by byte or any other length
    d.destSize = DECOMPRESSION_SIZE;

    printf("Decompression started - waiting...\n");

    do {
      res = uzlib_uncompress_chksum(&d);
    } while (res == TINF_OK);

    if (res not_eq TINF_DONE)
      throw Tar_exception(std::string{"Error during decompression. Res: " + std::to_string(res)});

    printf("Decompressed %d bytes\n", d.dest - dest.get());

    return read_uncompressed(reinterpret_cast<const char*>(dest.get()), dlen);
  }

  /* When have a tar.gz file inside a tar file f.ex. */
  Tar& decompress(Element& element) {
    return decompress(element.content(), element.size(), decompressed_length(element.content(), element.size()));
  }

  Tar& read_uncompressed(const char* data, size_t size);

private:
  Tar tar_;

};  // < class Tar_reader

};  // namespace tar

#endif
<commit_msg>Tar reader: Removed unused method<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef TAR_READER_HPP
#define TAR_READER_HPP

#include <posix/tar.h>        // Our posix header has the Tar_header struct, which the newlib tar.h does not
#include <util/tinf.h>        // From uzlib (mod)
#include <util/crc32.hpp>

#include <string>
#include <vector>
#include <stdexcept>

extern char _binary_input_bin_start;
extern uintptr_t _binary_input_bin_size;

namespace tar {

const int SECTOR_SIZE = 512;
const int DECOMPRESSION_SIZE = 256;

static bool has_uzlib_init = false;

// --------------------------- Tar_exception ---------------------------

class Tar_exception : public std::runtime_error {
  using runtime_error::runtime_error;
};

// ------------------------------ Element ------------------------------

// Element/file/folder in tarball
class Element {

public:
  Element(Tar_header& header)
    : header_{header} {}

  Element(Tar_header& header, const char* content_start)
    : header_{header}, content_start_{content_start} {}

  const Tar_header& header() const { return header_; }
  void set_header(const Tar_header& header) { header_ = header; }

  const char* content() const { return content_start_; }
  void set_content_start(const char* content_start) { content_start_ = content_start; }

  std::string name() const { return std::string{header_.name}; }
  std::string mode() const { return std::string{header_.mode}; }
  std::string uid() const { return std::string{header_.uid}; }
  std::string gid() const { return std::string{header_.gid}; }
  long int size();
  std::string mod_time() const { return std::string{header_.mod_time, LENGTH_MTIME}; }
  std::string checksum() const { return std::string{header_.checksum}; }
  char typeflag() const { return header_.typeflag; }
  std::string linkname() { return std::string{header_.linkname}; }
  std::string magic() const { return std::string{header_.magic}; }
  std::string version() const { return std::string{header_.version, LENGTH_VERSION}; }
  std::string uname() const { return std::string{header_.uname}; }
  std::string gname() const { return std::string{header_.gname}; }
  std::string devmajor() const { return std::string{header_.devmajor}; }
  std::string devminor() const { return std::string{header_.devminor}; }
  std::string prefix() const { return std::string{header_.prefix}; }
  std::string pad() const { return std::string{header_.pad}; }

  bool is_ustar() const { return header_.magic == TMAGIC; }
  bool is_dir() const { return header_.typeflag == DIRTYPE; }
  bool typeflag_is_set() const { return header_.typeflag not_eq ' '; }
  bool is_empty() { return size() == 0; }

  int num_content_blocks() {
    int num_blocks = 0;

    if (not typeflag_is_set() or not is_dir()) {
      long int sz = size();

      if (sz % SECTOR_SIZE not_eq 0)
        num_blocks = (sz / SECTOR_SIZE) + 1;
      else
        num_blocks = (sz / SECTOR_SIZE);
    }

    return num_blocks;
  }

private:
  Tar_header& header_;
  const char* content_start_ = nullptr;
};

// --------------------------------- Tar ---------------------------------

class Tar {

public:
  Tar() = default;
  int num_elements() const { return elements_.size(); }
  void add_element(const Element& element) { elements_.push_back(element); }
  const Element element(const std::string& path) const;
  const std::vector<Element>& elements() const { return elements_; }
  std::vector<std::string> element_names() const;

private:
  std::vector<Element> elements_;

};  // class Tar

// ------------------------------ Tar_reader ------------------------------

class Tar_reader {

public:
  uint32_t checksum(Element& element) const { return crc32(element.content(), element.size()); }

  unsigned int decompressed_length(const char* data, size_t size) const;

  Tar& read_binary_tar() {
    const char* bin_content   = &_binary_input_bin_start;
    const int   bin_size      = (intptr_t) &_binary_input_bin_size;

    return read_uncompressed(bin_content, bin_size);
  }

  Tar& read_binary_tar_gz() {
    const char* bin_content  = &_binary_input_bin_start;
    const int   bin_size     = (intptr_t) &_binary_input_bin_size;

    return decompress(bin_content, bin_size);
  }

  /**
    dlen is only given if the data is from an Element - see decompress(Element&)
  */
  Tar& decompress(const char* data, size_t size, unsigned int dlen = 0) {
    if (!has_uzlib_init) {
      uzlib_init();
      has_uzlib_init = true;
    }

    // If not decompressing an Element:
    if (dlen == 0)
      dlen = decompressed_length(data, size);

    TINF_DATA d;
    d.source = reinterpret_cast<const unsigned char*>(data);

    int res = uzlib_gzip_parse_header(&d);

    if (res != TINF_OK)
      throw Tar_exception(std::string{"Error parsing header: " + std::to_string(res)});

    uzlib_uncompress_init(&d, NULL, 0);

    auto dest = std::make_unique<unsigned char[]>(dlen);

    d.dest = dest.get();

    // decompress byte by byte or any other length
    d.destSize = DECOMPRESSION_SIZE;

    printf("Decompression started - waiting...\n");

    do {
      res = uzlib_uncompress_chksum(&d);
    } while (res == TINF_OK);

    if (res not_eq TINF_DONE)
      throw Tar_exception(std::string{"Error during decompression. Res: " + std::to_string(res)});

    printf("Decompressed %d bytes\n", d.dest - dest.get());

    return read_uncompressed(reinterpret_cast<const char*>(dest.get()), dlen);
  }

  /* When have a tar.gz file inside a tar file f.ex. */
  Tar& decompress(Element& element) {
    return decompress(element.content(), element.size(), decompressed_length(element.content(), element.size()));
  }

  Tar& read_uncompressed(const char* data, size_t size);

private:
  Tar tar_;

};  // < class Tar_reader

};  // namespace tar

#endif
<|endoftext|>


<commit_before><commit_msg>no need to call clear before destryozing a vector<commit_after><|endoftext|>


<commit_before>class Solution {
public:
    void reverseWords(string &s) {
        if(s.empty()) return;

        int len1 = s.size();
        int l=0;

        for(int i = 0; i < len; i++) {
            if(s[i] != ' ' || (i > 0 && s[i-1] != ' '))
                s[l++] = s[i];
        }

        if (l > 0 && s[l-1] == ' ') l--;
        s = s.substr(0,l);
        if (s.empty()) return;

        reverse(s.begin(), s.end());

        l = 0;

        for(int i = 0;i < s.size(); i++) {

            if(s[i] == ' ') {
                reverse(s.begin()+l, s.begin()+i);
                l = i+1;
            }
        }

        reverse(s.begin()+l, s.end());
    }
};
<commit_msg>Update 151-Reverse-Words-In-Sentence.cpp<commit_after>class Solution {
public:
    void reverseWords(string &s) {
        if(s.empty()) return;

        int len1 = s.size();
        int l=0;

        for(int i = 0; i < len1; i++) {
            if(s[i] != ' ' || (i > 0 && s[i-1] != ' '))
                s[l++] = s[i];
        }

        if (l > 0 && s[l-1] == ' ') l--;
        s = s.substr(0,l);
        if (s.empty()) return;

        reverse(s.begin(), s.end());

        l = 0;

        for(int i = 0;i < s.size(); i++) {

            if(s[i] == ' ') {
                reverse(s.begin()+l, s.begin()+i);
                l = i+1;
            }
        }

        reverse(s.begin()+l, s.end());
    }
};
<|endoftext|>


<commit_before><commit_msg>cid#1213562 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2018-2019 Intel Corporation                                    //
//                                                                          //
// 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 <iterator>
#include <memory>
#include <random>
#include "GLFWOSPRayWindow.h"

#include "ospcommon/library.h"
#include "ospcommon/FileName.h"
#include "ospcommon/utility/ArrayView.h"
#include "ospcommon/range.h"
#include "ospray_testing.h"

#include <imgui.h>

using namespace ospcommon;

static const std::string renderer_type = "scivis";

// ALOK: AMRVolume context info
std::vector<float *> brickPtrs;            // holds actual data
std::vector<OSPData> brickData;            // holds actual data as OSPData
range1f valueRange;
float *actualData;
box3f bounds;
int maxParseLevel;

int main(int argc, const char **argv)
{
  // initialize OSPRay; OSPRay parses (and removes) its commandline parameters,
  // e.g. "--osp:debug"
  OSPError initError = ospInit(&argc, argv);

  if (initError != OSP_NO_ERROR)
    return initError;

  // we must load the testing library explicitly on Windows to look up
  // object creation functions
  loadLibrary("ospray_testing");

  // set an error callback to catch any OSPRay errors and exit the application
  ospDeviceSetErrorFunc(
      ospGetCurrentDevice(), [](OSPError error, const char *errorDetails) {
        std::cerr << "OSPRay error: " << errorDetails << std::endl;
        exit(error);
      });

  // create the world which will contain all of our geometries
  OSPWorld world = ospNewWorld();

  std::vector<OSPGeometryInstance> geometryInstances;

  // add in AMR volume
  OSPTestingVolume testData = ospTestingNewVolume("gravity_spheres_amr_volume");

  OSPVolume amrVolume = testData.volume;

  // create a volume instance container
  OSPVolumeInstance instance = ospNewVolumeInstance(amrVolume);
  ospSetFloat(instance, "samplingRate", 10.f);

  // apply a transfer function to the instance
  osp_vec2f amrValueRange = testData.voxelRange;
  OSPTransferFunction tf = ospTestingNewTransferFunction(amrValueRange, "jet");
  ospSetObject(instance, "transferFunction", tf);
  ospCommit(instance);

  // create a data array of all instances
  OSPData volumeInstances = ospNewData(1, OSP_OBJECT, &instance);

  // add volume instance to the world
  ospSetObject(world, "volumes", volumeInstances);

  // create OSPRay renderer
  OSPRenderer renderer = ospNewRenderer(renderer_type.c_str());

  OSPData lightsData = ospTestingNewLights("ambient_only");
  ospSetData(renderer, "lights", lightsData);
  ospRelease(lightsData);

  ospCommit(renderer);

  bounds = reinterpret_cast<box3f &>(testData.bounds);

  // create a GLFW OSPRay window: this object will create and manage the OSPRay
  // frame buffer and camera directly
  auto glfwOSPRayWindow =
      std::unique_ptr<GLFWOSPRayWindow>(new GLFWOSPRayWindow(
          vec2i{1024, 768}, bounds, world, renderer));

  // commit the world
  ospCommit(world);

  // start the GLFW main loop, which will continuously render
  glfwOSPRayWindow->mainLoop();

  // cleanly shut OSPRay down
  ospShutdown();

  return 0;
}
<commit_msg>update volume models and instances API<commit_after>// ======================================================================== //
// Copyright 2018-2019 Intel Corporation                                    //
//                                                                          //
// 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 <iterator>
#include <memory>
#include <random>
#include "GLFWOSPRayWindow.h"

#include "ospcommon/library.h"
#include "ospcommon/FileName.h"
#include "ospcommon/utility/ArrayView.h"
#include "ospcommon/range.h"
#include "ospray_testing.h"

#include <imgui.h>

using namespace ospcommon;

static const std::string renderer_type = "scivis";

// ALOK: AMRVolume context info
std::vector<float *> brickPtrs;            // holds actual data
std::vector<OSPData> brickData;            // holds actual data as OSPData
range1f valueRange;
float *actualData;
box3f bounds;
int maxParseLevel;

int main(int argc, const char **argv)
{
  // initialize OSPRay; OSPRay parses (and removes) its commandline parameters,
  // e.g. "--osp:debug"
  OSPError initError = ospInit(&argc, argv);

  if (initError != OSP_NO_ERROR)
    return initError;

  // we must load the testing library explicitly on Windows to look up
  // object creation functions
  loadLibrary("ospray_testing");

  // set an error callback to catch any OSPRay errors and exit the application
  ospDeviceSetErrorFunc(
      ospGetCurrentDevice(), [](OSPError error, const char *errorDetails) {
        std::cerr << "OSPRay error: " << errorDetails << std::endl;
        exit(error);
      });

  // create the world
  OSPWorld world = ospNewWorld();

  // create the instance that will contain our volume model
  OSPInstance instance = ospNewInstance();

  // generate an AMR volume
  OSPTestingVolume testData = ospTestingNewVolume("gravity_spheres_amr_volume");

  OSPVolume amrVolume = testData.volume;

  osp_vec2f amrValueRange = testData.voxelRange;
  OSPTransferFunction tf = ospTestingNewTransferFunction(amrValueRange, "jet");

  // create the model that will contain our actual volume
  OSPVolumetricModel volumeModel = ospNewVolumetricModel(amrVolume);
  ospSetObject(volumeModel, "transferFunction", tf);
  ospSetFloat(volumeModel, "samplingRate", 10.f);
  ospCommit(volumeModel);

  // create a data array of all models for the instance
  OSPData volumeModels = ospNewData(1, OSP_OBJECT, &volumeModel);
  ospSetObject(instance, "volumes", volumeModels);
  ospCommit(instance);
  ospRelease(volumeModels);

  // create a data array of all instances for the world
  OSPData volumeInstances = ospNewData(1, OSP_OBJECT, &instance);
  ospSetData(world, "instances", volumeInstances);
  ospRelease(volumeInstances);

  // create OSPRay renderer
  OSPRenderer renderer = ospNewRenderer(renderer_type.c_str());

  OSPData lightsData = ospTestingNewLights("ambient_only");
  ospSetData(renderer, "lights", lightsData);
  ospRelease(lightsData);

  ospCommit(renderer);

  bounds = reinterpret_cast<box3f &>(testData.bounds);

  // commit the world
  ospCommit(world);

  // create a GLFW OSPRay window: this object will create and manage the OSPRay
  // frame buffer and camera directly
  auto glfwOSPRayWindow =
      std::unique_ptr<GLFWOSPRayWindow>(new GLFWOSPRayWindow(
          vec2i{1024, 768}, bounds, world, renderer));

  // start the GLFW main loop, which will continuously render
  glfwOSPRayWindow->mainLoop();

  // cleanly shut OSPRay down
  ospShutdown();

  return 0;
}
<|endoftext|>


<commit_before>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF

AliAnalysisTaskJets *AddTaskJets(){
  // fills the standard "jets" branch in the AOD
  // need the ESDFilter to run before, to access the AODtracks
  // Tracks selected by the first Filter (1<<0)
  // needs to be adapted for different cuts

  // UA1 as standard chosen, since it is the most robust and simple JF
  // R = 0.4 suffficient to provide accurate jet axis for correlation studies
  // energy resolution suffers a little
  // Acceptance of jets not limited by the Jet Finder but should be done
  // by user to abs(eta) < 0.5

  return AddTaskJets("AOD","UA1",0.4);

}

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
  // Creates a jet finder task, configures it and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskJets", "No analysis manager to connect to.");
      return NULL;
   }

   // Check the analysis type using the event handlers connected to the analysis manager.
   //==============================================================================
   if (!mgr->GetInputEventHandler()) {
      ::Error("AddTaskJets", "This task requires an input event handler");
      return NULL;
   }

  AliAODHandler *aodh = (AliAODHandler*)mgr->GetOutputEventHandler();
  if (!aodh) {
    ::Error("AddTaskJets", "This task needs an output event handler");
    return NULL;
  }

   // Create the task and configure it.
   //===========================================================================
   AliAnalysisTaskJets *jetana;
   AliJetReader *er = CreateJetReader(jr);
    // Define jet header and jet finder
   AliJetFinder *jetFinder = CreateJetFinder(jf,radius);

   if (jetFinder){
       if (er) jetFinder->SetJetReader(er);
   }

   char *cRadius = "";
   if(radius>0)cRadius = Form("%02d",(int)(radius*10));

   jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s%s%s",jr,jf,cRadius));
   TString type = mgr->GetInputEventHandler()->GetDataType();
   if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf));

   TString c_jr(jr);
   c_jr.ToLower();
   TString c_jf(jf);
   c_jf.ToLower();

   AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist%s%s%s",c_jr.Data(),c_jf.Data(),cRadius), TList::Class(),
							     AliAnalysisManager::kOutputContainer, Form("jethist_%s_%s%s.root",c_jr.Data(),c_jf.Data(),cRadius));
   // Connect jet finder to task.
   jetana->SetJetFinder(jetFinder);
   jetana->SetConfigFile("");
   jetana->SetDebugLevel(0);
   mgr->AddTask(jetana);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================
   mgr->ConnectInput  (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
   mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
   mgr->ConnectOutput (jetana, 1, cout_jet);

   return jetana;
}

AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){
  AliJetFinder *jetFinder = 0;

  switch (jf) {
  case "CDF":
    AliCdfJetHeader *jh = new AliCdfJetHeader();
    jh->SetRadius(0.7);

    jetFinder = new AliCdfJetFinder();
    jetFinder->SetOutputFile("jets.root");
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "DA":
    AliDAJetHeader *jh=new AliDAJetHeader();
    jh->SetComment("DA jet code with default parameters");
    jh->SelectJets(kTRUE);
    jh->SetNclust(10);

    jetFinder = new AliDAJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "FASTJET":
    AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1();
    jh->SetRparam(0.4); // setup parameters
    if(radius>0)jh->SetRparam(radius);
    jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh
    jetFinder = new AliFastJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default parameters");
    jh->BackgMode(0);
    jh->SetRadius(0.4);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetEtSeed(4.);
    jh->SetNAcceptJets(6);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(5.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1MC":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default MC parameters");
    jh->BackgMode(0);
    jh->SetRadius(1.0);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetNAcceptJets(6);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(5.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);
    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;
  default:
    Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n");
    break;
  }

  return jetFinder;

}

AliJetReader *CreateJetReader(Char_t *jr){
  AliJetReader *er = 0;

  switch (jr) {
  case "MC":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "MC2":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics spearate config charged only");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetChargedOnly(kTRUE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "ESD":
    AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    jrh->SetComment("Testing");
    jrh->SetFirstEvent(0);
    jrh->SetLastEvent(1000);
    jrh->SetPtCut(0.);
    jrh->SetReadSignalOnly(kFALSE);
    // Define reader and set its header
    er = new AliJetESDReader();
    er->SetReaderHeader(jrh);
    break;

  case "AOD":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD Reader");
    jrh->SetPtCut(0.);
    jrh->SetTestFilterMask(1<<0);
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;
  case "AODMC":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD MC Reader");
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9
    jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;
  case "AODMC2":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD MC Reader");
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9
    jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;

  default:
    ::Error("AddTaskJets", "Wrong jet reader selected\n");
    return 0;
  }

  return er;

}
<commit_msg>Added method to add a default set of jet fidners for a deltaAOD<commit_after>AliJetReader *CreateJetReader(Char_t *jr); // Common config
AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius = -1);

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf,Float_t radius = -1); // for the new AF

AliAnalysisTaskJets *AddTaskJets(){
  // fills the standard "jets" branch in the AOD
  // need the ESDFilter to run before, to access the AODtracks
  // Tracks selected by the first Filter (1<<0)
  // needs to be adapted for different cuts

  // UA1 as standard chosen, since it is the most robust and simple JF
  // R = 0.4 suffficient to provide accurate jet axis for correlation studies
  // energy resolution suffers a little
  // Acceptance of jets not limited by the Jet Finder but should be done
  // by user to abs(eta) < 0.5

  return AddTaskJets("AOD","UA1",0.4);

}

Int_t AddTaskJetsDelta(char *nonStdFile = ""){

  // Adds a whole set of jet finders  all to be written
  // to a delta AOD

  // this can in principle be done also with on the fly
  // if we have an ESD input jet fidner task does automatically fetch the ouput aod

   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskJetsDelta", "No analysis manager to connect to.");
      return 0;
   }

   // Check the analysis type using the event handlers connected to the analysis manager.
   //==============================================================================
   if (!mgr->GetInputEventHandler()) {
      ::Error("AddTaskJetsDelta", "This task requires an input event handler");
      return 0;
   }

  AliAODHandler *aodh = (AliAODHandler*)mgr->GetOutputEventHandler();
  if (!aodh) {
    ::Error("AddTaskJetsDelta", "This task needs an output event handler");
    return 0;
  }

  TString type = mgr->GetInputEventHandler()->GetDataType();

  AliAnalysisTaskJets *jetana = 0;
  Int_t iCount = 0;

  const char *cJF[3]        = {"UA1","UA1","UA1"};
  const Float_t radius[3]   = {0.4, 0.7, 1.0};
  // flag first bit AOD, second bit AODMC2 third bit AODMC2
  // i.e. 7 all, 6 only MC2 and MC
  // this stay at three
  const UInt_t  flag[3]     = {6,7,7};
  const char *cReader[3] = {"AOD","AODMC","AODMC2"};

  for(int i = 0; i< 3;i++){
    for(int ib = 0;ib<3;ib++){
      if(flag[i]&(1<<ib)){
	jetana = AddTaskJets(cReader[ib],cJF[i],radius[i]);
	if(jetana){
	  char *cRadius = "";
	  if(radius[i]>0)cRadius = Form("%02d",(int)(radius[i]*10));
	  jetana->SetNonStdBranch(Form("jets%s_%s%s",cReader[ib],cJF[i],cRadius));
	  iCount++;
	}
      }
    }
  }

  Printf("Added %d JetFinders",iCount);
}

AliAnalysisTaskJets *AddTaskJets(Char_t *jr, Char_t *jf, Float_t radius)
{
  // Creates a jet finder task, configures it and adds it to the analysis manager.

   // Get the pointer to the existing analysis manager via the static access method.
   //==============================================================================
   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {
      ::Error("AddTaskJets", "No analysis manager to connect to.");
      return NULL;
   }

   // Check the analysis type using the event handlers connected to the analysis manager.
   //==============================================================================
   if (!mgr->GetInputEventHandler()) {
      ::Error("AddTaskJets", "This task requires an input event handler");
      return NULL;
   }

  AliAODHandler *aodh = (AliAODHandler*)mgr->GetOutputEventHandler();
  if (!aodh) {
    ::Error("AddTaskJets", "This task needs an output event handler");
    return NULL;
  }

   // Create the task and configure it.
   //===========================================================================
   AliAnalysisTaskJets *jetana;
   AliJetReader *er = CreateJetReader(jr);
    // Define jet header and jet finder
   AliJetFinder *jetFinder = CreateJetFinder(jf,radius);

   if (jetFinder){
       if (er) jetFinder->SetJetReader(er);
   }

   char *cRadius = "";
   if(radius>0)cRadius = Form("%02d",(int)(radius*10));

   jetana = new AliAnalysisTaskJets(Form("JetAnalysis%s_%s%s",jr,jf,cRadius));
   TString type = mgr->GetInputEventHandler()->GetDataType();
   if (type == "AOD") jetana->SetNonStdBranch(Form("jets%s",jf));

   TString c_jr(jr);
   c_jr.ToLower();
   TString c_jf(jf);
   c_jf.ToLower();

   AliAnalysisDataContainer *cout_jet = mgr->CreateContainer(Form("jethist_%s_%s%s",c_jr.Data(),c_jf.Data(),cRadius), TList::Class(),
							     AliAnalysisManager::kOutputContainer, Form("jethist_%s_%s%s.root",c_jr.Data(),c_jf.Data(),cRadius));
   // Connect jet finder to task.
   jetana->SetJetFinder(jetFinder);
   jetana->SetConfigFile("");
   jetana->SetDebugLevel(0);
   mgr->AddTask(jetana);

   // Create ONLY the output containers for the data produced by the task.
   // Get and connect other common input/output containers via the manager as below
   //==============================================================================
   mgr->ConnectInput  (jetana, 0, mgr->GetCommonInputContainer());
// AOD output slot will be used in a different way in future
   mgr->ConnectOutput (jetana, 0, mgr->GetCommonOutputContainer());
   mgr->ConnectOutput (jetana, 1, cout_jet);

   return jetana;
}

AliJetFinder *CreateJetFinder(Char_t *jf,Float_t radius){
  AliJetFinder *jetFinder = 0;

  switch (jf) {
  case "CDF":
    AliCdfJetHeader *jh = new AliCdfJetHeader();
    jh->SetRadius(0.7);

    jetFinder = new AliCdfJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "DA":
    AliDAJetHeader *jh=new AliDAJetHeader();
    jh->SetComment("DA jet code with default parameters");
    jh->SelectJets(kTRUE);
    jh->SetNclust(10);

    jetFinder = new AliDAJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "FASTJET":
    // DEFAULT is ANTI KT
    AliFastJetHeaderV1 *jh = new AliFastJetHeaderV1();
    jh->SetRparam(0.4); // setup parameters
    if(radius>0)jh->SetRparam(radius);
    jh->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh
    jetFinder = new AliFastJetFinder();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default parameters");
    jh->BackgMode(0);
    jh->SetRadius(0.4);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetEtSeed(4.);
    jh->SetNAcceptJets(6);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(5.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);

    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;

  case "UA1MC":
    AliUA1JetHeaderV1 *jh=new AliUA1JetHeaderV1();
    jh->SetComment("UA1 jet code with default MC parameters");
    jh->BackgMode(0);
    jh->SetRadius(1.0);
    if(radius>0)jh->SetRadius(radius);
    jh->SetEtSeed(4.);
    jh->SetNAcceptJets(6);
    jh->SetLegoNbinPhi(432);
    jh->SetLegoNbinEta(274);
    jh->SetLegoEtaMin(-2);
    jh->SetLegoEtaMax(+2);
    jh->SetMinJetEt(5.);
    jh->SetJetEtaMax(1.5);
    jh->SetJetEtaMin(-1.5);
    jetFinder = new AliUA1JetFinderV1();
    if (jh) jetFinder->SetJetHeader(jh);
    break;
  default:
    Printf("\n >>>>>>> AddTaskJets Error Wrong jet finder selected\n");
    break;
  }

  return jetFinder;

}

AliJetReader *CreateJetReader(Char_t *jr){
  AliJetReader *er = 0;

  switch (jr) {
  case "MC":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "MC2":
    AliJetKineReaderHeader *jrh = new AliJetKineReaderHeader();
    jrh->SetComment("MC full Kinematics spearate config charged only");
    jrh->SetFastSimTPC(kFALSE);
    jrh->SetFastSimEMCAL(kFALSE);
    jrh->SetChargedOnly(kTRUE);
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0 .9
    // Define reader and set its header
    er = new AliJetKineReader();
    er->SetReaderHeader(jrh);
    break;
  case "ESD":
    AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    jrh->SetComment("Testing");
    jrh->SetFirstEvent(0);
    jrh->SetLastEvent(1000);
    jrh->SetPtCut(0.);
    jrh->SetReadSignalOnly(kFALSE);
    // Define reader and set its header
    er = new AliJetESDReader();
    er->SetReaderHeader(jrh);
    break;

  case "AOD":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD Reader");
    jrh->SetPtCut(0.);
    jrh->SetTestFilterMask(1<<0);
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;
  case "AODMC":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD MC Reader");
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9
    jrh->SetReadAODMC(1);// 1 all primary MC , 2 all primary charged
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;
  case "AODMC2":
    AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("AOD MC Reader");
    jrh->SetPtCut(0.);
    jrh->SetFiducialEta(-2.1,2.1); // to take all MC particles default is 0.9
    jrh->SetReadAODMC(2);// 1 all primary MC , 2 all primary charged
    // Define reader and set its header
    er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    break;

  default:
    ::Error("AddTaskJets", "Wrong jet reader selected\n");
    return 0;
  }

  return er;

}
<|endoftext|>