<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"

#define PLATFORM_ALL                "all"
#define PLATFORM_WIN_X86            "windows_x86"
#define PLATFORM_LINUX_X86          "linux_x86"
#define PLATFORM_LINUX_X86_64       "linux_x86_64"
#define PLATFORM_KFREEBSD_X86       "kfreebsd_x86"
#define PLATFORM_KFREEBSD_X86_64    "kfreebsd_x86_64"
#define PLATFORM_LINUX_SPARC        "linux_sparc"
#define PLATFORM_LINUX_POWERPC      "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64    "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI     "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI     "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL      "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB      "linux_mips_eb"
#define PLATFORM_LINUX_IA64         "linux_ia64"
#define PLATFORM_LINUX_M68K         "linux_m68k"
#define PLATFORM_LINUX_S390         "linux_s390"
#define PLATFORM_LINUX_S390x        "linux_s390x"
#define PLATFORM_LINUX_HPPA         "linux_hppa"
#define PLATFORM_LINUX_ALPHA        "linux_alpha"

#define PLATFORM_SOLARIS_SPARC      "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64    "solaris_sparc64"
#define PLATFORM_SOLARIS_X86        "solaris_x86"
#define PLATFORM_FREEBSD_X86        "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64     "freebsd_x86_64"
#define PLATFORM_NETBSD_X86         "netbsd_x86"
#define PLATFORM_NETBSD_X86_64      "netbsd_x86_64"
#define PLATFORM_MACOSX_X86         "macosx_x86"
#define PLATFORM_MACOSX_PPC         "macosx_powerpc"
#define PLATFORM_OS2_X86            "os2_x86"
#define PLATFORM_OPENBSD_X86        "openbsd_x86"
#define PLATFORM_OPENBSD_X86_64     "openbsd_x86_64"
#define PLATFORM_DRAGONFLY_X86      "dragonfly_x86"
#define PLATFORM_DRAGONFLY_X86_64   "dragonfly_x86_64"

#define PLATFORM_AIX_POWERPC        "aix_powerpc"

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_misc
{
namespace
{
    struct StrOperatingSystem :
        public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
            const OUString operator () () {
                OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
                ::rtl::Bootstrap::expandMacros( os );
                return os;
            }
    };

    struct StrCPU :
        public rtl::StaticWithInit<const OUString, StrCPU> {
            const OUString operator () () {
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                return arch;
            }
    };

    struct StrPlatform : public rtl::StaticWithInit<
        const OUString, StrPlatform> {
            const OUString operator () () {
                ::rtl::OUStringBuffer buf;
                buf.append( StrOperatingSystem::get() );
                buf.append( static_cast<sal_Unicode>('_') );
                buf.append( StrCPU::get() );
                return buf.makeStringAndClear();
            }
    };

    bool checkOSandCPU(OUString const & os, OUString const & cpu)
    {
        return os.equals(StrOperatingSystem::get())
            && cpu.equals(StrCPU::get());
    }

    bool isValidPlatform(OUString const &  token )
    {
        bool ret = false;
        if (token.equals(OUSTR(PLATFORM_ALL)))
            ret = true;
        else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
            ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_M68K)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("M68K"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_NETBSD_X86)))
            ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_NETBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
            ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_AIX_POWERPC)))
            ret = checkOSandCPU(OUSTR("AIX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86)))
            ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86)))
            ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86_64)))
            ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("X86_64"));
        else
        {
            OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
            "Check the platform element in the description.xml");
            ret = false;
        }
        return ret;
    }

} // anon namespace
//=============================================================================

OUString const & getPlatformString()
{
    return StrPlatform::get();
}

bool platform_fits( OUString const & platform_string )
{
    sal_Int32 index = 0;
    for (;;)
    {
        const OUString token(
            platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
        {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
    bool ret = false;
    for (sal_Int32 i  = 0; i < platformStrings.getLength(); i++)
    {
        if (isValidPlatform(platformStrings[i]))
        {
            ret = true;
            break;
        }
    }
    return ret;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Add x64 Windows here, too<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "dp_misc.h"
#include "dp_platform.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/instance.hxx"
#include "rtl/bootstrap.hxx"

#define PLATFORM_ALL                "all"
#define PLATFORM_WIN_X86            "windows_x86"
#define PLATFORM_WIN_X86_64         "windows_x86_64"
#define PLATFORM_LINUX_X86          "linux_x86"
#define PLATFORM_LINUX_X86_64       "linux_x86_64"
#define PLATFORM_KFREEBSD_X86       "kfreebsd_x86"
#define PLATFORM_KFREEBSD_X86_64    "kfreebsd_x86_64"
#define PLATFORM_LINUX_SPARC        "linux_sparc"
#define PLATFORM_LINUX_POWERPC      "linux_powerpc"
#define PLATFORM_LINUX_POWERPC64    "linux_powerpc64"
#define PLATFORM_LINUX_ARM_EABI     "linux_arm_eabi"
#define PLATFORM_LINUX_ARM_OABI     "linux_arm_oabi"
#define PLATFORM_LINUX_MIPS_EL      "linux_mips_el"
#define PLATFORM_LINUX_MIPS_EB      "linux_mips_eb"
#define PLATFORM_LINUX_IA64         "linux_ia64"
#define PLATFORM_LINUX_M68K         "linux_m68k"
#define PLATFORM_LINUX_S390         "linux_s390"
#define PLATFORM_LINUX_S390x        "linux_s390x"
#define PLATFORM_LINUX_HPPA         "linux_hppa"
#define PLATFORM_LINUX_ALPHA        "linux_alpha"

#define PLATFORM_SOLARIS_SPARC      "solaris_sparc"
#define PLATFORM_SOLARIS_SPARC64    "solaris_sparc64"
#define PLATFORM_SOLARIS_X86        "solaris_x86"
#define PLATFORM_FREEBSD_X86        "freebsd_x86"
#define PLATFORM_FREEBSD_X86_64     "freebsd_x86_64"
#define PLATFORM_NETBSD_X86         "netbsd_x86"
#define PLATFORM_NETBSD_X86_64      "netbsd_x86_64"
#define PLATFORM_MACOSX_X86         "macosx_x86"
#define PLATFORM_MACOSX_PPC         "macosx_powerpc"
#define PLATFORM_OS2_X86            "os2_x86"
#define PLATFORM_OPENBSD_X86        "openbsd_x86"
#define PLATFORM_OPENBSD_X86_64     "openbsd_x86_64"
#define PLATFORM_DRAGONFLY_X86      "dragonfly_x86"
#define PLATFORM_DRAGONFLY_X86_64   "dragonfly_x86_64"

#define PLATFORM_AIX_POWERPC        "aix_powerpc"

#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_misc
{
namespace
{
    struct StrOperatingSystem :
        public rtl::StaticWithInit<const OUString, StrOperatingSystem> {
            const OUString operator () () {
                OUString os( RTL_CONSTASCII_USTRINGPARAM("$_OS") );
                ::rtl::Bootstrap::expandMacros( os );
                return os;
            }
    };

    struct StrCPU :
        public rtl::StaticWithInit<const OUString, StrCPU> {
            const OUString operator () () {
                OUString arch( RTL_CONSTASCII_USTRINGPARAM("$_ARCH") );
                ::rtl::Bootstrap::expandMacros( arch );
                return arch;
            }
    };

    struct StrPlatform : public rtl::StaticWithInit<
        const OUString, StrPlatform> {
            const OUString operator () () {
                ::rtl::OUStringBuffer buf;
                buf.append( StrOperatingSystem::get() );
                buf.append( static_cast<sal_Unicode>('_') );
                buf.append( StrCPU::get() );
                return buf.makeStringAndClear();
            }
    };

    bool checkOSandCPU(OUString const & os, OUString const & cpu)
    {
        return os.equals(StrOperatingSystem::get())
            && cpu.equals(StrCPU::get());
    }

    bool isValidPlatform(OUString const &  token )
    {
        bool ret = false;
        if (token.equals(OUSTR(PLATFORM_ALL)))
            ret = true;
        else if (token.equals(OUSTR(PLATFORM_WIN_X86)))
            ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_WIN_X86_64)))
            ret = checkOSandCPU(OUSTR("Windows"), OUSTR("x86_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_X86_64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_KFREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("kFreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_SPARC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_POWERPC64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("PowerPC_64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_EABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_EABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ARM_OABI)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ARM_OABI"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EL)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EL"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_MIPS_EB)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("MIPS_EB"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_IA64)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("IA64"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_M68K)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("M68K"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_S390x)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("S390x"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_HPPA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("HPPA"));
        else if (token.equals(OUSTR(PLATFORM_LINUX_ALPHA)))
            ret = checkOSandCPU(OUSTR("Linux"), OUSTR("ALPHA"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_SPARC64)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("SPARC64"));
        else if (token.equals(OUSTR(PLATFORM_SOLARIS_X86)))
            ret = checkOSandCPU(OUSTR("Solaris"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_FREEBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("FreeBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_NETBSD_X86)))
            ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_NETBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("NetBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_X86)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_MACOSX_PPC)))
            ret = checkOSandCPU(OUSTR("MacOSX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OS2_X86)))
            ret = checkOSandCPU(OUSTR("OS2"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_AIX_POWERPC)))
            ret = checkOSandCPU(OUSTR("AIX"), OUSTR("PowerPC"));
        else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86)))
            ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_OPENBSD_X86_64)))
            ret = checkOSandCPU(OUSTR("OpenBSD"), OUSTR("X86_64"));
        else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86)))
            ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("x86"));
        else if (token.equals(OUSTR(PLATFORM_DRAGONFLY_X86_64)))
            ret = checkOSandCPU(OUSTR("DragonFly"), OUSTR("X86_64"));
        else
        {
            OSL_ENSURE(0, "Extension Manager: The extension supports an unknown platform. "
            "Check the platform element in the description.xml");
            ret = false;
        }
        return ret;
    }

} // anon namespace
//=============================================================================

OUString const & getPlatformString()
{
    return StrPlatform::get();
}

bool platform_fits( OUString const & platform_string )
{
    sal_Int32 index = 0;
    for (;;)
    {
        const OUString token(
            platform_string.getToken( 0, ',', index ).trim() );
        // check if this platform:
        if (token.equalsIgnoreAsciiCase( StrPlatform::get() ) ||
            (token.indexOf( '_' ) < 0 && /* check OS part only */
             token.equalsIgnoreAsciiCase( StrOperatingSystem::get() )))
        {
            return true;
        }
        if (index < 0)
            break;
    }
    return false;
}

bool hasValidPlatform( css::uno::Sequence<OUString> const & platformStrings)
{
    bool ret = false;
    for (sal_Int32 i  = 0; i < platformStrings.getLength(); i++)
    {
        if (isValidPlatform(platformStrings[i]))
        {
            ret = true;
            break;
        }
    }
    return ret;
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//===-- Hexagon.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "InputFiles.h"
#include "Symbols.h"
#include "Target.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Endian.h"

using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;

namespace {
class Hexagon final : public TargetInfo {
public:
  uint32_t calcEFlags() const override;
  RelExpr getRelExpr(RelType Type, const Symbol &S,
                     const uint8_t *Loc) const override;
  void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override;
};
} // namespace

// Support V60 only at the moment.
uint32_t Hexagon::calcEFlags() const { return 0x60; }

static uint32_t applyMask(uint32_t Mask, uint32_t Data) {
  uint32_t Result = 0;
  size_t Off = 0;

  for (size_t Bit = 0; Bit != 32; ++Bit) {
    uint32_t ValBit = (Data >> Off) & 1;
    uint32_t MaskBit = (Mask >> Bit) & 1;
    if (MaskBit) {
      Result |= (ValBit << Bit);
      ++Off;
    }
  }
  return Result;
}

RelExpr Hexagon::getRelExpr(RelType Type, const Symbol &S,
                            const uint8_t *Loc) const {
  switch (Type) {
  case R_HEX_B15_PCREL:
  case R_HEX_B15_PCREL_X:
  case R_HEX_B22_PCREL:
  case R_HEX_B22_PCREL_X:
  case R_HEX_B32_PCREL_X:
  case R_HEX_6_PCREL_X:
    return R_PC;
  default:
    return R_ABS;
  }
}

static uint32_t findMaskR6(uint32_t Insn) {
  // There are (arguably too) many relocation masks for the DSP's
  // R_HEX_6_X type.  The table below is used to select the correct mask
  // for the given instruction.
  struct InstructionMask {
    uint32_t CmpMask;
    uint32_t RelocMask;
  };

  static const InstructionMask R6[] = {
      {0x38000000, 0x0000201f}, {0x39000000, 0x0000201f},
      {0x3e000000, 0x00001f80}, {0x3f000000, 0x00001f80},
      {0x40000000, 0x000020f8}, {0x41000000, 0x000007e0},
      {0x42000000, 0x000020f8}, {0x43000000, 0x000007e0},
      {0x44000000, 0x000020f8}, {0x45000000, 0x000007e0},
      {0x46000000, 0x000020f8}, {0x47000000, 0x000007e0},
      {0x6a000000, 0x00001f80}, {0x7c000000, 0x001f2000},
      {0x9a000000, 0x00000f60}, {0x9b000000, 0x00000f60},
      {0x9c000000, 0x00000f60}, {0x9d000000, 0x00000f60},
      {0x9f000000, 0x001f0100}, {0xab000000, 0x0000003f},
      {0xad000000, 0x0000003f}, {0xaf000000, 0x00030078},
      {0xd7000000, 0x006020e0}, {0xd8000000, 0x006020e0},
      {0xdb000000, 0x006020e0}, {0xdf000000, 0x006020e0}};

  // Duplex forms have a fixed mask and parse bits 15:14 are always
  // zero.  Non-duplex insns will always have at least one bit set in the
  // parse field.
  if ((0xC000 & Insn) == 0x0)
    return 0x03f00000;

  for (InstructionMask I : R6)
    if ((0xff000000 & Insn) == I.CmpMask)
      return I.RelocMask;

  error("unrecognized instruction for R_HEX_6 relocation: 0x" +
        utohexstr(Insn));
  return 0;
}

static uint32_t findMaskR8(uint32_t Insn) {
  if ((0xff000000 & Insn) == 0xde000000)
    return 0x00e020e8;
  if ((0xff000000 & Insn) == 0x3c000000)
    return 0x0000207f;
  return 0x00001fe0;
}

static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }

void Hexagon::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const {
  switch (Type) {
  case R_HEX_NONE:
    break;
  case R_HEX_6_PCREL_X:
  case R_HEX_6_X:
    or32le(Loc, applyMask(findMaskR6(read32le(Loc)), Val));
    break;
  case R_HEX_8_X:
    or32le(Loc, applyMask(findMaskR8(read32le(Loc)), Val));
    break;
  case R_HEX_12_X:
    or32le(Loc, applyMask(0x000007e0, Val));
    break;
  case R_HEX_32:
    or32le(Loc, applyMask(0xffffffff, Val));
    break;
  case R_HEX_32_6_X:
    or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
    break;
  case R_HEX_B15_PCREL:
    or32le(Loc, applyMask(0x00df20fe, Val >> 2));
    break;
  case R_HEX_B15_PCREL_X:
    or32le(Loc, applyMask(0x00df20fe, Val & 0x3f));
    break;
  case R_HEX_B22_PCREL:
    or32le(Loc, applyMask(0x1ff3ffe, Val >> 2));
    break;
  case R_HEX_B22_PCREL_X:
    or32le(Loc, applyMask(0x1ff3ffe, Val & 0x3f));
    break;
  case R_HEX_B32_PCREL_X:
    or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
    break;
  case R_HEX_HI16:
    or32le(Loc, applyMask(0x00c03fff, Val >> 16));
    break;
  case R_HEX_LO16:
    or32le(Loc, applyMask(0x00c03fff, Val));
    break;
  default:
    error(getErrorLocation(Loc) + "unrecognized reloc " + toString(Type));
    break;
  }
}

TargetInfo *elf::getHexagonTargetInfo() {
  static Hexagon Target;
  return &Target;
}
<commit_msg>Remove unnecessary applyMask() application.<commit_after>//===-- Hexagon.cpp -------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "InputFiles.h"
#include "Symbols.h"
#include "Target.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/Object/ELF.h"
#include "llvm/Support/Endian.h"

using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::ELF;
using namespace lld;
using namespace lld::elf;

namespace {
class Hexagon final : public TargetInfo {
public:
  uint32_t calcEFlags() const override;
  RelExpr getRelExpr(RelType Type, const Symbol &S,
                     const uint8_t *Loc) const override;
  void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override;
};
} // namespace

// Support V60 only at the moment.
uint32_t Hexagon::calcEFlags() const { return 0x60; }

static uint32_t applyMask(uint32_t Mask, uint32_t Data) {
  uint32_t Result = 0;
  size_t Off = 0;

  for (size_t Bit = 0; Bit != 32; ++Bit) {
    uint32_t ValBit = (Data >> Off) & 1;
    uint32_t MaskBit = (Mask >> Bit) & 1;
    if (MaskBit) {
      Result |= (ValBit << Bit);
      ++Off;
    }
  }
  return Result;
}

RelExpr Hexagon::getRelExpr(RelType Type, const Symbol &S,
                            const uint8_t *Loc) const {
  switch (Type) {
  case R_HEX_B15_PCREL:
  case R_HEX_B15_PCREL_X:
  case R_HEX_B22_PCREL:
  case R_HEX_B22_PCREL_X:
  case R_HEX_B32_PCREL_X:
  case R_HEX_6_PCREL_X:
    return R_PC;
  default:
    return R_ABS;
  }
}

static uint32_t findMaskR6(uint32_t Insn) {
  // There are (arguably too) many relocation masks for the DSP's
  // R_HEX_6_X type.  The table below is used to select the correct mask
  // for the given instruction.
  struct InstructionMask {
    uint32_t CmpMask;
    uint32_t RelocMask;
  };

  static const InstructionMask R6[] = {
      {0x38000000, 0x0000201f}, {0x39000000, 0x0000201f},
      {0x3e000000, 0x00001f80}, {0x3f000000, 0x00001f80},
      {0x40000000, 0x000020f8}, {0x41000000, 0x000007e0},
      {0x42000000, 0x000020f8}, {0x43000000, 0x000007e0},
      {0x44000000, 0x000020f8}, {0x45000000, 0x000007e0},
      {0x46000000, 0x000020f8}, {0x47000000, 0x000007e0},
      {0x6a000000, 0x00001f80}, {0x7c000000, 0x001f2000},
      {0x9a000000, 0x00000f60}, {0x9b000000, 0x00000f60},
      {0x9c000000, 0x00000f60}, {0x9d000000, 0x00000f60},
      {0x9f000000, 0x001f0100}, {0xab000000, 0x0000003f},
      {0xad000000, 0x0000003f}, {0xaf000000, 0x00030078},
      {0xd7000000, 0x006020e0}, {0xd8000000, 0x006020e0},
      {0xdb000000, 0x006020e0}, {0xdf000000, 0x006020e0}};

  // Duplex forms have a fixed mask and parse bits 15:14 are always
  // zero.  Non-duplex insns will always have at least one bit set in the
  // parse field.
  if ((0xC000 & Insn) == 0x0)
    return 0x03f00000;

  for (InstructionMask I : R6)
    if ((0xff000000 & Insn) == I.CmpMask)
      return I.RelocMask;

  error("unrecognized instruction for R_HEX_6 relocation: 0x" +
        utohexstr(Insn));
  return 0;
}

static uint32_t findMaskR8(uint32_t Insn) {
  if ((0xff000000 & Insn) == 0xde000000)
    return 0x00e020e8;
  if ((0xff000000 & Insn) == 0x3c000000)
    return 0x0000207f;
  return 0x00001fe0;
}

static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); }

void Hexagon::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const {
  switch (Type) {
  case R_HEX_NONE:
    break;
  case R_HEX_6_PCREL_X:
  case R_HEX_6_X:
    or32le(Loc, applyMask(findMaskR6(read32le(Loc)), Val));
    break;
  case R_HEX_8_X:
    or32le(Loc, applyMask(findMaskR8(read32le(Loc)), Val));
    break;
  case R_HEX_12_X:
    or32le(Loc, applyMask(0x000007e0, Val));
    break;
  case R_HEX_32:
    or32le(Loc, Val);
    break;
  case R_HEX_32_6_X:
    or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
    break;
  case R_HEX_B15_PCREL:
    or32le(Loc, applyMask(0x00df20fe, Val >> 2));
    break;
  case R_HEX_B15_PCREL_X:
    or32le(Loc, applyMask(0x00df20fe, Val & 0x3f));
    break;
  case R_HEX_B22_PCREL:
    or32le(Loc, applyMask(0x1ff3ffe, Val >> 2));
    break;
  case R_HEX_B22_PCREL_X:
    or32le(Loc, applyMask(0x1ff3ffe, Val & 0x3f));
    break;
  case R_HEX_B32_PCREL_X:
    or32le(Loc, applyMask(0x0fff3fff, Val >> 6));
    break;
  case R_HEX_HI16:
    or32le(Loc, applyMask(0x00c03fff, Val >> 16));
    break;
  case R_HEX_LO16:
    or32le(Loc, applyMask(0x00c03fff, Val));
    break;
  default:
    error(getErrorLocation(Loc) + "unrecognized reloc " + toString(Type));
    break;
  }
}

TargetInfo *elf::getHexagonTargetInfo() {
  static Hexagon Target;
  return &Target;
}
<|endoftext|>


<commit_before>#include "ResourceManager.h"
#include <string>
#include <vector>
#ifdef __MACH__
#include <CoreFoundation/CoreFoundation.h>
#endif

namespace ResourceManager
{

namespace Internal
{

std::vector<std::string> searchPaths;
std::string userDirectoryPath;

bool FileExists ( const std::string& path )
{
	return false;
}

}

using namespace Internal;

// utility function for reading from a RWops in full
void* ReadFull ( size_t* length, SDL_RWops* ops, int autoclose )
{
	size_t len = SDL_RWseek(ops, 0, SEEK_END);
	*length = len;
	SDL_RWseek(ops, 0, SEEK_SET);
	void* buffer = malloc(len);
	SDL_RWread(ops, buffer, 1, len);
	if (autoclose)
		SDL_RWclose(ops);
	return buffer;
}

SDL_RWops* OpenFile ( const std::string& name )
{
	for (std::vector<std::string>::iterator iter = searchPaths.begin(); iter != searchPaths.end(); iter++)
	{
		std::string fullPath = (*iter) + '/' + name;
		if (FileExists(fullPath))
		{
			return SDL_RWFromFile(fullPath.c_str(), "r");
		}
	}
	return NULL;
}

void WriteFile ( const std::string& name, const void* data, size_t len )
{
	std::string path = userDirectoryPath + '/' + name;
	FILE* fp = fopen(path.c_str(), "rb");
	assert(fp);
	fwrite(data, 1, len, fp);
	fclose(fp);
}

void Init ()
{
	searchPaths.clear();
#ifdef __MACH__
	char systemDirectory[1024];
	char userDirectory[1024];
	sprintf(userDirectory, "%s/Library/Application Support/Xsera", getenv("HOME"));
	CFBundleRef mainBundle = CFBundleGetMainBundle();
	CFURLRef resourcePath = CFBundleCopyResourcesDirectoryURL(mainBundle);
	CFURLGetFileSystemRepresentation(resourcePath, 1, (Uint8*)systemDirectory, sizeof(systemDirectory));
	CFRelease(resourcePath);
	searchPaths.push_back(systemDirectory);
	searchPaths.push_back(userDirectory);
	userDirectoryPath = userDirectory;
#endif
}

}
<commit_msg>Finished resource manager.<commit_after>#include "ResourceManager.h"
#include <string>
#include <vector>
#ifdef __MACH__
#include <CoreFoundation/CoreFoundation.h>
#endif

namespace ResourceManager
{

namespace Internal
{

std::vector<std::string> searchPaths;
std::string userDirectoryPath;

bool FileExists ( const std::string& path )
{
	FILE* fp = fopen(path.c_str(), "rb");
	if (fp)
		fclose(fp);
	return fp != NULL;
}

}

using namespace Internal;

// utility function for reading from a RWops in full
void* ReadFull ( size_t* length, SDL_RWops* ops, int autoclose )
{
	size_t len = SDL_RWseek(ops, 0, SEEK_END);
	*length = len;
	SDL_RWseek(ops, 0, SEEK_SET);
	void* buffer = malloc(len);
	SDL_RWread(ops, buffer, 1, len);
	if (autoclose)
		SDL_RWclose(ops);
	return buffer;
}

SDL_RWops* OpenFile ( const std::string& name )
{
	for (std::vector<std::string>::iterator iter = searchPaths.begin(); iter != searchPaths.end(); iter++)
	{
		std::string fullPath = (*iter) + '/' + name;
		if (FileExists(fullPath))
		{
			return SDL_RWFromFile(fullPath.c_str(), "r");
		}
	}
	return NULL;
}

void WriteFile ( const std::string& name, const void* data, size_t len )
{
	std::string path = userDirectoryPath + '/' + name;
	FILE* fp = fopen(path.c_str(), "rb");
	assert(fp);
	fwrite(data, 1, len, fp);
	fclose(fp);
}

void Init ()
{
	searchPaths.clear();
#ifdef __MACH__
	char systemDirectory[1024];
	char userDirectory[1024];
	sprintf(userDirectory, "%s/Library/Application Support/Xsera", getenv("HOME"));
	CFBundleRef mainBundle = CFBundleGetMainBundle();
	CFURLRef resourcePath = CFBundleCopyResourcesDirectoryURL(mainBundle);
	CFURLGetFileSystemRepresentation(resourcePath, 1, (Uint8*)systemDirectory, sizeof(systemDirectory));
	CFRelease(resourcePath);
	searchPaths.push_back(systemDirectory);
	searchPaths.push_back(userDirectory);
	userDirectoryPath = userDirectory;
#endif
}

}
<|endoftext|>


<commit_before>#include "../tjh_draw.h"

const int WIDTH = 640;
const int HEIGHT = 480;

float clamp( float v, float min, float max )
{
	float vmin = min < max ? min : max;
	float vmax = max > min ? max : min;
	if( v < vmin ) return vmin;
	if( v > vmax ) return vmax;
	return v;
}

int main()
{
	draw::init( __FILE__, 640, 480 );

	float x = 100;
	float y = 100;
	float xSpeed = 2;
	float ySpeed = 2;
	float size = 50;

	bool done = false;
	SDL_Event event;
	while( !done )
	{
		while( SDL_PollEvent( &event ) )
		{
			if( event.type == SDL_QUIT ) done = true;
		}
		draw::clear(0.1, 0.1, 0.1);

		draw::setColor( 0.5, 0.5, 0.5 );
		draw::rectangle( x, y, size, size );

		x += xSpeed;
		float newx = clamp(x, 0, WIDTH - size);
		if( newx != x )
		{
			x = newx;
			xSpeed *= -1;
		}

		y += ySpeed;
		float newy = clamp(y, 0, HEIGHT - size);
		if( newy != y )
		{
			y = newy;
			ySpeed *= -1;
		}

		draw::flush();
		draw::present();
	}

	draw::shutdown();
	return 0;
}

#define TJH_DRAW_IMPLEMENTATION
#include "../tjh_draw.h"<commit_msg>rename functions for new draw.h<commit_after>#include "../tjh_draw.h"

const int WIDTH = 640;
const int HEIGHT = 480;

float clamp( float v, float min, float max )
{
	float vmin = min < max ? min : max;
	float vmax = max > min ? max : min;
	if( v < vmin ) return vmin;
	if( v > vmax ) return vmax;
	return v;
}

int main()
{
	draw::init( __FILE__, 640, 480 );

	float x = 100;
	float y = 100;
	float xSpeed = 2;
	float ySpeed = 2;
	float size = 50;

	bool done = false;
	SDL_Event event;
	while( !done )
	{
		while( SDL_PollEvent( &event ) )
		{
			if( event.type == SDL_QUIT ) done = true;
		}
		draw::clear(0.1, 0.1, 0.1);

		draw::setColor( 0.5, 0.5, 0.5 );
		draw::rect( x, y, size, size );

		x += xSpeed;
		float newx = clamp(x, 0, WIDTH - size);
		if( newx != x )
		{
			x = newx;
			xSpeed *= -1;
		}

		y += ySpeed;
		float newy = clamp(y, 0, HEIGHT - size);
		if( newy != y )
		{
			y = newy;
			ySpeed *= -1;
		}

		draw::flush();
		draw::present();
	}

	draw::shutdown();
	return 0;
}

#define TJH_DRAW_IMPLEMENTATION
#include "../tjh_draw.h"<|endoftext|>


<commit_before>#include <fstream>
#include "get-cluster.h"
using namespace cv;
using namespace std;

int main(int argc, char* argv[]){
    if (argc < 3){
		cout << "Usage: " << endl
			<< "IntrinsicImage.exe [-i input_image_path] [-o output_path]" << endl;
        exit(-1);
    }
    string image_path;
    string region_file_path;
    string mask_file_path;
    string output_path;
    for (int i = 1; i < argc; i = i + 2){
        if (strcmp(argv[i], "-i") == 0){
            image_path = string(argv[i+1]);
            cout << "image_path: " << image_path << endl;
        }
        else if (strcmp(argv[i], "-r") == 0){
            region_file_path = string(argv[i + 1]);
            cout << "region_file_path: " << region_file_path << endl;
        }
        else if (strcmp(argv[i], "-m") == 0){
            mask_file_path = string(argv[i + 1]);
        }
        else if (strcmp(argv[i], "-o") == 0){
            output_path = string(argv[i + 1]);
            cout << "output_path: " << output_path << endl;
        }
    }

    Mat_<Vec3b> image = imread(image_path);
    int image_width = image.cols;
    int image_height = image.rows;
    Mat_<Vec3b> lab_image(image_height, image_width);
    Mat_<int> region(image_height, image_width, 1); // not used now
    int expected_cluster_num = 500;
    Mat_<int> mask(image_height, image_width, 1); // not used now

    // transform into lab color space
    cvtColor(image, lab_image, CV_BGR2Lab);

    if(region_file_path.empty() == false){
        ifstream fin;
        fin.open(region_file_path);
        for (int i = 0; i < image_height; i++){
            for (int j = 0; j < image_width; j++){
                fin >> region(i, j);
            }
        }
        expected_cluster_num = 3000;
    }

    if(mask_file_path.empty() == false){
        Mat_<uchar> temp = imread(mask_file_path);
        mask = temp > 200;
    }

    Mat_<Vec3d> project_image = Mat_<Vec3d>(lab_image);
    double l_ratio = 0.3;
    for (int i = 0; i < image_height; i++){
        for (int j = 0; j < image_width; j++){
            project_image(i, j)[0] *= 0.3;
        }
    }

    double sigma = 0;
    double c = 500; // 1.0
    int min_size = 5;
    int cluster_num = 0;
    Mat_<Vec3b> output;
    Mat_<int> label;

    cout << "Segment the image..." << endl;
    GetReflectanceCluster(project_image, sigma, c, min_size, &cluster_num,
            output, label, expected_cluster_num, region);
    cout << "Super-pixel num: " << cluster_num << endl;

    ofstream fout;
    fout.open(output_path);
    fout << cv::format(label, cv::Formatter::FMT_CSV) << endl;

    return 0;
}
<commit_msg>rm: main file<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"

#include "core/svg/SVGCursorElement.h"

#include "core/SVGNames.h"
#include "core/XLinkNames.h"

namespace blink {

inline SVGCursorElement::SVGCursorElement(Document& document)
    : SVGElement(SVGNames::cursorTag, document)
    , SVGTests(this)
    , SVGURIReference(this)
    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths))
    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths))
{
    addToPropertyMap(m_x);
    addToPropertyMap(m_y);
}

DEFINE_NODE_FACTORY(SVGCursorElement)

SVGCursorElement::~SVGCursorElement()
{
    // The below teardown is all handled by weak pointer processing in oilpan.
#if !ENABLE(OILPAN)
    for (auto& client : m_clients)
        client->cursorElementRemoved();
#endif
}

bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName)
{
    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
    if (supportedAttributes.isEmpty()) {
        SVGTests::addSupportedAttributes(supportedAttributes);
        SVGURIReference::addSupportedAttributes(supportedAttributes);
        supportedAttributes.add(SVGNames::xAttr);
        supportedAttributes.add(SVGNames::yAttr);
    }
    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}

void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    parseAttributeNew(name, value);
}

void SVGCursorElement::addClient(SVGElement* element)
{
    m_clients.add(element);
    element->setCursorElement(this);
}

#if !ENABLE(OILPAN)
void SVGCursorElement::removeClient(SVGElement* element)
{
    HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element);
    if (it != m_clients.end()) {
        m_clients.remove(it);
        element->cursorElementRemoved();
    }
}
#endif

void SVGCursorElement::removeReferencedElement(SVGElement* element)
{
    m_clients.remove(element);
}

void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName)
{
    if (!isSupportedAttribute(attrName)) {
        SVGElement::svgAttributeChanged(attrName);
        return;
    }

    SVGElement::InvalidationGuard invalidationGuard(this);

    // Any change of a cursor specific attribute triggers this recalc.
    for (auto& client : m_clients)
        client->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::SVGCursor));
}

void SVGCursorElement::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_clients);
#endif
    SVGElement::trace(visitor);
}

} // namespace blink
<commit_msg>Oilpan: fix build after r183736.<commit_after>/*
 * Copyright (C) 2004, 2005, 2006, 2008 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"

#include "core/svg/SVGCursorElement.h"

#include "core/SVGNames.h"
#include "core/XLinkNames.h"

namespace blink {

inline SVGCursorElement::SVGCursorElement(Document& document)
    : SVGElement(SVGNames::cursorTag, document)
    , SVGTests(this)
    , SVGURIReference(this)
    , m_x(SVGAnimatedLength::create(this, SVGNames::xAttr, SVGLength::create(LengthModeWidth), AllowNegativeLengths))
    , m_y(SVGAnimatedLength::create(this, SVGNames::yAttr, SVGLength::create(LengthModeHeight), AllowNegativeLengths))
{
    addToPropertyMap(m_x);
    addToPropertyMap(m_y);
}

DEFINE_NODE_FACTORY(SVGCursorElement)

SVGCursorElement::~SVGCursorElement()
{
    // The below teardown is all handled by weak pointer processing in oilpan.
#if !ENABLE(OILPAN)
    for (const auto& client : m_clients)
        client->cursorElementRemoved();
#endif
}

bool SVGCursorElement::isSupportedAttribute(const QualifiedName& attrName)
{
    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
    if (supportedAttributes.isEmpty()) {
        SVGTests::addSupportedAttributes(supportedAttributes);
        SVGURIReference::addSupportedAttributes(supportedAttributes);
        supportedAttributes.add(SVGNames::xAttr);
        supportedAttributes.add(SVGNames::yAttr);
    }
    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}

void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    parseAttributeNew(name, value);
}

void SVGCursorElement::addClient(SVGElement* element)
{
    m_clients.add(element);
    element->setCursorElement(this);
}

#if !ENABLE(OILPAN)
void SVGCursorElement::removeClient(SVGElement* element)
{
    HashSet<RawPtr<SVGElement> >::iterator it = m_clients.find(element);
    if (it != m_clients.end()) {
        m_clients.remove(it);
        element->cursorElementRemoved();
    }
}
#endif

void SVGCursorElement::removeReferencedElement(SVGElement* element)
{
    m_clients.remove(element);
}

void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName)
{
    if (!isSupportedAttribute(attrName)) {
        SVGElement::svgAttributeChanged(attrName);
        return;
    }

    SVGElement::InvalidationGuard invalidationGuard(this);

    // Any change of a cursor specific attribute triggers this recalc.
    for (const auto& client : m_clients)
        client->setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::SVGCursor));
}

void SVGCursorElement::trace(Visitor* visitor)
{
#if ENABLE(OILPAN)
    visitor->trace(m_clients);
#endif
    SVGElement::trace(visitor);
}

} // namespace blink
<|endoftext|>


<commit_before>/*
 * classes_io.cpp
 *
 *  Created on: May 11, 2016
 *      Author: zmij
 */

#include <gtest/gtest.h>

#include <test/classes_for_io.hpp>
#include <wire/encoding/buffers.hpp>

namespace wire {
namespace encoding {
namespace test {

TEST(IO, Polymorphic)
{
    ::test::derived_ptr inst1 = ::std::make_shared< ::test::derived >();
    inst1->fvalue = 3.14;
    inst1->svalue = "inst1";
    inst1->ivalue = 100500;

    ::test::derived_ptr inst2 = ::std::make_shared< ::test::derived >();
    inst2->fvalue = 2.718;
    inst2->svalue = "inst2";
    inst2->bvalue = inst1;
    inst2->ivalue = 42;

    ::test::derived_ptr inst3 = ::std::make_shared< ::test::derived >();
    inst3->fvalue = 2.718 * 3.14;
    inst3->svalue = "inst3";
    inst3->bvalue = inst1;
    inst3->ivalue = 13;

    ::test::base_ptr b1 = inst2;
    ::test::base_ptr b2 = inst3;

    outgoing out{ core::connector_ptr{} };
    {
        write(::std::back_inserter(out), b1, b2);
        out.close_all_encaps();
        ::std::cerr << "Out buffer size " << out.size() << "\n";
        out.debug_print(::std::cerr);
    }

    incoming in{ message{}, ::std::move(out) };
    {
        b1.reset();
        b2.reset();

        auto encaps = in.current_encapsulation();
        auto b = encaps.begin();
        auto e = encaps.end();
        read(b, e, b1, b2);
        encaps.read_indirection_table(b);

        EXPECT_TRUE(b1.get());
        EXPECT_TRUE(b2.get());
    }
}

}  /* namespace test */
}  /* namespace encoding */
}  /* namespace wire */

<commit_msg>Tests for polymorphic I/O<commit_after>/*
 * classes_io.cpp
 *
 *  Created on: May 11, 2016
 *      Author: zmij
 */

#include <gtest/gtest.h>

#include <test/classes_for_io.hpp>
#include <wire/encoding/buffers.hpp>

namespace wire {
namespace encoding {
namespace test {

TEST(IO, Polymorphic)
{
    outgoing out{ core::connector_ptr{} };
    {
        ::test::derived_ptr inst1 = ::std::make_shared< ::test::derived >();
        inst1->fvalue = 3.14;
        inst1->svalue = "inst1";
        inst1->ivalue = 100500;

        ::test::derived_ptr inst2 = ::std::make_shared< ::test::derived >();
        inst2->fvalue = 2.718;
        inst2->svalue = "inst2";
        inst2->bvalue = inst1;
        inst2->ivalue = 42;

        ::test::derived_ptr inst3 = ::std::make_shared< ::test::derived >();
        inst3->fvalue = 2.718 * 3.14;
        inst3->svalue = "inst3";
        inst3->bvalue = inst1;
        inst3->ivalue = 13;

        ::test::base_ptr b1 = inst2;
        ::test::base_ptr b2 = inst3;

        write(::std::back_inserter(out), b1, b2);
        out.close_all_encaps();
        ::std::cerr << "Out buffer size " << out.size() << "\n";
        out.debug_print(::std::cerr);
    }

    incoming in{ message{}, ::std::move(out) };
    {
        ::test::base_ptr b1;
        ::test::base_ptr b2;

        auto encaps = in.current_encapsulation();
        auto b = encaps.begin();
        auto e = encaps.end();
        read(b, e, b1, b2);
        encaps.read_indirection_table(b);

        ASSERT_TRUE(b1.get());
        ASSERT_TRUE(b2.get());

        auto d1 = ::std::dynamic_pointer_cast<::test::derived>(b1);
        auto d2 = ::std::dynamic_pointer_cast<::test::derived>(b2);

        ASSERT_TRUE(d1.get());
        ASSERT_TRUE(d2.get());
        EXPECT_TRUE(d1->bvalue.get());

        EXPECT_EQ(d1->bvalue, d2->bvalue);
    }
}

}  /* namespace test */
}  /* namespace encoding */
}  /* namespace wire */

<|endoftext|>


<commit_before>#include <thread>
#include <utility>
#include <istream>

#include "database.hpp"
#include "ui.hpp"
#include "searching.hpp"

using namespace magicSearchEngine;
using namespace std;

int
main(int argc, char *argv[]) {
    JSONDatabase database;
    search_engine oraculum(database);
    // We expect enough space between running this program and writing the first
    // command within its interface. So for fluency, we run a new thread doing
    // expensive methods separately and after command processing we only check,
    // that the user was not too fast. In case, we join the thread and simply wait.
    thread data_loading([&]() {
        database.load_database();
        oraculum.create_index();
    });
    console cmd_ui(cin);

    while (true) {
        auto command = cmd_ui.get_cmd();
        switch (command.first) {
            case cmd::error:
            case cmd::parse_error:
                cmd_ui.bad_input();
            case cmd::end_of_input:
            case cmd::exit:
                return 0;
            case cmd::none:
                this_thread::yield();
                break;
            case cmd::find:
            {
                if (!database.is_ready()) {
                    data_loading.join();
                }
                auto res = oraculum.search_for(command.second[1]);
                if (res == nullptr) {
                    cout << "Demanded card was not found." << endl;
                }
                else {
                    cout << *(res) << endl;
                }
                break;
            }
            case cmd::similar:
            {
                if (!database.is_ready()) {
                    data_loading.join();
                }
                auto && res = oraculum.find_similar(command.second[1], 3);
                if (res.size() == 0) {
                    cout << "Demanded card was not found." << endl;
                }
                for (auto && card : res) {
                    cout << *card << endl;
                }
            }
            default:
                this_thread::yield();
                break;
        }
    }
}
<commit_msg>[src/main.cpp] Script mode added, docopt.cpp used.<commit_after>#include <thread>
#include <utility>
#include <istream>
#include <map>

#include "database.hpp"
#include "ui.hpp"
#include "searching.hpp"
#include "../docopt.cpp/docopt.h"

using namespace magicSearchEngine;
using namespace std;

static const char USAGE[] =
        R"(Magic Search Engine.

    Usage:
      MagicSearchEngine find <name>
      MagicSearchEngine similar <name> [<number>]
      MagicSearchEngine (-h | --help)
      MagicSearchEngine --interactive
      MagicSearchEngine --version

    Options:
      <number>          Number of cards returned [default: 3].
      -h --help         Show this screen.
      --interactive     Run interactive mode (type 'help' there).
      --version         Show version.
)";

static const char USAGE_INTERACTIVE[] =
        R"(Magic Search Engine, interactive mode.

    Usage:
      find <name>
      similar <name> [<number>]
      MagicSearchEngine (h | help)

    Options:
      <number>          Number of cards returned [default: 3].
      -h --help         Show this screen.
)";

inline void
find(const JSONDatabase & database,
        search_engine & oraculum,
        thread & data_loading,
        const string & name) {
    if (!database.is_ready()) {
        data_loading.join();
    }
    auto res = oraculum.search_for(name);
    if (res == nullptr) {
        cout << "Demanded card was not found." << endl;
    }
    else {
        cout << *(res) << endl;
    }
}

inline void
similar(const JSONDatabase & database,
        search_engine & oraculum,
        thread & data_loading,
        const string & name,
        const string & count) {
    // Parsing count.
    int cnt = 1;
    try {
        cnt = stoi(count);
        if (cnt < 1) {
            cout << "Number must be a positive integer." << endl;
            return;
        }
    }
    catch (...) {
        cout << USAGE << endl;
        return;
    }
    // Is db loaded?
    if (!database.is_ready()) {
        data_loading.join();
    }
    // Searching.
    vector<const Card *> res;
    res = oraculum.find_similar(name, cnt); // Here cnt is >= 1.
    if (res.size() == 0) {
        cout << "Demanded card was not found." << endl;
    }
    else {
        for (const Card * card : res) {
            cout << (*card) << endl;
        }
    }
}

inline void
interactive_mode(const JSONDatabase & database,
        search_engine & oraculum,
        thread & data_loading) {
    console cmd_ui(cin);
    while (true) {
        const auto & c = cmd_ui.get_cmd();
        switch (c.first) {
            case cmd::error:
            case cmd::parse_error:
                cout << "Error while parsing last input. Use command \"help\"." << endl;
            case cmd::help:
                cout << USAGE_INTERACTIVE << endl;
                break;
            case cmd::end_of_input:
            case cmd::exit:
                return;
            case cmd::none:
                this_thread::yield();
                break;
            case cmd::find:
            {
                find(database, oraculum, data_loading, c.second[1]);
                break;
            }
            case cmd::similar:
            {
                if (c.second.size() == 2)
                    similar(database, oraculum, data_loading, c.second[1], "3");
                else
                    similar(database, oraculum, data_loading, c.second[1], c.second[2]);
                break;
            }
            default:
                this_thread::yield();
                break;
        }
    }
}

int
main(int argc, char * argv[]) {
    JSONDatabase database;
    search_engine oraculum(database);
    // We expect enough space between running this program and writing the first
    // command in interactive mode. So for fluency, we run a new thread doing
    // expensive methods separately and after command processing we only check,
    // that the user was not too fast. In case, we join the thread and simply wait.
    thread data_loading([&]() {
        database.load_database();
        oraculum.create_index();
    });

    map<string, docopt::value> args = docopt::docopt(USAGE,{argv + 1, argv + argc},
    true, // show help if requested
    "Magic Search Engine 1.0"); // version string

    if (args["find"].asBool()) {
        find(database, oraculum, data_loading, args["<name>"].asString());
    }
    else if (args["similar"].asBool()) {
        if (!args["<number>"]) {
            similar(database, oraculum, data_loading, args["<name>"].asString(), "3");
        }
        else {
            similar(database, oraculum, data_loading, args["<name>"].asString(), args["<number>"].asString());
        }
    }
    else if (args["--interactive"].asBool()) {
        interactive_mode(database, oraculum, data_loading);
    }

    // Avoiding destruction of detachable thread in case of script mode with
    // wrong input parameters (i.g. negative number). In this way detached
    // thread is killed with main() instead of terminating program with thread
    // exception.
    if (data_loading.joinable())
        data_loading.detach();

    return 0;
}
<|endoftext|>


<commit_before>

/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California
 *    Jan Issac (jan.issac@gmail.com)
 *    Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 *
 *
 *  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.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  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 OWNER 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.
 *
 */

/**
 * @date 2014
 * @author Jan Issac (jan.issac@gmail.com)
 * Max-Planck-Institute for Intelligent Systems, University of Southern California
 */

#include <gtest/gtest.h>

#include <fl/exception/exception.hpp>
#include <fl/filter/gaussian/point_set.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>

TEST(Exception, create)
{
    struct FirstWeight
    {
        double w;
        std::string name;
    };

    typedef fl::PointSet<Eigen::Matrix<double, 1, 1>, -1> SigmaPointGaussian;
    SigmaPointGaussian sigmas(1);

    try
    {
        sigmas.point(0, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
        sigmas.point(1, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
        sigmas.point(2, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
    }
    catch(fl::OutOfBoundsException& e) { }
    catch(...)
    {
        ADD_FAILURE();
    }
}

TEST(Exception, OutOfBoundsException_default_construction)
{
    fl::OutOfBoundsException e;
//    EXPECT_NE(
//        std::string(e.what()).find("Index out of bounds"),
//        std::string::npos);

    try {
        fl_throw(fl::OutOfBoundsException());
    } catch (fl::Exception& e) {
        std::cout << e.what() << std::endl;
    }
}

TEST(Exception, OutOfBoundsException_index)
{
    fl::OutOfBoundsException e(10);
//    EXPECT_NE(
//        std::string(e.what()).find("Index[10] out of bounds"),
//        std::string::npos);

    try {
        fl_throw(e);
    } catch (fl::Exception& e) {
        std::cout << e.what() << std::endl;
    }
}

TEST(Exception, OutOfBoundsException_index_size)
{
    fl::OutOfBoundsException e(10, 8);
    EXPECT_NE(
        std::string(e.what()).find("Index[10] out of bounds [0, 8)"),
        std::string::npos);

    try {
        fl_throw(e);
    } catch (fl::Exception& e) {
        std::cout << e.what() << std::endl;
    }
}
<commit_msg>Updated exception tests<commit_after>

/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California
 *    Jan Issac (jan.issac@gmail.com)
 *    Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 *
 *
 *  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.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  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 OWNER 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.
 *
 */

/**
 * @date 2014
 * @author Jan Issac (jan.issac@gmail.com)
 * Max-Planck-Institute for Intelligent Systems, University of Southern California
 */

#include <gtest/gtest.h>

#include <fl/exception/exception.hpp>
#include <fl/filter/gaussian/point_set.hpp>
#include <fl/filter/gaussian/gaussian_filter.hpp>

TEST(Exception, create)
{
    struct FirstWeight
    {
        double w;
        std::string name;
    };

    typedef fl::PointSet<Eigen::Matrix<double, 1, 1>, -1> SigmaPointGaussian;
    SigmaPointGaussian sigmas(1);

    try
    {
        sigmas.point(0, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
        sigmas.point(1, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
        sigmas.point(2, Eigen::Matrix<double, 1, 1>::Random(), {1.23, 1.24});
    }
    catch(fl::OutOfBoundsException& e) { }
    catch(...)
    {
        ADD_FAILURE();
    }
}

TEST(Exception, OutOfBoundsException_default_construction)
{
    fl::OutOfBoundsException e;
    EXPECT_NE(
        std::string(e.what()).find("Index out of bounds"),
        std::string::npos);

//    try {
//        fl_throw(fl::OutOfBoundsException());
//    } catch (fl::Exception& e) {
//        std::cout << e.what() << std::endl;
//    }
}

TEST(Exception, OutOfBoundsException_index)
{
    fl::OutOfBoundsException e(10);
    EXPECT_NE(
        std::string(e.what()).find("Index[10] out of bounds"),
        std::string::npos);

//    try {
//        fl_throw(e);
//    } catch (fl::Exception& e) {
//        std::cout << e.what() << std::endl;
//    }
}

TEST(Exception, OutOfBoundsException_index_size)
{
    fl::OutOfBoundsException e(10, 8);
    EXPECT_NE(
        std::string(e.what()).find("Index[10] out of bounds [0, 8)"),
        std::string::npos);

//    try {
//        fl_throw(e);
//    } catch (fl::Exception& e) {
//        std::cout << e.what() << std::endl;
//    }
}
<|endoftext|>


<commit_before>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[]) {
    /*! Initialize options list.
     */

    bool verbose = false;
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
    ("iterations,n",opt::value<int>(), "Number of iterations")
    ("help","Show help message")
    ("verbose,v", "Show extensive debugging info")
    ("output,o", opt::value<int>(), "Output style.");
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

    if (vmap.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    verbose = vmap.count("verbose");

    int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;

    if (verbose) {
      print(iterations);
      #pragma omp parallel
      #pragma omp single
      print(omp_get_num_threads());
    }

    OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, output_style);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {
    boost::timer::auto_cpu_timer t;

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations];

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            histogram[systems[k].endingBitString]++;
        }

        #pragma omp single nowait
        delete [] systems;

        #pragma omp for nowait
        for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
            int setBits = bitCount(k,BIT_STREAM_LENGTH);
            p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
            p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
        }

        #pragma omp single nowait
        delete [] histogram;

	#pragma omp barrier

        //Make sure we don't accidentally share a seed.

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }

        #pragma omp single nowait
        {
            delete [] p_prime;
            delete [] p;
            if(type==CommaSeparated) {
                static int once = 0;
                if (!once) {
                    std::cout<<"delta,epsilon,avg,max_surprise\n";
                    once=1;
                }
                std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
            }
            if(type==PrettyPrint) {
                print(beta);
                print(constants.delta);
                print(constants.epsilon);
                print(sum/iterations);
                print(max_surprise);
                print(sum);
                std::cout<<std::endl;
            }

            if (type==Mathematica) {
                assert(0);
            }
        }
	gsl_rng_free(localRNG);
    }
}
<commit_msg>Parallelize at higher granularity.<commit_after>//
//  main.cpp
//  thermaleraser
//
//  Created by Mark Larus on 9/8/12.
//  Copyright (c) 2012 Kenyon College. All rights reserved.
//

#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>

#include "States.h"
#include "System.h"
#include "Utilities.h"

#define print(x) std::cout<<#x <<": " <<x<<std::endl;

namespace opt = boost::program_options;

enum OutputType {
    CommaSeparated,
    PrettyPrint,
    Mathematica,
    NoOutput
};

void simulate_and_print(Constants constants, int iterations, OutputType type);

int main(int argc, char * argv[]) {
    /*! Initialize options list.
     */

    bool verbose = false;
    const int default_iterations = 1<<16;

    opt::options_description desc("Allowed options");
    desc.add_options()
    ("iterations,n",opt::value<int>(), "Number of iterations")
    ("help","Show help message")
    ("verbose,v", "Show extensive debugging info")
    ("output,o", opt::value<int>(), "Output style.");
    ;

    opt::variables_map vmap;
    opt::store(opt::parse_command_line(argc,argv,desc),vmap);
    opt::notify(vmap);

    if (vmap.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    verbose = vmap.count("verbose");

    int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;

    if (verbose) {
        print(iterations);
        #pragma omp parallel
        #pragma omp single
        print(omp_get_num_threads());
    }

    OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;

    /*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
     represented by an object with pointers to the next states and the bit-flip states. */
    setupStates();

    Constants constants;

    /*! The delta used here is NOT, at this point, the delta used in the paper. This is the
     ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
     calculating this at runtime is just an invitation for bugs. */
    constants.delta = .5;
    constants.epsilon = .7;
    constants.tau = 1;
    int dimension = 50;
    #pragma omp parallel for private(constants)
    for (int k=dimension*dimension; k>=0; k--) {
        constants.epsilon = (k % dimension)/(double)(dimension);
        constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
        simulate_and_print(constants, iterations, output_style);
    }

}

void simulate_and_print(Constants constants, int iterations, OutputType type) {

    /*! Use this to change the length of the tape. */
    const int BIT_STREAM_LENGTH = 8;

    int first_pass_iterations = iterations;

    System *systems = new System[first_pass_iterations];

    int *histogram = new int[1<<BIT_STREAM_LENGTH];
    std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);

    long double *p = new long double[1<<BIT_STREAM_LENGTH];
    long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
    long double sum = 0;

    const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
    long double max_surprise = 0;
    long double min_surprise = LONG_MAX;

    #pragma omp parallel
    {
        //TODO: Move this into a semaphore in the utility function
        gsl_rng *localRNG = GSLRandomNumberGenerator();

        #pragma omp for
        for (int k=0; k<first_pass_iterations; ++k) {
            System *currentSystem = systems+k;

            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            histogram[systems[k].endingBitString]++;
        }

        #pragma omp single nowait
        delete [] systems;

        #pragma omp for nowait
        for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
            int setBits = bitCount(k,BIT_STREAM_LENGTH);
            p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
            p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
        }

        #pragma omp single nowait
        delete [] histogram;

        #pragma omp barrier

        #pragma omp for reduction(+ : sum)
        for(int k=0; k<iterations; k++) {
            System *currentSystem = new System();
            currentSystem->constants = constants;
            currentSystem->nbits = BIT_STREAM_LENGTH;

            evolveSystem(currentSystem, localRNG);

            long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
            max_surprise = surprise > max_surprise ? surprise : max_surprise;
            min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
            sum = sum + surprise;
            delete currentSystem;
        }

        #pragma omp single nowait
        {
            delete [] p_prime;
            delete [] p;
        }

        #pragma omp critical
        {
            if(type==CommaSeparated) {
                static int once = 0;
                if (!once) {
                    std::cout<<"delta,epsilon,avg,max_surprise\n";
                    once=1;
                }
                std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
            }
            if(type==PrettyPrint) {
                print(beta);
                print(constants.delta);
                print(constants.epsilon);
                print(sum/iterations);
                print(max_surprise);
                print(sum);
                std::cout<<std::endl;
            }

            if (type==Mathematica) {
                assert(0);
            }
        }
        gsl_rng_free(localRNG);
    }
}
<|endoftext|>


<commit_before>/*
vc_crt_fix_ulink.cpp

Workaround for Visual C++ CRT incompatibility with old Windows versions (ulink version)
*/
/*
Copyright © 2010 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "disable_warnings_in_std_begin.hpp"
#include <windows.h>
#include "disable_warnings_in_std_end.hpp"
#include <delayimp.h>

//----------------------------------------------------------------------------
static LPVOID WINAPI no_recode_pointer(LPVOID p)
{
    return p;
}

//----------------------------------------------------------------------------
static FARPROC WINAPI delayFailureHook(/*dliNotification*/unsigned dliNotify,
                                       PDelayLoadInfo pdli)
{
    if(   dliNotify == /*dliFailGetProcAddress*/dliFailGetProc
       && pdli && pdli->cb == sizeof(*pdli)
       && pdli->hmodCur == GetModuleHandleA("kernel32")
       && pdli->dlp.fImportByName && pdli->dlp.szProcName
       && (   !lstrcmpA(pdli->dlp.szProcName, "EncodePointer")
           || !lstrcmpA(pdli->dlp.szProcName, "DecodePointer")))
    {
      return (FARPROC)no_recode_pointer;
    }
    return nullptr;
}

//----------------------------------------------------------------------------
#if _MSC_FULL_VER >= 190024215 // VS2015sp3
const
#endif
PfnDliHook __pfnDliFailureHook2 = (PfnDliHook)delayFailureHook;

//----------------------------------------------------------------------------

// TODO: Add GetModuleHandleExW
<commit_msg>remove compiler warning (VS2017.6)<commit_after>/*
vc_crt_fix_ulink.cpp

Workaround for Visual C++ CRT incompatibility with old Windows versions (ulink version)
*/
/*
Copyright © 2010 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "disable_warnings_in_std_begin.hpp"
#include <windows.h>
#include "disable_warnings_in_std_end.hpp"
#include <delayimp.h>

//----------------------------------------------------------------------------
static LPVOID WINAPI no_recode_pointer(LPVOID p)
{
    return p;
}

//----------------------------------------------------------------------------
static FARPROC WINAPI delayFailureHook(/*dliNotification*/unsigned dliNotify,
                                       PDelayLoadInfo pdli)
{
    if(   dliNotify == /*dliFailGetProcAddress*/dliFailGetProc
       && pdli && pdli->cb == sizeof(*pdli)
       && pdli->hmodCur == GetModuleHandleA("kernel32")
       && pdli->dlp.fImportByName && pdli->dlp.szProcName
       && (   !lstrcmpA(pdli->dlp.szProcName, "EncodePointer")
           || !lstrcmpA(pdli->dlp.szProcName, "DecodePointer")))
    {
#pragma warning(disable: 4191)  // unsafe conversion from...to
      return (FARPROC)no_recode_pointer;
#pragma warning(default: 4191)
    }
    return nullptr;
}

//----------------------------------------------------------------------------
#if _MSC_FULL_VER >= 190024215 // VS2015sp3
const
#endif
PfnDliHook __pfnDliFailureHook2 = (PfnDliHook)delayFailureHook;

//----------------------------------------------------------------------------

// TODO: Add GetModuleHandleExW
<|endoftext|>


<commit_before>#ifndef UNIT_TEST
#include <Arduino.h>
#include <avr/wdt.h>
#include <DHT.h>
#include <TimerOne.h>
#include "lib/SDCard.h"
#include "PinMap.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
// #include "test/bmp.test.h"

SoftwareSerial gpsSerial(9, 10);

DHT dht(DHTPIN, DHTTYPE);
SDCard sd(SD_PIN);
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
TinyGPSPlus gps;

float lat = 0.00;
float lng = 0.00;

float hum = 0;
float tmp = 0;
float hid = 0;

int mq7 = 0;
int mq2 = 0;
int mq135 = 0;

int readMQ(int pin) {
    int value = analogRead(pin);
    if (isnan(value)) {
        return -1;
    } else {
        return value;
    }
}

void serialize(char* fmt) {
    sprintf(fmt, "{mq7:%i,mq2:%i,mq135:%i,hum:%i,tmp:%i,hid:%i;}", mq7, mq2, mq135, (int)hum, (int)tmp, (int)(hid+0.5));
}

void callback() {
    mq7 = readMQ(MQ7PIN);
    char foo [64];
    sprintf(foo, "%d", mq7);
    // Serial.println(foo);
    // mq2 = readMQ(MQ2PIN);
    // mq135 = readMQ(MQ135PIN);
    // hid = dht.computeHeatIndex(tmp, hum, false);
    //
    // char fmt [64];
    // serialize(fmt);
    // if (Serial.available()) {
    //     Serial.println(fmt);
    // }
}

long rgbToVoltage(long value) {
    return map(value, 0, 255, 0, 1023);
}

ISR(WDT_vect) {

}

void setup() {
    pinMode(LED_BLUE, OUTPUT);
    pinMode(LED_GREEN, OUTPUT);
    pinMode(LED_RED, OUTPUT);

    analogWrite(LED_RED, rgbToVoltage(242));
    analogWrite(LED_GREEN, rgbToVoltage(14));
    analogWrite(LED_BLUE, rgbToVoltage(48));

    Serial.begin(9600);
    gpsSerial.begin(9600);
    while(!Serial) {;}
    // while(!gpsSerial) {;}
    // // dht.begin();
    Timer1.initialize(1000000);
    Timer1.attachInterrupt(callback);
    if(!sd.begin()) {
        Serial.println("sd could not begin!");
        while(1);
    }

    // setup went ok, blue color means good to go
    // red light is more intense than the others, so the voltage is cut down by three
    analogWrite(LED_RED, rgbToVoltage(39)/3);
    analogWrite(LED_GREEN, rgbToVoltage(18));
    analogWrite(LED_BLUE, rgbToVoltage(229));

    // enable watchdog with 2 seconds timer
    wdt_enable(WDTO_2S);
    // sd.writeToFile("gpslog.txt", "lat, lng, time");
}

void loop() {
    // send data only when you receive data:
    if (gpsSerial.available() > 0) {
        gps.encode(gpsSerial.read());
        if (gps.location.isValid()) {
            analogWrite(LED_RED, rgbToVoltage(39)/3);
            analogWrite(LED_GREEN, rgbToVoltage(18));
            analogWrite(LED_BLUE, rgbToVoltage(229));
            lat = gps.location.lat();
            lng = gps.location.lng();
            char gpsData [64];
            sprintf(gpsData, "%0.2f,%0.2f,%lu", lat, lng, (long unsigned int) gps.time.value());
            sd.writeToFile("gpslog.txt", gpsData);
        } else {
            analogWrite(LED_RED, rgbToVoltage(242));
            analogWrite(LED_GREEN, rgbToVoltage(14));
            analogWrite(LED_BLUE, rgbToVoltage(48));
        }
    }

    // reset watchdog timer
    wdt_reset();
}
#endif
<commit_msg>fix lat lng types to double<commit_after>#ifndef UNIT_TEST
#include <Arduino.h>
#include <avr/wdt.h>
#include <DHT.h>
#include <TimerOne.h>
#include "lib/SDCard.h"
#include "PinMap.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
// #include "test/bmp.test.h"

SoftwareSerial gpsSerial(9, 10);

DHT dht(DHTPIN, DHTTYPE);
SDCard sd(SD_PIN);
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
TinyGPSPlus gps;

double lat = 0.00;
double lng = 0.00;

float hum = 0;
float tmp = 0;
float hid = 0;

int mq7 = 0;
int mq2 = 0;
int mq135 = 0;

int readMQ(int pin) {
    int value = analogRead(pin);
    if (isnan(value)) {
        return -1;
    } else {
        return value;
    }
}

void serialize(char* fmt) {
    sprintf(fmt, "{mq7:%i,mq2:%i,mq135:%i,hum:%i,tmp:%i,hid:%i;}", mq7, mq2, mq135, (int)hum, (int)tmp, (int)(hid+0.5));
}

void callback() {
    mq7 = readMQ(MQ7PIN);
    char foo [64];
    sprintf(foo, "%d", mq7);
    // Serial.println(foo);
    // mq2 = readMQ(MQ2PIN);
    // mq135 = readMQ(MQ135PIN);
    // hid = dht.computeHeatIndex(tmp, hum, false);
    //
    // char fmt [64];
    // serialize(fmt);
    // if (Serial.available()) {
    //     Serial.println(fmt);
    // }
}

long rgbToVoltage(long value) {
    return map(value, 0, 255, 0, 1023);
}

ISR(WDT_vect) {

}

void setup() {
    pinMode(LED_BLUE, OUTPUT);
    pinMode(LED_GREEN, OUTPUT);
    pinMode(LED_RED, OUTPUT);

    analogWrite(LED_RED, rgbToVoltage(242));
    analogWrite(LED_GREEN, rgbToVoltage(14));
    analogWrite(LED_BLUE, rgbToVoltage(48));

    Serial.begin(9600);
    gpsSerial.begin(9600);
    while(!Serial) {;}
    // while(!gpsSerial) {;}
    // // dht.begin();
    Timer1.initialize(1000000);
    Timer1.attachInterrupt(callback);
    if(!sd.begin()) {
        Serial.println("sd could not begin!");
        while(1);
    }

    // setup went ok, blue color means good to go
    // red light is more intense than the others, so the voltage is cut down by three
    analogWrite(LED_RED, rgbToVoltage(39)/3);
    analogWrite(LED_GREEN, rgbToVoltage(18));
    analogWrite(LED_BLUE, rgbToVoltage(229));

    // enable watchdog with 2 seconds timer
    wdt_enable(WDTO_2S);
    // sd.writeToFile("gpslog.txt", "lat, lng, time");
}

void loop() {
    // send data only when you receive data:
    if (gpsSerial.available() > 0) {
        gps.encode(gpsSerial.read());
        if (gps.location.isValid()) {
            analogWrite(LED_RED, rgbToVoltage(39)/3);
            analogWrite(LED_GREEN, rgbToVoltage(18));
            analogWrite(LED_BLUE, rgbToVoltage(229));
            lat = gps.location.lat();
            lng = gps.location.lng();
            char gpsData [64];
            sprintf(gpsData, "%0.2f,%0.2f,%lu", lat, lng, (long unsigned int) gps.time.value());
            sd.writeToFile("gpslog.txt", gpsData);
        } else {
            analogWrite(LED_RED, rgbToVoltage(242));
            analogWrite(LED_GREEN, rgbToVoltage(14));
            analogWrite(LED_BLUE, rgbToVoltage(48));
        }
    }

    // reset watchdog timer
    wdt_reset();
}
#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <cmath>

#include <tclap/CmdLine.h>
#include <fitsio.h>

#define fits_check(x) (x); if (status) { fits_report_error(stderr, status); exit(status); }
#define fits_checkp(x) (x); if (*status) { fits_report_error(stderr, *status); exit(*status); }

using namespace std;

const double NULL_VALUE = NAN;

long get_nimages(const string &filename) {
    fitsfile *fptr;
    int status = 0;

    fits_check(fits_open_file(&fptr, filename.c_str(), READONLY, &status));

    int hdutype = 0;
    fits_check(fits_movabs_hdu(fptr, 2, &hdutype, &status));
    assert(BINARY_TBL == hdutype);

    long nrows = 0;
    fits_check(fits_get_num_rows(fptr, &nrows, &status));

    fits_check(fits_close_file(fptr, &status));
    return nrows;
}

void compute_image_dimensions(const vector<string> &files, long *nobjects, long *nimages) {
    *nobjects = files.size();
    vector<long> sizes;
    transform(files.begin(), files.end(), back_inserter(sizes), get_nimages);
    *nimages = *max_element(sizes.begin(), sizes.end());
    cout << endl;
}

vector<double> get_column(const string &filename, const string &column, int datatype, int *status) {
    fitsfile *fptr;
    long nimages = get_nimages(filename);
    vector<double> out(nimages);

    fits_checkp(fits_open_file(&fptr, filename.c_str(), READONLY, status));
    fits_checkp(fits_movabs_hdu(fptr, 2, NULL, status));

    int colnum = 0;
    fits_checkp(fits_get_colnum(fptr, CASEINSEN, const_cast<char*>(column.c_str()), &colnum, status));
    assert(0 != colnum);
    cout << column << " column number: " << colnum << endl;

    fits_checkp(fits_read_col(fptr, datatype, colnum, 1, 1, nimages, NULL, &out[0], NULL, status));
    fits_checkp(fits_close_file(fptr, status));

    return out;
}

void create_image_hdu(const string &hdu_name, const string &column, fitsfile *fptr, int datatype, const vector<string> &files, long nobjects, long nimages, int *status) {
    long naxes[] = {nimages, nobjects};

    switch (datatype) {
        case TDOUBLE:
            fits_checkp(fits_create_img(fptr, DOUBLE_IMG, 2, naxes, status));
            break;
        case TINT:
            fits_checkp(fits_create_img(fptr, LONG_IMG, 2, naxes, status));
            break;
        default:
            cerr << "Unsupported data type: " << datatype << endl;
            exit(-1);
            break;
    }

    /* Check that we've changed hdu */
    int hdunum = 0;
    fits_checkp(fits_get_hdu_num(fptr, &hdunum));

    char *extname = const_cast<char*>(hdu_name.c_str());
    fits_checkp(fits_update_key(fptr, TSTRING, "EXTNAME", extname, NULL, status));

    for (int i=0; i<nobjects; i++) {
        auto filename = files[i];
        auto data = get_column(filename, column, datatype, status);
        for (int j=data.size(); j<nimages; j++) {
            data.push_back(NULL_VALUE);
        }
        long fpixel[] = {1, i + 1};
        long lpixel[] = {nimages, i + 1};
        fits_checkp(fits_write_subset(fptr, datatype, fpixel, lpixel, &data[0], status));
    }
}

fitsfile *create_and_clobber(const string &filename) {
    int status = 0;
    fitsfile *fptr = nullptr;

    fits_create_file(&fptr, filename.c_str(), &status);
    if (FILE_NOT_CREATED == status) {
        cerr << "File " << filename << " exists, overwriting" << endl;
        remove(filename.c_str());
        status = 0;
        return create_and_clobber(filename);
    } else if (0 != status) {
        fits_report_error(stderr, status);
        exit(status);
    }

    return fptr;
}

void combine_files(const vector<string> &files, const string &output) {
    long nobjects = 0, nimages = 0;
    fitsfile *fptr;
    int status = 0;
    compute_image_dimensions(files, &nobjects, &nimages);
    cout << "Image dimensions: " << nimages << " images, " << nobjects << " objects" << endl;

    fptr = create_and_clobber(output);
    assert(nullptr != fptr);

    /* Create the primary hdu */
    fits_check(fits_create_img(fptr, BYTE_IMG, 0, NULL, &status));

    /* Write the HDUS */
    fits_check(create_image_hdu("HJD", "TIME", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("FLUX", "DETFLUX", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("FLUXERR", "DETFLUX_ERR", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("CCDX", "CENT_COL", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("CCDY", "CENT_ROW", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("QUALITY", "QUALITY", fptr, TINT, files, nobjects, nimages, &status));

    fits_check(fits_close_file(fptr, &status));
}

int main(int argc, const char *argv[]) {
    try {
        TCLAP::CmdLine cmd("extract", ' ', "0.0.1");
        TCLAP::UnlabeledMultiArg<string> filesArg("files", "files to combine", true, "filename", cmd);
        TCLAP::ValueArg<string> outputArg("o", "output", "output filename", true, "", "filename", cmd);
        cmd.parse(argc, argv);

        combine_files(filesArg.getValue(), outputArg.getValue());
    } catch (TCLAP::ArgException &e) {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
        return 1;
    }
    return 0;
}
<commit_msg>Add print statements<commit_after>#include <iostream>
#include <cassert>
#include <cmath>

#include <tclap/CmdLine.h>
#include <fitsio.h>

#define fits_check(x) (x); if (status) { fits_report_error(stderr, status); exit(status); }
#define fits_checkp(x) (x); if (*status) { fits_report_error(stderr, *status); exit(*status); }

using namespace std;

const double NULL_VALUE = NAN;

long get_nimages(const string &filename) {
    fitsfile *fptr;
    int status = 0;

    fits_check(fits_open_file(&fptr, filename.c_str(), READONLY, &status));

    int hdutype = 0;
    fits_check(fits_movabs_hdu(fptr, 2, &hdutype, &status));
    assert(BINARY_TBL == hdutype);

    long nrows = 0;
    fits_check(fits_get_num_rows(fptr, &nrows, &status));

    fits_check(fits_close_file(fptr, &status));
    return nrows;
}

void compute_image_dimensions(const vector<string> &files, long *nobjects, long *nimages) {
    *nobjects = files.size();
    vector<long> sizes;
    transform(files.begin(), files.end(), back_inserter(sizes), get_nimages);
    *nimages = *max_element(sizes.begin(), sizes.end());
    cout << endl;
}

vector<double> get_column(const string &filename, const string &column, int datatype, int *status) {
    fitsfile *fptr;
    long nimages = get_nimages(filename);
    vector<double> out(nimages);

    fits_checkp(fits_open_file(&fptr, filename.c_str(), READONLY, status));
    fits_checkp(fits_movabs_hdu(fptr, 2, NULL, status));

    int colnum = 0;
    fits_checkp(fits_get_colnum(fptr, CASEINSEN, const_cast<char*>(column.c_str()), &colnum, status));
    assert(0 != colnum);
    cout << column << " column number: " << colnum << endl;

    fits_checkp(fits_read_col(fptr, datatype, colnum, 1, 1, nimages, NULL, &out[0], NULL, status));
    fits_checkp(fits_close_file(fptr, status));

    return out;
}

void create_image_hdu(const string &hdu_name, const string &column, fitsfile *fptr, int datatype, const vector<string> &files, long nobjects, long nimages, int *status) {
    cout << "Creating " << hdu_name << " hdu, from column " << column << endl;
    long naxes[] = {nimages, nobjects};

    switch (datatype) {
        case TDOUBLE:
            fits_checkp(fits_create_img(fptr, DOUBLE_IMG, 2, naxes, status));
            break;
        case TINT:
            fits_checkp(fits_create_img(fptr, LONG_IMG, 2, naxes, status));
            break;
        default:
            cerr << "Unsupported data type: " << datatype << endl;
            exit(-1);
            break;
    }

    /* Check that we've changed hdu */
    int hdunum = 0;
    fits_checkp(fits_get_hdu_num(fptr, &hdunum));

    cout << "Writing hdu name" << endl;
    char *extname = const_cast<char*>(hdu_name.c_str());
    fits_checkp(fits_update_key(fptr, TSTRING, "EXTNAME", extname, NULL, status));

    for (int i=0; i<nobjects; i++) {
        auto filename = files[i];
        cout << "Updating from file " << filename << endl;
        auto data = get_column(filename, column, datatype, status);
        for (int j=data.size(); j<nimages; j++) {
            data.push_back(NULL_VALUE);
        }
        long fpixel[] = {1, i + 1};
        long lpixel[] = {nimages, i + 1};
        fits_checkp(fits_write_subset(fptr, datatype, fpixel, lpixel, &data[0], status));
    }
}

fitsfile *create_and_clobber(const string &filename) {
    int status = 0;
    fitsfile *fptr = nullptr;

    fits_create_file(&fptr, filename.c_str(), &status);
    if (FILE_NOT_CREATED == status) {
        cerr << "File " << filename << " exists, overwriting" << endl;
        remove(filename.c_str());
        status = 0;
        return create_and_clobber(filename);
    } else if (0 != status) {
        fits_report_error(stderr, status);
        exit(status);
    }

    return fptr;
}

void combine_files(const vector<string> &files, const string &output) {
    long nobjects = 0, nimages = 0;
    fitsfile *fptr;
    int status = 0;
    compute_image_dimensions(files, &nobjects, &nimages);
    cout << "Image dimensions: " << nimages << " images, " << nobjects << " objects" << endl;

    fptr = create_and_clobber(output);
    assert(nullptr != fptr);

    /* Create the primary hdu */
    cout << "Creating primary hdu" << endl;
    fits_check(fits_create_img(fptr, BYTE_IMG, 0, NULL, &status));

    /* Write the image HDUS */
    fits_check(create_image_hdu("HJD", "TIME", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("FLUX", "DETFLUX", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("FLUXERR", "DETFLUX_ERR", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("CCDX", "CENT_COL", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("CCDY", "CENT_ROW", fptr, TDOUBLE, files, nobjects, nimages, &status));
    fits_check(create_image_hdu("QUALITY", "QUALITY", fptr, TINT, files, nobjects, nimages, &status));

    fits_check(fits_close_file(fptr, &status));
}

int main(int argc, const char *argv[]) {
    try {
        TCLAP::CmdLine cmd("extract", ' ', "0.0.1");
        TCLAP::UnlabeledMultiArg<string> filesArg("files", "files to combine", true, "filename", cmd);
        TCLAP::ValueArg<string> outputArg("o", "output", "output filename", true, "", "filename", cmd);
        cmd.parse(argc, argv);

        combine_files(filesArg.getValue(), outputArg.getValue());
    } catch (TCLAP::ArgException &e) {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
        return 1;
    }
    return 0;
}
<|endoftext|>