<commit_before>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 2010 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "utility.h"

#include <stdio.h>
#include <wx/filename.h>
#include <wx/log.h>
#include <wx/config.h>
#include <wx/display.h>

// ----------------------------------------------------------------------
// TempDirectory
// ----------------------------------------------------------------------

bool TempDirectory::ms_keepFiles = false;

TempDirectory::TempDirectory() : m_counter(0)
{
#ifdef HAVE_MKDTEMP
    wxString path = wxFileName::GetTempDir();
    path += _T("/poeditXXXXXX");
    wxCharBuffer buf(path.fn_str());
    if ( mkdtemp(buf.data()) == NULL )
    {
        wxLogError(_("Cannot create temporary directory."));
        return;
    }
    m_dir = wxConvFile.cMB2WX(buf.data());
#else
    for ( ;; )
    {
        wxString name = wxFileName::CreateTempFileName(_T("poedit"));
        if ( name.empty() )
        {
            wxLogError(_("Cannot create temporary directory."));
            return;
        }

        wxLogNull null;
        if ( wxRemoveFile(name) && wxMkdir(name, 0700) )
        {
            m_dir = name;
            wxLogTrace(_T("poedit.tmp"), _T("created temp dir %s"), name.c_str());
            break;
        }
        // else: try again
    }
#endif
}

TempDirectory::~TempDirectory()
{
    if ( m_dir.empty() )
        return;

    if ( ms_keepFiles )
    {
        wxLogTrace(_T("poedit.tmp"), _T("keeping temp files in %s"), m_dir.c_str());
        return;
    }

    for ( wxArrayString::const_iterator i = m_files.begin(); i != m_files.end(); ++i )
    {
        if ( wxFileName::FileExists(*i) )
        {
            wxLogTrace(_T("poedit.tmp"), _T("removing temp file %s"), i->c_str());
            wxRemoveFile(*i);
        }
    }

    wxLogTrace(_T("poedit.tmp"), _T("removing temp dir %s"), m_dir.c_str());
    wxFileName::Rmdir(m_dir);
}

wxString TempDirectory::CreateFileName(const wxString& suffix)
{
    wxString s = wxString::Format(_T("%s%c%d%s"),
                                  m_dir.c_str(), wxFILE_SEP_PATH,
                                  m_counter++,
                                  suffix.c_str());
    m_files.push_back(s);
    wxLogTrace(_T("poedit.tmp"), _T("new temp file %s"), s.c_str());
    return s;
}

// ----------------------------------------------------------------------
// Helpers for persisting windows' state
// ----------------------------------------------------------------------

void SaveWindowState(const wxTopLevelWindow *win, int flags)
{
    wxConfigBase *cfg = wxConfig::Get();
    const wxString path = WindowStatePath(win);

    if ( !win->IsIconized() )
    {
        if ( !win->IsMaximized() )
        {
            if ( flags & WinState_Pos )
            {
                const wxPoint pos = win->GetPosition();
                cfg->Write(path + _T("x"), (long)pos.x);
                cfg->Write(path + _T("y"), (long)pos.y);
            }
            if ( flags &  WinState_Size )
            {
                const wxSize sz = win->GetClientSize();
                cfg->Write(path + _T("w"), (long)sz.x);
                cfg->Write(path + _T("h"), (long)sz.y);
            }
        }

        if ( flags &  WinState_Size )
            cfg->Write(path + _T("maximized"), (long)win->IsMaximized());
    }
}

void RestoreWindowState(wxTopLevelWindow *win, const wxSize& defaultSize, int flags)
{
    wxConfigBase *cfg = wxConfig::Get();
    const wxString path = WindowStatePath(win);

    if ( flags & WinState_Size )
    {
        int width = cfg->Read(path + _T("w"), defaultSize.x);
        int height = cfg->Read(path + _T("h"), defaultSize.y);
        if ( width != -1 || height != -1 )
            win->SetClientSize(width, height);
    }

    if ( flags & WinState_Pos )
    {
#ifndef __WXGTK__
        int posx = cfg->Read(path + _T("x"), -1);
        int posy = cfg->Read(path + _T("y"), -1);
        if ( posx != -1 || posy != -1 )
            win->Move(posx, posy);
#endif
    }

#ifndef __WXGTK__
    // If the window is completely out of all screens (e.g. because
    // screens configuration changed), move it to primary screen:
    if ( wxDisplay::GetFromWindow(win) == wxNOT_FOUND )
        win->Move(0, 0);
#endif

    // If the window is larger than current screen, resize it to fit:
    int display = wxDisplay::GetFromWindow(win);
    wxCHECK_RET( display != wxNOT_FOUND, _T("window not on screen") );
    wxRect screenRect = wxDisplay(display).GetClientArea();
    wxRect winRect = win->GetRect();
    if ( !screenRect.Contains(winRect) )
    {
        winRect.Intersect(screenRect);
        win->SetSize(winRect);
    }

    // Maximize if it should be
    if ( cfg->Read(path + _T("maximized"), long(0)) )
    {
        win->Maximize();
    }
}
<commit_msg>Don't adjust window position if it wasn't determined yet.<commit_after>/*
 *  This file is part of Poedit (http://www.poedit.net)
 *
 *  Copyright (C) 2010 Vaclav Slavik
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *  DEALINGS IN THE SOFTWARE.
 *
 */

#include "utility.h"

#include <stdio.h>
#include <wx/filename.h>
#include <wx/log.h>
#include <wx/config.h>
#include <wx/display.h>

// ----------------------------------------------------------------------
// TempDirectory
// ----------------------------------------------------------------------

bool TempDirectory::ms_keepFiles = false;

TempDirectory::TempDirectory() : m_counter(0)
{
#ifdef HAVE_MKDTEMP
    wxString path = wxFileName::GetTempDir();
    path += _T("/poeditXXXXXX");
    wxCharBuffer buf(path.fn_str());
    if ( mkdtemp(buf.data()) == NULL )
    {
        wxLogError(_("Cannot create temporary directory."));
        return;
    }
    m_dir = wxConvFile.cMB2WX(buf.data());
#else
    for ( ;; )
    {
        wxString name = wxFileName::CreateTempFileName(_T("poedit"));
        if ( name.empty() )
        {
            wxLogError(_("Cannot create temporary directory."));
            return;
        }

        wxLogNull null;
        if ( wxRemoveFile(name) && wxMkdir(name, 0700) )
        {
            m_dir = name;
            wxLogTrace(_T("poedit.tmp"), _T("created temp dir %s"), name.c_str());
            break;
        }
        // else: try again
    }
#endif
}

TempDirectory::~TempDirectory()
{
    if ( m_dir.empty() )
        return;

    if ( ms_keepFiles )
    {
        wxLogTrace(_T("poedit.tmp"), _T("keeping temp files in %s"), m_dir.c_str());
        return;
    }

    for ( wxArrayString::const_iterator i = m_files.begin(); i != m_files.end(); ++i )
    {
        if ( wxFileName::FileExists(*i) )
        {
            wxLogTrace(_T("poedit.tmp"), _T("removing temp file %s"), i->c_str());
            wxRemoveFile(*i);
        }
    }

    wxLogTrace(_T("poedit.tmp"), _T("removing temp dir %s"), m_dir.c_str());
    wxFileName::Rmdir(m_dir);
}

wxString TempDirectory::CreateFileName(const wxString& suffix)
{
    wxString s = wxString::Format(_T("%s%c%d%s"),
                                  m_dir.c_str(), wxFILE_SEP_PATH,
                                  m_counter++,
                                  suffix.c_str());
    m_files.push_back(s);
    wxLogTrace(_T("poedit.tmp"), _T("new temp file %s"), s.c_str());
    return s;
}

// ----------------------------------------------------------------------
// Helpers for persisting windows' state
// ----------------------------------------------------------------------

void SaveWindowState(const wxTopLevelWindow *win, int flags)
{
    wxConfigBase *cfg = wxConfig::Get();
    const wxString path = WindowStatePath(win);

    if ( !win->IsIconized() )
    {
        if ( !win->IsMaximized() )
        {
            if ( flags & WinState_Pos )
            {
                const wxPoint pos = win->GetPosition();
                cfg->Write(path + _T("x"), (long)pos.x);
                cfg->Write(path + _T("y"), (long)pos.y);
            }
            if ( flags &  WinState_Size )
            {
                const wxSize sz = win->GetClientSize();
                cfg->Write(path + _T("w"), (long)sz.x);
                cfg->Write(path + _T("h"), (long)sz.y);
            }
        }

        if ( flags &  WinState_Size )
            cfg->Write(path + _T("maximized"), (long)win->IsMaximized());
    }
}

void RestoreWindowState(wxTopLevelWindow *win, const wxSize& defaultSize, int flags)
{
    wxConfigBase *cfg = wxConfig::Get();
    const wxString path = WindowStatePath(win);

    if ( flags & WinState_Size )
    {
        int width = cfg->Read(path + _T("w"), defaultSize.x);
        int height = cfg->Read(path + _T("h"), defaultSize.y);
        if ( width != -1 || height != -1 )
            win->SetClientSize(width, height);
    }

    if ( flags & WinState_Pos )
    {
#ifndef __WXGTK__
        int posx = cfg->Read(path + _T("x"), -1);
        int posy = cfg->Read(path + _T("y"), -1);
        if ( posx != -1 || posy != -1 )
            win->Move(posx, posy);
#endif
    }

#ifndef __WXGTK__
    // If the window is completely out of all screens (e.g. because
    // screens configuration changed), move it to primary screen:
    if ( wxDisplay::GetFromWindow(win) == wxNOT_FOUND )
        win->Move(0, 0);
#endif

    // If the window is larger than current screen, resize it to fit:
    int display = wxDisplay::GetFromWindow(win);
    wxCHECK_RET( display != wxNOT_FOUND, _T("window not on screen") );
    wxRect screenRect = wxDisplay(display).GetClientArea();

    wxRect winRect = win->GetRect();
    if ( winRect.GetPosition() == wxDefaultPosition )
        winRect.SetPosition(screenRect.GetPosition()); // not place yet, fake it

    if ( !screenRect.Contains(winRect) )
    {
        winRect.Intersect(screenRect);
        win->SetSize(winRect);
    }

    // Maximize if it should be
    if ( cfg->Read(path + _T("maximized"), long(0)) )
    {
        win->Maximize();
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

//static int TransactionDbVersion = DB_MINVER_INCHASH;

// Client version number
// Refer to version.h for current version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 0
//#ifdef GIT_ARCHIVE
//#    define GIT_COMMIT_ID "df9d55a"
//#    define GIT_COMMIT_DATE "$Format:%cD"
//#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version number<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");

//static int TransactionDbVersion = DB_MINVER_INCHASH;

// Client version number
// Refer to version.h for current version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
//#define GIT_ARCHIVE 0
//#ifdef GIT_ARCHIVE
//#    define GIT_COMMIT_ID "df9d55a"
//#    define GIT_COMMIT_DATE "$Format:%cD"
//#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "A"

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>/***************************************************************************
    copyright            : (C) 2011 by Lukas Lalinsky
    email                : lalinsky@gmail.com
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include "tiostream.h"

using namespace TagLib;

#ifdef _WIN32

// MSVC 2008 or later can't produce the binary for Win9x.
#if !defined(_MSC_VER) || (_MSC_VER < 1500)

namespace
{

  // Determines whether or not the running system is WinNT.
  // In other words, whether the system supports Unicode.

  bool isWinNT()
  {
    OSVERSIONINFOA ver = {};
    ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
    if(GetVersionExA(&ver)) {
      return (ver.dwPlatformId == VER_PLATFORM_WIN32_NT);
    }
    else {
      return false;
    }
  }

  const bool IsWinNT = isWinNT();

  // Converts a UTF-16 string into a local encoding.

  std::string unicodeToAnsi(const std::wstring &wstr)
  {
    const int len = WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, NULL, 0, NULL, NULL);
    if(len == 0)
      return std::string();

    std::string str(len, '\0');
    WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, &str[0], len, NULL, NULL);

    return str;
  }
}

// If WinNT, stores a Unicode string into m_wname directly.
// If Win9x, converts and stores it into m_name to avoid calling Unicode version functions.

FileName::FileName(const wchar_t *name)
  : m_wname(IsWinNT ? name : L"")
  , m_name(IsWinNT ? "" : unicodeToAnsi(name))
{
}

#else

FileName::FileName(const wchar_t *name)
  : m_wname(name)
{
}

#endif

FileName::FileName(const char *name)
  : m_name(name)
{
}

FileName::FileName(const FileName &name)
  : m_wname(name.m_wname)
  , m_name(name.m_name)
{
}

FileName::operator const wchar_t *() const
{
  return m_wname.c_str();
}

FileName::operator const char *() const
{
  return m_name.c_str();
}

const std::wstring &FileName::wstr() const
{
  return m_wname;
}

const std::string &FileName::str() const
{
  return m_name;
}

#endif

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

IOStream::IOStream()
{
}

IOStream::~IOStream()
{
}

void IOStream::clear()
{
}

<commit_msg>Small change in Win9x support<commit_after>/***************************************************************************
    copyright            : (C) 2011 by Lukas Lalinsky
    email                : lalinsky@gmail.com
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include "tiostream.h"

using namespace TagLib;

#ifdef _WIN32

# include <windows.h>

namespace
{
  // Check if the running system has CreateFileW() function.
  // Windows9x systems don't have CreateFileW() or can't accept Unicode file names.

  bool supportsUnicode()
  {
    const FARPROC p = GetProcAddress(GetModuleHandleA("kernel32"), "CreateFileW");
    return (p != NULL);
  }

  // Indicates whether the system supports Unicode file names.

  const bool SystemSupportsUnicode = supportsUnicode();

  // Converts a UTF-16 string into a local encoding.
  // This function should only be used in Windows9x systems which don't support
  // Unicode file names.

  std::string unicodeToAnsi(const std::wstring &wstr)
  {
    const int len = WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, NULL, 0, NULL, NULL);
    if(len == 0)
      return std::string();

    std::string str(len, '\0');
    WideCharToMultiByte(CP_ACP, 0, &wstr[0], -1, &str[0], len, NULL, NULL);

    return str;
  }
}

// If WinNT, stores a Unicode string into m_wname directly.
// If Win9x, converts and stores it into m_name to avoid calling Unicode version functions.

FileName::FileName(const wchar_t *name)
  : m_wname(SystemSupportsUnicode ? name : L"")
  , m_name (SystemSupportsUnicode ? "" : unicodeToAnsi(name))
{
}

FileName::FileName(const char *name)
  : m_name(name)
{
}

FileName::FileName(const FileName &name)
  : m_wname(name.m_wname)
  , m_name (name.m_name)
{
}

FileName::operator const wchar_t *() const
{
  return m_wname.c_str();
}

FileName::operator const char *() const
{
  return m_name.c_str();
}

const std::wstring &FileName::wstr() const
{
  return m_wname;
}

const std::string &FileName::str() const
{
  return m_name;
}

#endif  // _WIN32

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

IOStream::IOStream()
{
}

IOStream::~IOStream()
{
}

void IOStream::clear()
{
}

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2017 Abdullah Tahiri <abdullah.tahiri.yo@gmail.com>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <cfloat>
# include <QMessageBox>
# include <Precision.hxx>
# include <QApplication>
# include <Standard_Version.hxx>
#endif

# include <QMessageBox>

#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>
#include <Gui/MainWindow.h>
#include <Gui/DlgEditFileIncludeProptertyExternal.h>

#include <Gui/Action.h>
#include <Gui/BitmapFactory.h>

#include "ViewProviderSketch.h"
#include "DrawSketchHandler.h"

#include <Mod/Part/App/Geometry.h>
#include <Mod/Sketcher/App/SketchObject.h>

#include "CommandConstraints.h"

using namespace std;
using namespace SketcherGui;
using namespace Sketcher;

bool isSketcherVirtualSpaceActive(Gui::Document *doc, bool actsOnSelection )
{
    if (doc) {
        // checks if a Sketch Viewprovider is in Edit and is in no special mode
        if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) {
            if (static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit())
                ->getSketchMode() == ViewProviderSketch::STATUS_NONE) {
                if (!actsOnSelection)
                    return true;
                else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0)
                    return true;
            }
        }
    }

    return false;
}

void ActivateVirtualSpaceHandler(Gui::Document *doc,DrawSketchHandler *handler)
{
    if (doc) {
        if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom
           (SketcherGui::ViewProviderSketch::getClassTypeId())) {

            SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*> (doc->getInEdit());
            vp->purgeHandler();
            vp->activateHandler(handler);
        }
    }
}

// Show/Hide B-spline degree
DEF_STD_CMD_A(CmdSketcherSwitchVirtualSpace);

CmdSketcherSwitchVirtualSpace::CmdSketcherSwitchVirtualSpace()
:Command("Sketcher_SwitchVirtualSpace")
{
    sAppModule      = "Sketcher";
    sGroup          = QT_TR_NOOP("Sketcher");
    sMenuText       = QT_TR_NOOP("Switch virtual space");
    sToolTipText    = QT_TR_NOOP("Switches between the two virtual spaces");
    sWhatsThis      = "Sketcher_SwitchVirtualSpace";
    sStatusTip      = sToolTipText;
    sPixmap         = "Sketcher_SwitchVirtualSpace";
    sAccel          = "";
    eType           = ForEdit;
}

void CmdSketcherSwitchVirtualSpace::activated(int iMsg)
{
    Q_UNUSED(iMsg);

    Gui::Document * doc= getActiveGuiDocument();

    SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit());

    vp->setIsShownVirtualSpace(!vp->getIsShownVirtualSpace());

}

bool CmdSketcherSwitchVirtualSpace::isActive(void)
{
    return isSketcherVirtualSpaceActive( getActiveGuiDocument(), false );
}

void CreateSketcherCommandsVirtualSpace(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();

    rcCmdMgr.addCommand(new CmdSketcherSwitchVirtualSpace());
}
<commit_msg>Sketcher:  Switch virtual space toolbar button to operate on selection<commit_after>/***************************************************************************
 *   Copyright (c) 2017 Abdullah Tahiri <abdullah.tahiri.yo@gmail.com>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"
#ifndef _PreComp_
# include <cfloat>
# include <QMessageBox>
# include <Precision.hxx>
# include <QApplication>
# include <Standard_Version.hxx>
#endif

# include <QMessageBox>

#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/Document.h>
#include <Gui/Selection.h>
#include <Gui/Command.h>
#include <Gui/MainWindow.h>
#include <Gui/DlgEditFileIncludeProptertyExternal.h>

#include <Gui/Action.h>
#include <Gui/BitmapFactory.h>

#include "ViewProviderSketch.h"
#include "DrawSketchHandler.h"

#include <Mod/Part/App/Geometry.h>
#include <Mod/Sketcher/App/SketchObject.h>

#include "CommandConstraints.h"

using namespace std;
using namespace SketcherGui;
using namespace Sketcher;

bool isSketcherVirtualSpaceActive(Gui::Document *doc, bool actsOnSelection )
{
    if (doc) {
        // checks if a Sketch Viewprovider is in Edit and is in no special mode
        if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom(SketcherGui::ViewProviderSketch::getClassTypeId())) {
            if (static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit())
                ->getSketchMode() == ViewProviderSketch::STATUS_NONE) {
                if (!actsOnSelection)
                    return true;
                else if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0)
                    return true;
            }
        }
    }

    return false;
}

void ActivateVirtualSpaceHandler(Gui::Document *doc,DrawSketchHandler *handler)
{
    if (doc) {
        if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom
           (SketcherGui::ViewProviderSketch::getClassTypeId())) {

            SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*> (doc->getInEdit());
            vp->purgeHandler();
            vp->activateHandler(handler);
        }
    }
}

// Show/Hide B-spline degree
DEF_STD_CMD_A(CmdSketcherSwitchVirtualSpace);

CmdSketcherSwitchVirtualSpace::CmdSketcherSwitchVirtualSpace()
:Command("Sketcher_SwitchVirtualSpace")
{
    sAppModule      = "Sketcher";
    sGroup          = QT_TR_NOOP("Sketcher");
    sMenuText       = QT_TR_NOOP("Switch virtual space");
    sToolTipText    = QT_TR_NOOP("Switches the selected constraints or the view to the other virtual space");
    sWhatsThis      = "Sketcher_SwitchVirtualSpace";
    sStatusTip      = sToolTipText;
    sPixmap         = "Sketcher_SwitchVirtualSpace";
    sAccel          = "";
    eType           = ForEdit;
}

void CmdSketcherSwitchVirtualSpace::activated(int iMsg)
{
    Q_UNUSED(iMsg);
    bool modeChange=true;

    std::vector<Gui::SelectionObject> selection;

    if (Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0){
        // Now we check whether we have a constraint selected or not.

        // get the selection
        selection = getSelection().getSelectionEx();

        // only one sketch with its subelements are allowed to be selected
        if (selection.size() != 1) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
                                 QObject::tr("Select constraint(s) from the sketch."));
            return;
        }

        // get the needed lists and objects
        const std::vector<std::string> &SubNames = selection[0].getSubNames();
        if (SubNames.empty()) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
                                 QObject::tr("Select constraint(s) from the sketch."));
            return;
        }

        for (std::vector<std::string>::const_iterator it=SubNames.begin();it!=SubNames.end();++it){
            // see if we have constraints, if we do it is not a mode change, but a toggle.
            if (it->size() > 10 && it->substr(0,10) == "Constraint")
                modeChange=false;
        }
    }

    if (modeChange) {
        Gui::Document * doc= getActiveGuiDocument();

        SketcherGui::ViewProviderSketch* vp = static_cast<SketcherGui::ViewProviderSketch*>(doc->getInEdit());

        vp->setIsShownVirtualSpace(!vp->getIsShownVirtualSpace());
    }
    else // toggle the selected constraint(s)
    {
        // get the needed lists and objects
        const std::vector<std::string> &SubNames = selection[0].getSubNames();
        if (SubNames.empty()) {
            QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
                                 QObject::tr("Select constraint(s) from the sketch."));
            return;
        }

        SketcherGui::ViewProviderSketch* sketchgui = static_cast<SketcherGui::ViewProviderSketch*>(getActiveGuiDocument()->getInEdit());
        Sketcher::SketchObject* Obj = sketchgui->getSketchObject();

        // undo command open
        openCommand("Toggle constraints to the other virtual space");

        int successful=SubNames.size();
        // go through the selected subelements
        for (std::vector<std::string>::const_iterator it=SubNames.begin();it!=SubNames.end();++it){
            // only handle constraints
            if (it->size() > 10 && it->substr(0,10) == "Constraint") {
                int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it);
                Gui::Command::openCommand("Update constraint's virtual space");
                try {
                    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.toggleVirtualSpace(%d)",
                                            Obj->getNameInDocument(),
                                            ConstrId);
                }
                catch(const Base::Exception&) {
                    successful--;
                }
            }
        }

        if (successful > 0)
            commitCommand();
        else
            abortCommand();

        tryAutoRecompute();

        // clear the selection (convenience)
        getSelection().clearSelection();
    }
}

bool CmdSketcherSwitchVirtualSpace::isActive(void)
{
    return isSketcherVirtualSpaceActive( getActiveGuiDocument(), false );
}

void CreateSketcherCommandsVirtualSpace(void)
{
    Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();

    rcCmdMgr.addCommand(new CmdSketcherSwitchVirtualSpace());
}
<|endoftext|>


<commit_before>#include <ros/ros.h>

#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>

#include <interactive_markers/interactive_marker_server.h>
#include <interactive_markers/menu_handler.h>
#include <visualization_msgs/InteractiveMarkerInit.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>

#include <math.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <boost/program_options.hpp>

bool compareInteractiveMarker(visualization_msgs::InteractiveMarker left,
                              visualization_msgs::InteractiveMarker right)
{
  return std::stoi(left.name) < std::stoi(right.name);
}

class WaypointSaver
{
public:
  WaypointSaver(const std::string& waypoints_file):
    waypoints_file_(waypoints_file), saved_waypoints_(false)
  {
    ros::NodeHandle n;
    ROS_INFO("Waiting for waypoints");
    waypoints_sub_ = n.subscribe("/cube/update_full", 1, &WaypointSaver::pointsCallback, this);
  }

  void pointsCallback(visualization_msgs::InteractiveMarkerInit all_markers)
  {
    ROS_INFO("Received markers : %d", (int)all_markers.markers.size());
    std::ofstream savefile(waypoints_file_.c_str(), std::ios::out);
    std::sort(all_markers.markers.begin(), all_markers.markers.end(), compareInteractiveMarker);
    size_t size = all_markers.markers.size();
    for(unsigned int i = 0; i < size; i++){
      //３次元の位置の指定
      savefile << all_markers.markers[i].name << ","
               << all_markers.markers[i].pose.position.x << ","
               << all_markers.markers[i].pose.position.y << ","
               << 0 << ","
               << all_markers.markers[i].pose.orientation.x << ","
               << all_markers.markers[i].pose.orientation.y << ","
               << all_markers.markers[i].pose.orientation.z << ","
               << all_markers.markers[i].pose.orientation.w << std::endl;
    }
    saved_waypoints_ = true;
  }

  std::string waypoints_file_;
  ros::Subscriber waypoints_sub_;
  bool saved_waypoints_;
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "waypoint_saver");
  std::string waypoints_name = "points.csv";

  WaypointSaver saver(waypoints_name);
  while(!saver.saved_waypoints_ && ros::ok())
  {
    ros::spinOnce();
  }
  return 0;
}
<commit_msg>remove unnecessary information for waypoint<commit_after>#include <ros/ros.h>

#include <nav_msgs/Odometry.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>

#include <interactive_markers/interactive_marker_server.h>
#include <interactive_markers/menu_handler.h>
#include <visualization_msgs/InteractiveMarkerInit.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>

#include <math.h>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <boost/shared_array.hpp>
#include <boost/program_options.hpp>

bool compareInteractiveMarker(visualization_msgs::InteractiveMarker left,
                              visualization_msgs::InteractiveMarker right)
{
  return std::stoi(left.name) < std::stoi(right.name);
}

class WaypointSaver
{
public:
  WaypointSaver(const std::string& waypoints_file):
    waypoints_file_(waypoints_file), saved_waypoints_(false)
  {
    ros::NodeHandle n;
    ROS_INFO("Waiting for waypoints");
    waypoints_sub_ = n.subscribe("/cube/update_full", 1, &WaypointSaver::pointsCallback, this);
  }

  void pointsCallback(visualization_msgs::InteractiveMarkerInit all_markers)
  {
    ROS_INFO("Received markers : %d", (int)all_markers.markers.size());
    std::ofstream savefile(waypoints_file_.c_str(), std::ios::out);
    std::sort(all_markers.markers.begin(), all_markers.markers.end(), compareInteractiveMarker);
    size_t size = all_markers.markers.size();
    for(unsigned int i = 0; i < size; i++){
      //３次元の位置の指定
      savefile << all_markers.markers[i].pose.position.x << ","
               << all_markers.markers[i].pose.position.y << ","
               << 0 << ","
               << all_markers.markers[i].pose.orientation.x << ","
               << all_markers.markers[i].pose.orientation.y << ","
               << all_markers.markers[i].pose.orientation.z << ","
               << all_markers.markers[i].pose.orientation.w << std::endl;
    }
    saved_waypoints_ = true;
  }

  std::string waypoints_file_;
  ros::Subscriber waypoints_sub_;
  bool saved_waypoints_;
};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "waypoint_saver");
  std::string waypoints_name = "points.csv";

  WaypointSaver saver(waypoints_name);
  while(!saver.saved_waypoints_ && ros::ok())
  {
    ros::spinOnce();
  }
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 - 2016, Roland Bock
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *   Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *   Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "detail/prepared_statement_handle.h"
#include <ciso646>
#include <date.h>
#include <iostream>
#include <sqlpp11/exception.h>
#include <sqlpp11/sqlite3/prepared_statement.h>
#include <sstream>
#include <string>

#if defined(__CYGWIN__)
#include <sstream>

#ifdef SQLPP_DYNAMIC_LOADING
#include <sqlpp11/sqlite3/dynamic_libsqlite3.h>
#endif

// Workaround because cygwin gcc does not define to_string
namespace std
{
  template <typename T>
  std::string to_string(T t)
  {
    std::ostringstream stream;

    stream << t;
    return stream.str();
  }
}
#endif

namespace sqlpp
{
  namespace sqlite3
  {
#ifdef SQLPP_DYNAMIC_LOADING
   using namespace dynamic;
#endif
    namespace
    {
      void check_bind_result(int result, const char* const type)
      {
        switch (result)
        {
          case SQLITE_OK:
            return;
          case SQLITE_RANGE:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind value out of range");
          case SQLITE_NOMEM:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind out of memory");
          default:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind returned unexpected value: " +
                                   std::to_string(result));
        }
      }
    }

    prepared_statement_t::prepared_statement_t(std::shared_ptr<detail::prepared_statement_handle_t>&& handle)
        : _handle(std::move(handle))
    {
      if (_handle and _handle->debug)
        std::cerr << "Sqlite3 debug: Constructing prepared_statement, using handle at " << _handle.get() << std::endl;
    }

    void prepared_statement_t::_reset()
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: reseting prepared statement" << std::endl;
      sqlite3_reset(_handle->sqlite_statement);
    }

    void prepared_statement_t::_bind_boolean_parameter(size_t index, const signed char* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding boolean parameter " << (*value ? "true" : "false")
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_int(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "boolean");
    }

    void prepared_statement_t::_bind_floating_point_parameter(size_t index, const double* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding floating_point parameter " << *value << " at index: " << index
                  << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_double(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "floating_point");
    }

    void prepared_statement_t::_bind_integral_parameter(size_t index, const int64_t* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding integral parameter " << *value << " at index: " << index << ", being "
                  << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_int64(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "integral");
    }

    void prepared_statement_t::_bind_text_parameter(size_t index, const std::string* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding text parameter " << *value << " at index: " << index << ", being "
                  << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), value->data(),
                                   static_cast<int>(value->size()), SQLITE_STATIC);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "text");
    }

    void prepared_statement_t::_bind_date_parameter(size_t index, const ::sqlpp::chrono::day_point* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding date parameter "
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
      {
        std::ostringstream os;
        const auto ymd = ::date::year_month_day{*value};
        os << ymd;
        const auto text = os.str();
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), text.data(),
                                   static_cast<int>(text.size()), SQLITE_TRANSIENT);
      }
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "date");
    }

    void prepared_statement_t::_bind_date_time_parameter(size_t index,
                                                         const ::sqlpp::chrono::microsecond_point* value,
                                                         bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding date_time parameter "
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
      {
        const auto dp = ::sqlpp::chrono::floor<::date::days>(*value);
        const auto time = date::make_time(::sqlpp::chrono::floor<::std::chrono::milliseconds>(*value - dp));
        const auto ymd = ::date::year_month_day{dp};
        std::ostringstream os;  // gcc-4.9 does not support auto os = std::ostringstream{};
        os << ymd << ' ' << time;
        const auto text = os.str();
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), text.data(),
                                   static_cast<int>(text.size()), SQLITE_TRANSIENT);
      }
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "date");
    }
  }
}
<commit_msg>Fixed SQLPP_DYNAMIC_LOADING define which slipped into another ifdef<commit_after>/*
 * Copyright (c) 2013 - 2016, Roland Bock
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *   Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *   Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "detail/prepared_statement_handle.h"
#include <ciso646>
#include <date.h>
#include <iostream>
#include <sqlpp11/exception.h>
#include <sqlpp11/sqlite3/prepared_statement.h>
#include <sstream>
#include <string>

#if defined(__CYGWIN__)
#include <sstream>

// Workaround because cygwin gcc does not define to_string
namespace std
{
  template <typename T>
  std::string to_string(T t)
  {
    std::ostringstream stream;

    stream << t;
    return stream.str();
  }
}
#endif

#ifdef SQLPP_DYNAMIC_LOADING
#include <sqlpp11/sqlite3/dynamic_libsqlite3.h>
#endif

namespace sqlpp
{
  namespace sqlite3
  {
#ifdef SQLPP_DYNAMIC_LOADING
   using namespace dynamic;
#endif
    namespace
    {
      void check_bind_result(int result, const char* const type)
      {
        switch (result)
        {
          case SQLITE_OK:
            return;
          case SQLITE_RANGE:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind value out of range");
          case SQLITE_NOMEM:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind out of memory");
          default:
            throw sqlpp::exception("Sqlite3 error: " + std::string(type) + " bind returned unexpected value: " +
                                   std::to_string(result));
        }
      }
    }

    prepared_statement_t::prepared_statement_t(std::shared_ptr<detail::prepared_statement_handle_t>&& handle)
        : _handle(std::move(handle))
    {
      if (_handle and _handle->debug)
        std::cerr << "Sqlite3 debug: Constructing prepared_statement, using handle at " << _handle.get() << std::endl;
    }

    void prepared_statement_t::_reset()
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: reseting prepared statement" << std::endl;
      sqlite3_reset(_handle->sqlite_statement);
    }

    void prepared_statement_t::_bind_boolean_parameter(size_t index, const signed char* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding boolean parameter " << (*value ? "true" : "false")
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_int(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "boolean");
    }

    void prepared_statement_t::_bind_floating_point_parameter(size_t index, const double* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding floating_point parameter " << *value << " at index: " << index
                  << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_double(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "floating_point");
    }

    void prepared_statement_t::_bind_integral_parameter(size_t index, const int64_t* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding integral parameter " << *value << " at index: " << index << ", being "
                  << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_int64(_handle->sqlite_statement, static_cast<int>(index + 1), *value);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "integral");
    }

    void prepared_statement_t::_bind_text_parameter(size_t index, const std::string* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding text parameter " << *value << " at index: " << index << ", being "
                  << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), value->data(),
                                   static_cast<int>(value->size()), SQLITE_STATIC);
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "text");
    }

    void prepared_statement_t::_bind_date_parameter(size_t index, const ::sqlpp::chrono::day_point* value, bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding date parameter "
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
      {
        std::ostringstream os;
        const auto ymd = ::date::year_month_day{*value};
        os << ymd;
        const auto text = os.str();
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), text.data(),
                                   static_cast<int>(text.size()), SQLITE_TRANSIENT);
      }
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "date");
    }

    void prepared_statement_t::_bind_date_time_parameter(size_t index,
                                                         const ::sqlpp::chrono::microsecond_point* value,
                                                         bool is_null)
    {
      if (_handle->debug)
        std::cerr << "Sqlite3 debug: binding date_time parameter "
                  << " at index: " << index << ", being " << (is_null ? "" : "not ") << "null" << std::endl;

      int result;
      if (not is_null)
      {
        const auto dp = ::sqlpp::chrono::floor<::date::days>(*value);
        const auto time = date::make_time(::sqlpp::chrono::floor<::std::chrono::milliseconds>(*value - dp));
        const auto ymd = ::date::year_month_day{dp};
        std::ostringstream os;  // gcc-4.9 does not support auto os = std::ostringstream{};
        os << ymd << ' ' << time;
        const auto text = os.str();
        result = sqlite3_bind_text(_handle->sqlite_statement, static_cast<int>(index + 1), text.data(),
                                   static_cast<int>(text.size()), SQLITE_TRANSIENT);
      }
      else
        result = sqlite3_bind_null(_handle->sqlite_statement, static_cast<int>(index + 1));
      check_bind_result(result, "date");
    }
  }
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *  Copyright (C) 2008-2011 Massachusetts Institute of Technology            *
 *                                                                           *
 *  Permission is hereby granted, free of charge, to any person obtaining    *
 *  a copy of this software and associated documentation files (the          *
 *  "Software"), to deal in the Software without restriction, including      *
 *  without limitation the rights to use, copy, modify, merge, publish,      *
 *  distribute, sublicense, and/or sell copies of the Software, and to       *
 *  permit persons to whom the Software is furnished to do so, subject       *
 *  to the following conditions:                                             *
 *                                                                           *
 *  The above copyright notice and this permission notice shall be included  *
 *  in all copies or substantial portions of the Software.                   *
 *                                                                           *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY                *
 *  KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE               *
 *  WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND      *
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE   *
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION   *
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION    *
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE           *
 *                                                                           *
 *  This source code is part of the PetaBricks project:                      *
 *    http://projects.csail.mit.edu/petabricks/                              *
 *                                                                           *
 *****************************************************************************/
#include "gpumanager.h"

#include "dynamicscheduler.h"
#include "gpudynamictask.h"
#include "workerthread.h"

#include "common/openclutil.h"

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

//#define GPU_TRACE 1

#ifdef HAVE_OPENCL
static bool _useOpenCL() { return true; }
#else
static bool _useOpenCL() { return false; }
#endif

namespace petabricks {

typedef std::list<GpuDynamicTaskPtr>::iterator gpuTaskIter;

std::queue<GpuDynamicTaskPtr> GpuManager::_readytasks;
jalib::JMutex  GpuManager::_lock;
bool GpuManager::_shutdown = true;
pthread_t GpuManager::_thread;

GpuTaskInfoPtr GpuManager::_currenttaskinfo;
cl_kernel GpuManager::_kernel;

#ifdef HAVE_OPENCL
cl_command_queue GpuManager::_queue = OpenCLUtil::getQueue(0);
cl_context GpuManager::_context = OpenCLUtil::getContext();
#else
cl_command_queue GpuManager::_queue = -1;
cl_context GpuManager::_context = -1;
#endif

extern "C" void *startGpuManager(void* /*arg*/) {
  if(!_useOpenCL()) return NULL;
  //try {
  petabricks::WorkerThread::markUtilityThread();
  petabricks::GpuManager::mainLoop();
  //}catch(petabricks::DynamicScheduler::CleanExitException e){}
  return NULL;
}

void GpuManager::start() {
  if(!_useOpenCL()) return;
  if(!_shutdown) return;
  _shutdown = false;
  #ifdef GPU_TRACE
  std::cout << "pthead_create~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  #endif
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, 0);
  JASSERT(pthread_create(&_thread, &attr, startGpuManager, NULL) == 0);
  pthread_attr_destroy(&attr);
}

void GpuManager::shutdown() {
  if(!_useOpenCL()) return;
  if(_shutdown) return;
  _shutdown = true;
  int rv = pthread_join(_thread, NULL);
  JWARNING(rv==0)(rv).Text("pthread_join failed");
  OpenCLUtil::deinit();
  #ifdef GPU_TRACE
  std::cout << "pthead_join~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  #endif
}

void GpuManager::mainLoop() {
  if(!_useOpenCL()) return;
  for(;;){

    //TODO: whey do I have to use empty?
    bool empty = _readytasks.empty();
    while(!empty) {
      #ifdef GPU_TRACE
      std::cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>> START " << std::endl;
      #endif
      GpuDynamicTaskPtr task = _readytasks.front();
      _currenttaskinfo = task->taskinfo();
      int done = true;
      switch(task->tasktype()) {
        case GpuDynamicTask::PREPARE: prepare(task);        break;
        case GpuDynamicTask::COPYIN:  copyin(task);         break;
        case GpuDynamicTask::RUN:     run(task);            break;
        case GpuDynamicTask::COPYOUT: done = copyout(task); break;
      }
      #ifdef GPU_TRACE
      std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<< DONE" << std::endl;
      #endif
      _lock.lock();
      _readytasks.pop();
      if(!done)
        _readytasks.push(task);
      empty = _readytasks.empty();
      _lock.unlock();
    }

    if(_shutdown) {
      break;
    }
  }
}

void GpuManager::addTask(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  _lock.lock();
  _readytasks.push(task);
  _lock.unlock();
}

#ifndef HAVE_OPENCL

void GpuManager::prepare(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

void GpuManager::copyin(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

void GpuManager::run(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

bool GpuManager::copyout(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

#else

void GpuManager::prepare(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[PREPARE]" << std::endl;
  #endif
  task->runWrapper();
  #ifdef GPU_TRACE
  std::cout << "Number of From Matrices = " << _currenttaskinfo->_from.size() << std::endl;
  std::cout << "Number of To Matrices   = " << _currenttaskinfo->_to.size() << std::endl;
  #endif

  for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_to.begin(); i != _currenttaskinfo->_to.end(); ++i) {
    (*i)->initGpuMem(_queue,_context,false); // clCreateBuffer
  }
}

void GpuManager::copyin(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[COPY IN]" << std::endl;
  #endif
  MatrixStorageInfoPtr storageinfo = task->storageinfo();

  if(storageinfo->initGpuMem(_queue,_context,true)) { // clCreateBuffer
    #ifdef GPU_TRACE
    std::cout << "copying in... " << &(*storageinfo) << std::endl;
    #endif
    task->runWrapper(); // clEnqueueWriteBuffer
  }
  else {
    task->completeTaskDeps();
  }
}

void GpuManager::run(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[RUN]" << std::endl;
  #endif
  /*for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_from.begin(); i != _currenttaskinfo->_from.end(); ++i) {
    (*i)->check(_queue);
  }*/

  task->run();

  for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_to.begin(); i != _currenttaskinfo->_to.end(); ++i) {
    (*i)->finishGpuMem(_queue,_currenttaskinfo->nodeID(), _currenttaskinfo->regionNodeGroupMap(), _currenttaskinfo->gpuCopyOut()); // clEnqueueReadBuffer
  }
  task->completeTaskDeps();
}

bool GpuManager::copyout(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  MatrixStorageInfoPtr storage = task->storageinfo();
  #ifdef GPU_TRACE
  std::cout << "[COPY OUT]" << &(*storage) << std::endl;
  #endif

  CopyoutInfoPtr copyInfo = storage->getCopyoutInfo(_currenttaskinfo->nodeID());
  //TODO: still not totally right
  if(!copyInfo) {
    #ifdef GPU_TRACE
    std::cout << "not done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    return false;
  }
  if(copyInfo->done()) {
    #ifdef GPU_TRACE
    std::cout << "done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    task->completeTaskDeps();
    storage->done(_currenttaskinfo->nodeID());
    return true;
  }
  if(copyInfo->complete()) {
    #ifdef GPU_TRACE
    std::cout << "copy out... " << &(*storage) << std::endl;
    std::cout << "done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    task->setRegions(copyInfo->getBegins(), copyInfo->getEnds(), _currenttaskinfo->nodeID());
    task->runWrapper();
    storage->done(_currenttaskinfo->nodeID());
    return true;
  }
  #ifdef GPU_TRACE
  std::cout << "not done " << _currenttaskinfo->nodeID() << std::endl;
  #endif
  return false;
}

#endif

}

<commit_msg>compile with -Wall -Werror<commit_after>/*****************************************************************************
 *  Copyright (C) 2008-2011 Massachusetts Institute of Technology            *
 *                                                                           *
 *  Permission is hereby granted, free of charge, to any person obtaining    *
 *  a copy of this software and associated documentation files (the          *
 *  "Software"), to deal in the Software without restriction, including      *
 *  without limitation the rights to use, copy, modify, merge, publish,      *
 *  distribute, sublicense, and/or sell copies of the Software, and to       *
 *  permit persons to whom the Software is furnished to do so, subject       *
 *  to the following conditions:                                             *
 *                                                                           *
 *  The above copyright notice and this permission notice shall be included  *
 *  in all copies or substantial portions of the Software.                   *
 *                                                                           *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY                *
 *  KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE               *
 *  WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND      *
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE   *
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION   *
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION    *
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE           *
 *                                                                           *
 *  This source code is part of the PetaBricks project:                      *
 *    http://projects.csail.mit.edu/petabricks/                              *
 *                                                                           *
 *****************************************************************************/
#include "gpumanager.h"

#include "dynamicscheduler.h"
#include "gpudynamictask.h"
#include "workerthread.h"

#include "common/openclutil.h"

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

//#define GPU_TRACE 1

#ifdef HAVE_OPENCL
static bool _useOpenCL() { return true; }
#else
static bool _useOpenCL() { return false; }
#endif

namespace petabricks {

typedef std::list<GpuDynamicTaskPtr>::iterator gpuTaskIter;

std::queue<GpuDynamicTaskPtr> GpuManager::_readytasks;
jalib::JMutex  GpuManager::_lock;
bool GpuManager::_shutdown = true;
pthread_t GpuManager::_thread;

GpuTaskInfoPtr GpuManager::_currenttaskinfo;
cl_kernel GpuManager::_kernel;

#ifdef HAVE_OPENCL
cl_command_queue GpuManager::_queue = OpenCLUtil::getQueue(0);
cl_context GpuManager::_context = OpenCLUtil::getContext();
#else
cl_command_queue GpuManager::_queue = -1;
cl_context GpuManager::_context = -1;
#endif

extern "C" void *startGpuManager(void* /*arg*/) {
  if(!_useOpenCL()) return NULL;
  //try {
  petabricks::WorkerThread::markUtilityThread();
  petabricks::GpuManager::mainLoop();
  //}catch(petabricks::DynamicScheduler::CleanExitException e){}
  return NULL;
}

void GpuManager::start() {
  if(!_useOpenCL()) return;
  if(!_shutdown) return;
  _shutdown = false;
  #ifdef GPU_TRACE
  std::cout << "pthead_create~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  #endif
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, 0);
  JASSERT(pthread_create(&_thread, &attr, startGpuManager, NULL) == 0);
  pthread_attr_destroy(&attr);
}

void GpuManager::shutdown() {
  if(!_useOpenCL()) return;
  if(_shutdown) return;
  _shutdown = true;
  int rv = pthread_join(_thread, NULL);
  JWARNING(rv==0)(rv).Text("pthread_join failed");
  OpenCLUtil::deinit();
  #ifdef GPU_TRACE
  std::cout << "pthead_join~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  #endif
}

void GpuManager::mainLoop() {
  if(!_useOpenCL()) return;
  for(;;){

    //TODO: whey do I have to use empty?
    bool empty = _readytasks.empty();
    while(!empty) {
      #ifdef GPU_TRACE
      std::cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>> START " << std::endl;
      #endif
      GpuDynamicTaskPtr task = _readytasks.front();
      _currenttaskinfo = task->taskinfo();
      int done = true;
      switch(task->tasktype()) {
        case GpuDynamicTask::PREPARE: prepare(task);        break;
        case GpuDynamicTask::COPYIN:  copyin(task);         break;
        case GpuDynamicTask::RUN:     run(task);            break;
        case GpuDynamicTask::COPYOUT: done = copyout(task); break;
      }
      #ifdef GPU_TRACE
      std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<< DONE" << std::endl;
      #endif
      _lock.lock();
      _readytasks.pop();
      if(!done)
        _readytasks.push(task);
      empty = _readytasks.empty();
      _lock.unlock();
    }

    if(_shutdown) {
      break;
    }
  }
}

void GpuManager::addTask(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  _lock.lock();
  _readytasks.push(task);
  _lock.unlock();
}

#ifndef HAVE_OPENCL

void GpuManager::prepare(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

void GpuManager::copyin(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

void GpuManager::run(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
}

bool GpuManager::copyout(GpuDynamicTaskPtr ) {
  UNIMPLEMENTED();
  return false;
}

#else

void GpuManager::prepare(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[PREPARE]" << std::endl;
  #endif
  task->runWrapper();
  #ifdef GPU_TRACE
  std::cout << "Number of From Matrices = " << _currenttaskinfo->_from.size() << std::endl;
  std::cout << "Number of To Matrices   = " << _currenttaskinfo->_to.size() << std::endl;
  #endif

  for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_to.begin(); i != _currenttaskinfo->_to.end(); ++i) {
    (*i)->initGpuMem(_queue,_context,false); // clCreateBuffer
  }
}

void GpuManager::copyin(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[COPY IN]" << std::endl;
  #endif
  MatrixStorageInfoPtr storageinfo = task->storageinfo();

  if(storageinfo->initGpuMem(_queue,_context,true)) { // clCreateBuffer
    #ifdef GPU_TRACE
    std::cout << "copying in... " << &(*storageinfo) << std::endl;
    #endif
    task->runWrapper(); // clEnqueueWriteBuffer
  }
  else {
    task->completeTaskDeps();
  }
}

void GpuManager::run(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  #ifdef GPU_TRACE
  std::cout << "[RUN]" << std::endl;
  #endif
  /*for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_from.begin(); i != _currenttaskinfo->_from.end(); ++i) {
    (*i)->check(_queue);
  }*/

  task->run();

  for(std::vector<MatrixStorageInfoPtr>::iterator i = _currenttaskinfo->_to.begin(); i != _currenttaskinfo->_to.end(); ++i) {
    (*i)->finishGpuMem(_queue,_currenttaskinfo->nodeID(), _currenttaskinfo->regionNodeGroupMap(), _currenttaskinfo->gpuCopyOut()); // clEnqueueReadBuffer
  }
  task->completeTaskDeps();
}

bool GpuManager::copyout(GpuDynamicTaskPtr task) {
  JASSERT(_useOpenCL());
  MatrixStorageInfoPtr storage = task->storageinfo();
  #ifdef GPU_TRACE
  std::cout << "[COPY OUT]" << &(*storage) << std::endl;
  #endif

  CopyoutInfoPtr copyInfo = storage->getCopyoutInfo(_currenttaskinfo->nodeID());
  //TODO: still not totally right
  if(!copyInfo) {
    #ifdef GPU_TRACE
    std::cout << "not done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    return false;
  }
  if(copyInfo->done()) {
    #ifdef GPU_TRACE
    std::cout << "done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    task->completeTaskDeps();
    storage->done(_currenttaskinfo->nodeID());
    return true;
  }
  if(copyInfo->complete()) {
    #ifdef GPU_TRACE
    std::cout << "copy out... " << &(*storage) << std::endl;
    std::cout << "done " << _currenttaskinfo->nodeID() << std::endl;
    #endif
    task->setRegions(copyInfo->getBegins(), copyInfo->getEnds(), _currenttaskinfo->nodeID());
    task->runWrapper();
    storage->done(_currenttaskinfo->nodeID());
    return true;
  }
  #ifdef GPU_TRACE
  std::cout << "not done " << _currenttaskinfo->nodeID() << std::endl;
  #endif
  return false;
}

#endif

}

<|endoftext|>


<commit_before>#include "HalideRuntime.h"
#include "device_buffer_utils.h"

extern "C" {

WEAK int halide_msan_annotate_memory_is_initialized(void *user_context, const void *ptr, size_t len) {
    return 0;
}

WEAK int halide_msan_annotate_buffer_is_initialized(void *user_context, buffer_t *b) {
    return 0;
}

}
<commit_msg>remove unnecessary include<commit_after>#include "HalideRuntime.h"

extern "C" {

WEAK int halide_msan_annotate_memory_is_initialized(void *user_context, const void *ptr, size_t len) {
    return 0;
}

WEAK int halide_msan_annotate_buffer_is_initialized(void *user_context, buffer_t *b) {
    return 0;
}

}
<|endoftext|>


<commit_before>#include "mini_stdint.h"

#define WEAK __attribute__((weak))

extern "C" {

// To get at stderr, we need to know sizeof(FILE) on windows.
#ifdef BITS_64
#define FILE_SIZE 48
#else
#define FILE_SIZE 32
#endif

extern uint8_t *__iob_func();
extern int vfprintf(void *stream, const char *format, __builtin_va_list ap);

WEAK int halide_printf(const char * fmt, ...) {
    uint8_t *stderr = __iob_func() + FILE_SIZE;
    __builtin_va_list args;
    __builtin_va_start(args,fmt);
    int ret = vfprintf(stderr, fmt, args);
    __builtin_va_end(args);
    return ret;
}

}
<commit_msg>Actually stderr be stderr on windows.<commit_after>#include "mini_stdint.h"

#define WEAK __attribute__((weak))

extern "C" {

// To get at stderr, we need to know sizeof(FILE) on windows.
#ifdef BITS_64
#define FILE_SIZE 48
#else
#define FILE_SIZE 32
#endif

extern uint8_t *__iob_func();
extern int vfprintf(void *stream, const char *format, __builtin_va_list ap);

WEAK int halide_printf(const char * fmt, ...) {
    uint8_t *stderr = __iob_func() + FILE_SIZE*2;
    __builtin_va_list args;
    __builtin_va_start(args,fmt);
    int ret = vfprintf(stderr, fmt, args);
    __builtin_va_end(args);
    return ret;
}

}
<|endoftext|>


<commit_before>/*
 * CAnony_tests.cpp
 *
 *  Created on: 2015-04-24
 *      Author: frank
 */

#include "CAnony_tests.h"
#include "CycleTestManger.h"

CAnonyTest::CAnonyTest():nNum(0), nStep(0), strTxHash(""), strAppRegId(""),regId("") {
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) {
		string strArgv = boost::unit_test::framework::master_test_suite().argv[i];
		string::size_type pos = strArgv.find("-number=");
		if (string::npos != pos) {
			string strNum = strArgv.substr(pos + strlen("-number="), string::npos);
			nNum = Str2Int(strNum);
			break;
		}
	}
}

TEST_STATE CAnonyTest::Run(){
	switch(nStep){
	case 0:
	{
		if(RegistScript())
			nStep = 3;
		break;
	}
	case 1:
		if(CreateAnonyTx())
			nStep = 2;
		break;
	case 2:
		if(WaitComfirmed(strTxHash, regId)) {
			nStep = 1;
		}
		break;
	case 3:
		if(WaitComfirmed(strTxHash, strAppRegId)) {
			nStep = 1;
		}
		break;
	default:
		nStep = 1;
		break;
	}
	return next_state;
}

bool CAnonyTest::RegistScript(){
	string strFileName("anony.bin");
	int nFee = basetest.GetRandomFee();
	int nCurHight;
	basetest.GetBlockHeight(nCurHight);
	string regAddr="";
	if(!SelectOneAccount(regAddr))
		return false;
	//reg anony app
	Value regscript = basetest.RegisterAppTx(regAddr, strFileName, nCurHight, nFee+20*COIN);
	if(basetest.GetHashFromCreatedTx(regscript, strTxHash)){
		return true;
	}
	return false;
}

bool CAnonyTest::CreateAnonyTx(){
	srand(time(NULL));
	int nNum = (rand() % 3) + 3;
	vector<string> vRegId;
	string regId;
	std::pair<std::set<string>::iterator, bool> ret;
	for(int i=0; i< nNum;) {
		if(SelectOneAccount(regId)) {
			if(vRegId.end() == find(vRegId.begin(), vRegId.end(), regId)) {
				CRegID nRegid(regId);
				string strTemp = HexStr(nRegid.GetVec6());
				vRegId.push_back(strTemp);
				++i;
			}
		}
		else
			return false;
	}
	ACCOUNT_INFO accountInfo;
	int accountInfoSize = ::GetSerializeSize(accountInfo, SER_NETWORK, PROTOCOL_VERSION);
	unsigned short length = (nNum-1) * accountInfoSize;

	ACCOUNT_INFO pAccountInfo[nNum-1];
	memset(pAccountInfo, 0, length);

	vector<unsigned char> sendRegId = ParseHex(vRegId[0]);
	int64_t llSendTotal(0);
	for(int i=1; i<nNum; ++i) {
		vector<unsigned char> vTemp =ParseHex(vRegId[i]);
		memcpy(&accountInfo.account, &vTemp.at(0),vTemp.size());
		accountInfo.nReciMoney = i*100*COIN;
		llSendTotal += accountInfo.nReciMoney;
		pAccountInfo[i-1] = accountInfo;
		//memcpy(pAccountInfo+(i-1)*accountInfoSize, &accountInfo, accountInfoSize);
	}
	CONTRACT head;
	memcpy(head.Sender, &sendRegId.at(0), sendRegId.size());
	head.nPayMoney = llSendTotal;
	head.len = length;
	CDataStream ds(SER_DISK, CLIENT_VERSION);
	ds<<head;
	for(int i=1; i<nNum; ++i)
		ds<<pAccountInfo[i-1];

	string contract = HexStr(ds);
	Value  retValue = basetest.CreateContractTx(strAppRegId, vRegId[0], contract, 0, 0, llSendTotal);
	if(basetest.GetHashFromCreatedTx(retValue, strTxHash)){
			return true;
	}
	return false;
}

void CAnonyTest::Initialize(){
	CycleTestManger aCycleManager  = CycleTestManger::GetNewInstance();
	vector<std::shared_ptr<CycleTestBase> > vTest;
	if(0 == nNum) { //if don't have input param -number, default create 100 CCreateTxText instance defalue;
		nNum = 100;
	}
	for(int i=0; i< 1; ++i)
	{
		vTest.push_back(std::make_shared<CAnonyTest>());
	}
	aCycleManager.Initialize(vTest);
	aCycleManager.Run();
}

BOOST_FIXTURE_TEST_SUITE(CreateAnonyTxTest,CAnonyTest)

BOOST_FIXTURE_TEST_CASE(Test,CAnonyTest)
{
	Initialize();
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>modfiy test code<commit_after>/*
 * CAnony_tests.cpp
 *
 *  Created on: 2015-04-24
 *      Author: frank
 */

#include "CAnony_tests.h"
#include "CycleTestManger.h"

CAnonyTest::CAnonyTest():nNum(0), nStep(0), strTxHash(""), strAppRegId(""),regId("") {
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) {
		string strArgv = boost::unit_test::framework::master_test_suite().argv[i];
		string::size_type pos = strArgv.find("-number=");
		if (string::npos != pos) {
			string strNum = strArgv.substr(pos + strlen("-number="), string::npos);
			nNum = Str2Int(strNum);
			break;
		}
	}
}

TEST_STATE CAnonyTest::Run(){
	switch(nStep){
	case 0:
	{
		if(RegistScript())
			nStep = 2;
		break;
	}
	case 1:
		CreateAnonyTx();
		break;
	case 2:
		if(WaitComfirmed(strTxHash, strAppRegId)) {
			nStep = 1;
		}
		break;
	default:
		nStep = 1;
		break;
	}
	return next_state;
}

bool CAnonyTest::RegistScript(){
	string strFileName("anony.bin");
	int nFee = basetest.GetRandomFee();
	int nCurHight;
	basetest.GetBlockHeight(nCurHight);
	string regAddr="";
	if(!SelectOneAccount(regAddr))
		return false;
	//reg anony app
	Value regscript = basetest.RegisterAppTx(regAddr, strFileName, nCurHight, nFee+20*COIN);
	if(basetest.GetHashFromCreatedTx(regscript, strTxHash)){
		return true;
	}
	return false;
}

bool CAnonyTest::CreateAnonyTx(){
	srand(time(NULL));
	int nNum = (rand() % 3) + 3;
	vector<string> vRegId;
	string regId;
	std::pair<std::set<string>::iterator, bool> ret;
	for(int i=0; i< nNum;) {
		if(SelectOneAccount(regId)) {
			if(vRegId.end() == find(vRegId.begin(), vRegId.end(), regId)) {
				CRegID nRegid(regId);
				string strTemp = HexStr(nRegid.GetVec6());
				vRegId.push_back(strTemp);
				++i;
			}
		}
		else
			return false;
	}
	ACCOUNT_INFO accountInfo;
	int accountInfoSize = ::GetSerializeSize(accountInfo, SER_NETWORK, PROTOCOL_VERSION);
	unsigned short length = (nNum-1) * accountInfoSize;

	ACCOUNT_INFO pAccountInfo[nNum-1];
	memset(pAccountInfo, 0, length);

	vector<unsigned char> sendRegId = ParseHex(vRegId[0]);
	int64_t llSendTotal(0);
	for(int i=1; i<nNum; ++i) {
		vector<unsigned char> vTemp =ParseHex(vRegId[i]);
		memcpy(&accountInfo.account, &vTemp.at(0),vTemp.size());
		accountInfo.nReciMoney = i*100*COIN;
		llSendTotal += accountInfo.nReciMoney;
		pAccountInfo[i-1] = accountInfo;
		//memcpy(pAccountInfo+(i-1)*accountInfoSize, &accountInfo, accountInfoSize);
	}
	CONTRACT head;
	memcpy(head.Sender, &sendRegId.at(0), sendRegId.size());
	head.nPayMoney = llSendTotal;
	head.len = length;
	CDataStream ds(SER_DISK, CLIENT_VERSION);
	ds<<head;
	for(int i=1; i<nNum; ++i)
		ds<<pAccountInfo[i-1];

	string contract = HexStr(ds);
	Value  retValue = basetest.CreateContractTx(strAppRegId, vRegId[0], contract, 0, 0, llSendTotal);
	if(basetest.GetHashFromCreatedTx(retValue, strTxHash)){
			return true;
	}
	return false;
}

void CAnonyTest::Initialize(){
	CycleTestManger aCycleManager  = CycleTestManger::GetNewInstance();
	vector<std::shared_ptr<CycleTestBase> > vTest;
	if(0 == nNum) { //if don't have input param -number, default create 100 CCreateTxText instance defalue;
		nNum = 100;
	}
	for(int i=0; i< nNum; ++i)
	{
		vTest.push_back(std::make_shared<CAnonyTest>());
	}
	aCycleManager.Initialize(vTest);
	aCycleManager.Run();
}

BOOST_FIXTURE_TEST_SUITE(CreateAnonyTxTest,CAnonyTest)

BOOST_FIXTURE_TEST_CASE(Test,CAnonyTest)
{
	Initialize();
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>