text stringlengths 54 60.6k |
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: serviceinfohelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 03:55:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#define CONFIGMGR_SERVICEINFOHELPER_HXX_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
using ::rtl::OUString;
// -----------------------------------------------------------------------------
typedef sal_Char const * AsciiServiceName;
// -----------------------------------------------------------------------------
/// POD struct describing the registration information of a service implementation
struct ServiceRegistrationInfo
{
/// The implementation name of this service implementation
AsciiServiceName implementationName;
/// The services for which this service implementation is registered
AsciiServiceName const * registeredServiceNames;
};
// -----------------------------------------------------------------------------
/// POD struct describing the implementation information of a service implementation
struct ServiceImplementationInfo
{
/// The implementation name of this service implementation
AsciiServiceName implementationName;
/// The services for which this service implementation is registered
AsciiServiceName const * registeredServiceNames;
/// Additional services implemented by this service implementation, for which it is not registered
AsciiServiceName const * additionalServiceNames;
};
// -----------------------------------------------------------------------------
// ServiceImplementationInfo has a compatible initial sequence with struct ServiceRegistrationInfo
inline
ServiceRegistrationInfo const *
getRegistrationInfo(ServiceImplementationInfo const * _info)
{
return reinterpret_cast<ServiceRegistrationInfo const *>(_info);
}
// -----------------------------------------------------------------------------
/// POD struct describing the registration information of a singleton
struct SingletonRegistrationInfo
{
/// The name of this singleton
AsciiServiceName singletonName;
/// The implementation, which owns this singleton
AsciiServiceName implementationName;
/// The service, which should be instatiated for this singleton
AsciiServiceName instantiatedServiceName;
/// A name for a pseudo-implementation, which is mapped to this singleton
ServiceRegistrationInfo const * mappedImplementation;
};
// -----------------------------------------------------------------------------
class ServiceRegistrationHelper
{
ServiceRegistrationInfo const*const m_info;
public:
ServiceRegistrationHelper(ServiceRegistrationInfo const* _info)
: m_info(_info)
{}
ServiceRegistrationHelper(ServiceImplementationInfo const* _info)
: m_info(getRegistrationInfo(_info))
{}
sal_Int32 countServices() const;
OUString getImplementationName( ) const
throw(uno::RuntimeException);
uno::Sequence< OUString > getRegisteredServiceNames( ) const
throw(uno::RuntimeException);
};
// -----------------------------------------------------------------------------
class ServiceInfoHelper
{
ServiceImplementationInfo const*const m_info;
public:
ServiceInfoHelper(ServiceImplementationInfo const* _info)
: m_info(_info)
{}
sal_Int32 countServices() const;
OUString getImplementationName( ) const
throw(uno::RuntimeException);
sal_Bool supportsService( OUString const & ServiceName ) const
throw(uno::RuntimeException);
uno::Sequence< OUString > getSupportedServiceNames( ) const
throw(uno::RuntimeException);
};
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008/04/01 12:27:25 thb 1.4.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:45 rt 1.4.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: serviceinfohelper.hxx,v $
* $Revision: 1.5 $
*
* 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.
*
************************************************************************/
#ifndef CONFIGMGR_SERVICEINFOHELPER_HXX_
#define CONFIGMGR_SERVICEINFOHELPER_HXX_
#include <com/sun/star/lang/XServiceInfo.hpp>
namespace configmgr
{
// -----------------------------------------------------------------------------
namespace uno = ::com::sun::star::uno;
namespace lang = ::com::sun::star::lang;
using ::rtl::OUString;
// -----------------------------------------------------------------------------
typedef sal_Char const * AsciiServiceName;
// -----------------------------------------------------------------------------
/// POD struct describing the registration information of a service implementation
struct ServiceRegistrationInfo
{
/// The implementation name of this service implementation
AsciiServiceName implementationName;
/// The services for which this service implementation is registered
AsciiServiceName const * registeredServiceNames;
};
// -----------------------------------------------------------------------------
/// POD struct describing the implementation information of a service implementation
struct ServiceImplementationInfo
{
/// The implementation name of this service implementation
AsciiServiceName implementationName;
/// The services for which this service implementation is registered
AsciiServiceName const * registeredServiceNames;
/// Additional services implemented by this service implementation, for which it is not registered
AsciiServiceName const * additionalServiceNames;
};
// -----------------------------------------------------------------------------
// ServiceImplementationInfo has a compatible initial sequence with struct ServiceRegistrationInfo
inline
ServiceRegistrationInfo const *
getRegistrationInfo(ServiceImplementationInfo const * _info)
{
return reinterpret_cast<ServiceRegistrationInfo const *>(_info);
}
// -----------------------------------------------------------------------------
/// POD struct describing the registration information of a singleton
struct SingletonRegistrationInfo
{
/// The name of this singleton
AsciiServiceName singletonName;
/// The implementation, which owns this singleton
AsciiServiceName implementationName;
/// The service, which should be instatiated for this singleton
AsciiServiceName instantiatedServiceName;
/// A name for a pseudo-implementation, which is mapped to this singleton
ServiceRegistrationInfo const * mappedImplementation;
};
// -----------------------------------------------------------------------------
class ServiceRegistrationHelper
{
ServiceRegistrationInfo const*const m_info;
public:
ServiceRegistrationHelper(ServiceRegistrationInfo const* _info)
: m_info(_info)
{}
ServiceRegistrationHelper(ServiceImplementationInfo const* _info)
: m_info(getRegistrationInfo(_info))
{}
sal_Int32 countServices() const;
OUString getImplementationName( ) const
throw(uno::RuntimeException);
uno::Sequence< OUString > getRegisteredServiceNames( ) const
throw(uno::RuntimeException);
};
// -----------------------------------------------------------------------------
class ServiceInfoHelper
{
ServiceImplementationInfo const*const m_info;
public:
ServiceInfoHelper(ServiceImplementationInfo const* _info)
: m_info(_info)
{}
sal_Int32 countServices() const;
OUString getImplementationName( ) const
throw(uno::RuntimeException);
sal_Bool supportsService( OUString const & ServiceName ) const
throw(uno::RuntimeException);
uno::Sequence< OUString > getSupportedServiceNames( ) const
throw(uno::RuntimeException);
};
// -----------------------------------------------------------------------------
} // namespace configmgr
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/sandbox_init_wrapper.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "content/common/content_switches.h"
#include "content/common/sandbox_mac.h"
bool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,
const std::string& process_type) {
using sandbox::Sandbox;
if (command_line.HasSwitch(switches::kNoSandbox))
return true;
Sandbox::SandboxProcessType sandbox_process_type;
FilePath allowed_dir; // Empty by default.
if (process_type.empty()) {
// Browser process isn't sandboxed.
return true;
} else if (process_type == switches::kRendererProcess) {
if (!command_line.HasSwitch(switches::kDisable3DAPIs) &&
!command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
command_line.HasSwitch(switches::kInProcessWebGL)) {
// TODO(kbr): this check seems to be necessary only on this
// platform because the sandbox is initialized later. Remove
// this once this flag is removed.
return true;
} else {
sandbox_process_type = Sandbox::SANDBOX_TYPE_RENDERER;
}
} else if (process_type == switches::kExtensionProcess) {
// Extension processes are just renderers [they use RenderMain()] with a
// different set of command line flags.
// If we ever get here it means something has changed in regards
// to the extension process mechanics and we should probably reexamine
// how we sandbox extension processes since they are no longer identical
// to renderers.
NOTREACHED();
return true;
} else if (process_type == switches::kUtilityProcess) {
// Utility process sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_UTILITY;
allowed_dir =
command_line.GetSwitchValuePath(switches::kUtilityProcessAllowedDir);
} else if (process_type == switches::kWorkerProcess) {
// Worker process sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_WORKER;
} else if (process_type == switches::kNaClLoaderProcess) {
// Native Client sel_ldr (user untrusted code) sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_NACL_LOADER;
} else if (process_type == switches::kGpuProcess) {
sandbox_process_type = Sandbox::SANDBOX_TYPE_GPU;
} else if ((process_type == switches::kPluginProcess) ||
(process_type == switches::kProfileImportProcess) ||
(process_type == switches::kServiceProcess)) {
return true;
} else if (process_type == switches::kPpapiPluginProcess) {
sandbox_process_type = Sandbox::SANDBOX_TYPE_PPAPI;
} else {
// Failsafe: If you hit an unreached here, is your new process type in need
// of sandboxing?
NOTREACHED();
return true;
}
// Warm up APIs before turning on the sandbox.
Sandbox::SandboxWarmup(sandbox_process_type);
// Actually sandbox the process.
return Sandbox::EnableSandbox(sandbox_process_type, allowed_dir);
}
<commit_msg>Show unhandled process types during failed sandbox initialization.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/sandbox_init_wrapper.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "content/common/content_switches.h"
#include "content/common/sandbox_mac.h"
bool SandboxInitWrapper::InitializeSandbox(const CommandLine& command_line,
const std::string& process_type) {
using sandbox::Sandbox;
if (command_line.HasSwitch(switches::kNoSandbox))
return true;
Sandbox::SandboxProcessType sandbox_process_type;
FilePath allowed_dir; // Empty by default.
if (process_type.empty()) {
// Browser process isn't sandboxed.
return true;
} else if (process_type == switches::kRendererProcess) {
if (!command_line.HasSwitch(switches::kDisable3DAPIs) &&
!command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
command_line.HasSwitch(switches::kInProcessWebGL)) {
// TODO(kbr): this check seems to be necessary only on this
// platform because the sandbox is initialized later. Remove
// this once this flag is removed.
return true;
} else {
sandbox_process_type = Sandbox::SANDBOX_TYPE_RENDERER;
}
} else if (process_type == switches::kExtensionProcess) {
// Extension processes are just renderers [they use RenderMain()] with a
// different set of command line flags.
// If we ever get here it means something has changed in regards
// to the extension process mechanics and we should probably reexamine
// how we sandbox extension processes since they are no longer identical
// to renderers.
NOTREACHED();
return true;
} else if (process_type == switches::kUtilityProcess) {
// Utility process sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_UTILITY;
allowed_dir =
command_line.GetSwitchValuePath(switches::kUtilityProcessAllowedDir);
} else if (process_type == switches::kWorkerProcess) {
// Worker process sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_WORKER;
} else if (process_type == switches::kNaClLoaderProcess) {
// Native Client sel_ldr (user untrusted code) sandbox.
sandbox_process_type = Sandbox::SANDBOX_TYPE_NACL_LOADER;
} else if (process_type == switches::kGpuProcess) {
sandbox_process_type = Sandbox::SANDBOX_TYPE_GPU;
} else if ((process_type == switches::kPluginProcess) ||
(process_type == switches::kProfileImportProcess) ||
(process_type == switches::kServiceProcess)) {
return true;
} else if (process_type == switches::kPpapiPluginProcess) {
sandbox_process_type = Sandbox::SANDBOX_TYPE_PPAPI;
} else {
// Failsafe: If you hit an unreached here, is your new process type in need
// of sandboxing?
NOTREACHED() << "Unknown process type " << process_type;
return true;
}
// Warm up APIs before turning on the sandbox.
Sandbox::SandboxWarmup(sandbox_process_type);
// Actually sandbox the process.
return Sandbox::EnableSandbox(sandbox_process_type, allowed_dir);
}
<|endoftext|> |
<commit_before>#if __cplusplus > 199711L
#include "Halide.h"
// When using Generators to JIT, just include the Generator .cpp file.
// Yes, this is a little unusual, but it's recommended practice.
#include "example_generator.cpp"
using Halide::Image;
const int kSize = 32;
void verify(const Image<int32_t> &img, float compiletime_factor, float runtime_factor, int channels) {
for (int i = 0; i < kSize; i++) {
for (int j = 0; j < kSize; j++) {
for (int c = 0; c < channels; c++) {
if (img(i, j, c) !=
(int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {
printf("img[%d, %d, %d] = %d\n", i, j, c, img(i, j, c));
exit(-1);
}
}
}
}
}
int main(int argc, char **argv) {
{
// Create a Generator and set its GeneratorParams by a map
// of key-value pairs. Values are looked up by name, order doesn't matter.
// GeneratorParams not set here retain their existing values. (Note that
// all Generators have a "target" GeneratorParam, which is just
// a Halide::Target set using the normal syntax.)
Example gen;
gen.set_generator_param_values({ { "compiletime_factor", "2.3" },
{ "channels", "3" },
{ "target", "host" },
{ "enummy", "foo" },
{ "flag", "false" } });
Image<int32_t> img = gen.build().realize(kSize, kSize, 3, gen.get_target());
verify(img, 2.3, 1, 3);
}
{
// You can also set the GeneratorParams after creation by setting the
// member values directly, of course.
Example gen;
gen.compiletime_factor.set(2.9);
Image<int32_t> img = gen.build().realize(kSize, kSize, 3);
verify(img, 2.9, 1, 3);
// You can change the GeneratorParams between each call to build().
gen.compiletime_factor.set(0.1);
gen.channels.set(4);
Image<int32_t> img2 = gen.build().realize(kSize, kSize, 4);
verify(img2, 0.1, 1, 4);
// Setting non-existent GeneratorParams will fail with a user_assert.
// gen->set_generator_param_values({{"unknown_name", "0.1"}});
// Setting GeneratorParams to values that can't be properly parsed
// into the correct type will fail with a user_assert.
// gen->set_generator_param_values({{"compiletime_factor", "this is not a number"}});
// gen->set_generator_param_values({{"channels", "neither is this"}});
// gen->set_generator_param_values({{"enummy", "not_in_the_enum_map"}});
// gen->set_generator_param_values({{"flag", "maybe"}});
// gen->set_generator_param_values({{"target", "6502-8"}});
}
{
// If you're fine with the default values of all GeneratorParams,
// you can just use a temporary:
Image<int32_t> img = Example().build().realize(kSize, kSize, 3);
verify(img, 1, 1, 3);
}
{
// Want to set both GeneratorParams and FilterParams
// (aka Runtime Params aka plain-old-params)? The currently-recommended
// approach is to set all before calling build() or realize().
// (Better approaches should be possible in the future.)
Example gen;
gen.compiletime_factor.set(1.234f);
gen.runtime_factor.set(3.456f);
Image<int32_t> img = gen.build().realize(kSize, kSize, 3);
verify(img, 1.234f, 3.456f, 3);
}
printf("Success!\n");
return 0;
}
#else
#include <stdio.h>
int main(int argc, char **argv) {
printf("This test requires C++11\n");
return 0;
}
#endif
<commit_msg>Also change constants in jit example<commit_after>#if __cplusplus > 199711L
#include "Halide.h"
// When using Generators to JIT, just include the Generator .cpp file.
// Yes, this is a little unusual, but it's recommended practice.
#include "example_generator.cpp"
using Halide::Image;
const int kSize = 32;
void verify(const Image<int32_t> &img, float compiletime_factor, float runtime_factor, int channels) {
for (int i = 0; i < kSize; i++) {
for (int j = 0; j < kSize; j++) {
for (int c = 0; c < channels; c++) {
if (img(i, j, c) !=
(int32_t)(compiletime_factor * runtime_factor * c * (i > j ? i : j))) {
printf("img[%d, %d, %d] = %d\n", i, j, c, img(i, j, c));
exit(-1);
}
}
}
}
}
int main(int argc, char **argv) {
{
// Create a Generator and set its GeneratorParams by a map
// of key-value pairs. Values are looked up by name, order doesn't matter.
// GeneratorParams not set here retain their existing values. (Note that
// all Generators have a "target" GeneratorParam, which is just
// a Halide::Target set using the normal syntax.)
Example gen;
gen.set_generator_param_values({ { "compiletime_factor", "2.392" },
{ "channels", "3" },
{ "target", "host" },
{ "enummy", "foo" },
{ "flag", "false" } });
Image<int32_t> img = gen.build().realize(kSize, kSize, 3, gen.get_target());
verify(img, 2.392, 1, 3);
}
{
// You can also set the GeneratorParams after creation by setting the
// member values directly, of course.
Example gen;
gen.compiletime_factor.set(2.913);
Image<int32_t> img = gen.build().realize(kSize, kSize, 3);
verify(img, 2.913, 1, 3);
// You can change the GeneratorParams between each call to build().
gen.compiletime_factor.set(0.1423);
gen.channels.set(4);
Image<int32_t> img2 = gen.build().realize(kSize, kSize, 4);
verify(img2, 0.1423, 1, 4);
// Setting non-existent GeneratorParams will fail with a user_assert.
// gen->set_generator_param_values({{"unknown_name", "0.1"}});
// Setting GeneratorParams to values that can't be properly parsed
// into the correct type will fail with a user_assert.
// gen->set_generator_param_values({{"compiletime_factor", "this is not a number"}});
// gen->set_generator_param_values({{"channels", "neither is this"}});
// gen->set_generator_param_values({{"enummy", "not_in_the_enum_map"}});
// gen->set_generator_param_values({{"flag", "maybe"}});
// gen->set_generator_param_values({{"target", "6502-8"}});
}
{
// If you're fine with the default values of all GeneratorParams,
// you can just use a temporary:
Image<int32_t> img = Example().build().realize(kSize, kSize, 3);
verify(img, 1, 1, 3);
}
{
// Want to set both GeneratorParams and FilterParams
// (aka Runtime Params aka plain-old-params)? The currently-recommended
// approach is to set all before calling build() or realize().
// (Better approaches should be possible in the future.)
Example gen;
gen.compiletime_factor.set(1.234f);
gen.runtime_factor.set(3.456f);
Image<int32_t> img = gen.build().realize(kSize, kSize, 3);
verify(img, 1.234f, 3.456f, 3);
}
printf("Success!\n");
return 0;
}
#else
#include <stdio.h>
int main(int argc, char **argv) {
printf("This test requires C++11\n");
return 0;
}
#endif
<|endoftext|> |
<commit_before>/*
All Hands On Deck
Copyright (C) 2015-2017 Vladimir "allejo" Jimenez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <memory>
#include "bzfsAPI.h"
#include "plugin_files.h"
#include "plugin_utils.h"
// Define plugin name
const char* PLUGIN_NAME = "All Hands On Deck!";
// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 1;
const int REV = 0;
const int BUILD = 24;
static void killAllPlayers()
{
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerByIndex(playerID)->spawned && bz_killPlayer(playerID, false))
{
bz_incrementPlayerLosses(playerID, -1);
}
bz_setPlayerSpawnAtBase(playerID, true);
}
bz_deleteIntList(playerList);
}
static void sendToPlayers(bz_eTeamType team, const std::string &message)
{
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerByIndex(playerID)->team == team)
{
bz_sendTextMessagef(playerID, playerID, message.c_str());
}
}
bz_deleteIntList(playerList);
}
enum class AhodGameMode
{
Undefined = -1,
SingleDeck = 0, // Game mode where all teams need to go a neutral Deck in order to capture; requires an "AHOD" map object
MultipleDecks // Game mode where teams must have the entire team + enemy flag present on their own base to capture; no "AHOD" object allowed
};
class DeckObject : public bz_CustomZoneObject
{
public:
DeckObject() : bz_CustomZoneObject(),
defined(false),
team(eNoTeam)
{}
bool defined;
bz_eTeamType team;
};
class AllHandsOnDeck : public bz_Plugin, bz_CustomMapObjectHandler
{
public:
virtual const char* Name ();
virtual void Init(const char* config);
virtual void Event(bz_EventData *eventData);
virtual void Cleanup(void);
virtual bool MapObject(bz_ApiString object, bz_CustomMapObjectInfo *data);
private:
bool isPlayerOnDeck(int playerID);
bool enoughHandsOnDeck(bz_eTeamType team);
DeckObject& getTargetDeck(int playerID);
// Plug-in configuration
void handleCommandLine(const char* commandLine);
void configureGameMode(const std::string &gameModeLiteral);
void configureWelcomeMessage(const std::string &filepath);
// Game status information
bool enabled;
AhodGameMode gameMode;
// SingleDeck Mode data
DeckObject singleDeck;
// MultipleDecks Mode data
std::map<bz_eTeamType, bool> isCarryingEnemyFlag;
std::map<bz_eTeamType, DeckObject> teamDecks;
// Miscellaneous data
bz_eTeamType teamOne, teamTwo;
std::vector<std::string> introMessage;
};
BZ_PLUGIN(AllHandsOnDeck)
const char* AllHandsOnDeck::Name(void)
{
static const char* pluginBuild;
if (!pluginBuild)
{
pluginBuild = bz_format("%s %d.%d.%d (%d)", PLUGIN_NAME, MAJOR, MINOR, REV, BUILD);
}
return pluginBuild;
}
void AllHandsOnDeck::Init(const char* commandLine)
{
bz_registerCustomMapObject("AHOD", this);
bz_registerCustomMapObject("DECK", this);
enabled = false;
teamOne = teamTwo = eNoTeam;
gameMode = AhodGameMode::Undefined;
for (bz_eTeamType t = eRedTeam; t <= ePurpleTeam; t = (bz_eTeamType) (t + 1))
{
if (bz_getTeamPlayerLimit(t) > 0)
{
if (teamOne == eNoTeam) teamOne = t;
else if (teamTwo == eNoTeam) teamTwo = t;
}
}
handleCommandLine(commandLine);
Register(bz_eAllowCTFCaptureEvent);
Register(bz_eFlagGrabbedEvent);
Register(bz_eFlagDroppedEvent);
Register(bz_ePlayerJoinEvent);
Register(bz_ePlayerPausedEvent);
Register(bz_eTickEvent);
Register(bz_eWorldFinalized);
// Default to 100% of the team
if (!bz_BZDBItemExists("_ahodPercentage"))
{
bz_setBZDBDouble("_ahodPercentage", 1);
}
}
void AllHandsOnDeck::Cleanup(void)
{
Flush();
bz_removeCustomMapObject("AHOD");
bz_removeCustomMapObject("DECK");
}
bool AllHandsOnDeck::MapObject(bz_ApiString object, bz_CustomMapObjectInfo *data)
{
if ((object != "AHOD" && object != "DECK") || !data)
{
return false;
}
if (object == "AHOD")
{
bz_debugMessagef(0, "WARNING :: %s :: The 'AHOD' object has been renamed to 'DECK'.", PLUGIN_NAME);
bz_debugMessagef(0, "WARNING :: %s :: Future versions of this plug-in will drop support for 'AHOD' objects.", PLUGIN_NAME);
}
if (gameMode == AhodGameMode::SingleDeck)
{
singleDeck.handleDefaultOptions(data);
singleDeck.defined = true;
}
else if (gameMode == AhodGameMode::MultipleDecks)
{
DeckObject teamDeck;
teamDeck.handleDefaultOptions(data);
teamDeck.defined = true;
for (unsigned int i = 0; i < data->data.size(); i++)
{
std::string line = data->data.get(i);
bz_APIStringList nubs;
nubs.tokenize(line.c_str(), " ", 0, true);
if (nubs.size() > 0)
{
std::string key = bz_toupper(nubs.get(0).c_str());
if (key == "COLOR")
{
teamDeck.team = (bz_eTeamType)atoi(nubs.get(1).c_str());
}
}
}
if (teamDecks.count(teamDeck.team) == 0)
{
teamDecks[teamDeck.team] = teamDeck;
}
else
{
bz_debugMessagef(0, "ERROR :: %s :: Multiple bases for %s team detected. Ignoring...", PLUGIN_NAME, bzu_GetTeamName(teamDeck.team));
}
}
return true;
}
void AllHandsOnDeck::Event(bz_EventData *eventData)
{
switch (eventData->eventType)
{
case bz_eAllowCTFCaptureEvent: // This event is called each time a flag is about to be captured
{
bz_AllowCTFCaptureEventData_V1* allowCtfData = (bz_AllowCTFCaptureEventData_V1*)eventData;
switch (gameMode)
{
case AhodGameMode::SingleDeck:
allowCtfData->allow = false;
break;
case AhodGameMode::MultipleDecks:
allowCtfData->allow = enoughHandsOnDeck(allowCtfData->teamCapping);
break;
default:
break;
}
}
break;
case bz_eFlagGrabbedEvent:
{
bz_FlagGrabbedEventData_V1 *data = (bz_FlagGrabbedEventData_V1*)eventData;
bz_BasePlayerRecord *pr = bz_getPlayerByIndex(data->playerID);
if (!pr)
{
return;
}
bz_eTeamType flagOwner = bzu_getTeamFromFlag(data->flagType);
isCarryingEnemyFlag[pr->team] = (pr->team != flagOwner);
bz_freePlayerRecord(pr);
}
break;
case bz_eFlagDroppedEvent:
{
bz_FlagDroppedEventData_V1 *data = (bz_FlagDroppedEventData_V1*)eventData;
isCarryingEnemyFlag[bz_getPlayerTeam(data->playerID)] = false;
}
break;
case bz_ePlayerJoinEvent: // This event is called each time a player joins the game
{
bz_PlayerJoinPartEventData_V1* joinData = (bz_PlayerJoinPartEventData_V1*)eventData;
int playerID = joinData->playerID;
for (auto line : introMessage)
{
bz_sendTextMessage(playerID, playerID, line.c_str());
}
if (!enabled)
{
bz_sendTextMessage(BZ_SERVER, playerID, "All Hands on Deck! has been disabled. Minimum of 2v2 is required.");
}
}
break;
case bz_ePlayerPausedEvent: // This event is called each time a playing tank is paused
{
bz_PlayerPausedEventData_V1* pauseData = (bz_PlayerPausedEventData_V1*)eventData;
if (isPlayerOnDeck(pauseData->playerID) && pauseData->pause)
{
bz_killPlayer(pauseData->playerID, false);
bz_sendTextMessage(BZ_SERVER, pauseData->playerID, "Pausing on the deck is not permitted.");
}
}
break;
case bz_eTickEvent: // This event is called once for each BZFS main loop
{
// AHOD is only enabled if there are at least 2 players per team
if (bz_getTeamCount(teamOne) < 2 || bz_getTeamCount(teamTwo) < 2)
{
if (enabled)
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "All Hands on Deck! has been disabled. Minimum of 2v2 is required.");
enabled = false;
}
return;
}
if (!enabled)
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "All Hands on Deck! has been enabled.");
enabled = true;
}
if (gameMode == AhodGameMode::SingleDeck)
{
bool teamOneAhod = enoughHandsOnDeck(teamOne);
bool teamTwoAhod = enoughHandsOnDeck(teamTwo);
if (teamOneAhod || teamTwoAhod)
{
bool teamOneHasEnemyFlag = isCarryingEnemyFlag[teamOne];
bool teamTwoHasEnemyFlag = isCarryingEnemyFlag[teamTwo];
if (teamOneHasEnemyFlag || teamTwoHasEnemyFlag)
{
if ((teamOneAhod && teamOneHasEnemyFlag) || (teamTwoAhod && teamTwoHasEnemyFlag))
{
bz_eTeamType victor = (teamOneHasEnemyFlag) ? teamOne : teamTwo;
bz_eTeamType loser = (teamOneHasEnemyFlag) ? teamTwo : teamOne;
killAllPlayers();
bz_incrementTeamWins(victor, 1);
bz_incrementTeamLosses(loser, 1);
bz_resetFlags(false);
sendToPlayers(loser, bz_format("Team flag captured by the %s team!", bzu_GetTeamName(victor)));
sendToPlayers(victor, std::string("Great teamwork! Don't let them capture your flag!"));
}
}
}
}
}
break;
case bz_eWorldFinalized:
{
if (gameMode == AhodGameMode::SingleDeck)
{
if (!singleDeck.defined)
{
bz_debugMessagef(0, "ERROR :: %s :: There was no AHOD zone defined for this AHOD style map.", PLUGIN_NAME);
}
}
else if (gameMode == AhodGameMode::MultipleDecks)
{
if (teamDecks.size() < 2)
{
bz_debugMessagef(0, "WARNING :: %s :: There were not enough bases found on this map for a MultipleDecks game mode.", PLUGIN_NAME);
}
}
}
break;
default:
break;
}
}
void AllHandsOnDeck::handleCommandLine(const char* commandLine)
{
if (!commandLine)
{
return;
}
bz_APIStringList cmdLineOptions;
cmdLineOptions.tokenize(commandLine, ",");
if (cmdLineOptions.size() != 1 || cmdLineOptions.size() != 2)
{
bz_debugMessagef(0, "ERROR :: %s :: Syntax usage:", PLUGIN_NAME);
bz_debugMessagef(0, "ERROR :: %s :: -loadplugin AllHandsOnDeck,<SingleDeck|MultipleDecks>", PLUGIN_NAME);
bz_debugMessagef(0, "ERROR :: %s :: -loadplugin AllHandsOnDeck,<SingleDeck|MultipleDecks>,<welcome message file path>", PLUGIN_NAME);
return;
}
configureGameMode(cmdLineOptions[0]);
if (cmdLineOptions.size() == 2)
{
configureWelcomeMessage(cmdLineOptions[1]);
}
}
void AllHandsOnDeck::configureGameMode(const std::string &gameModeLiteral)
{
if (gameModeLiteral == "SingleDeck")
{
gameMode = AhodGameMode::SingleDeck;
}
else if (gameModeLiteral == "MultipleDecks")
{
gameMode = AhodGameMode::MultipleDecks;
}
if (gameMode == AhodGameMode::Undefined)
{
bz_debugMessagef(0, "ERROR :: %s :: Ahod game mode is undefined! This plug-in will not work correctly.", PLUGIN_NAME);
}
}
void AllHandsOnDeck::configureWelcomeMessage(const std::string &filepath)
{
if (filepath.empty())
{
introMessage.push_back("********************************************************************");
introMessage.push_back(" ");
introMessage.push_back(" --- How To Play ---");
introMessage.push_back(" Take the enemy flag to the neutral base along with your entire");
introMessage.push_back(" team in order to cap. If any player is missing, you will not be");
introMessage.push_back(" able to cap. Teamwork matters!");
introMessage.push_back(" ");
introMessage.push_back("********************************************************************");
return;
}
introMessage = getFileTextLines(filepath);
}
bool AllHandsOnDeck::isPlayerOnDeck(int playerID)
{
bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);
if (!pr)
{
return false;
}
DeckObject& targetDeck = getTargetDeck(playerID);
// The player must match the following criteria
// 1. is inside the deck
// 2. is alive
// 3. is not jumping inside the deck
bool playerIsOnDeck = (targetDeck.pointInZone(pr->lastKnownState.pos) && pr->spawned && !pr->lastKnownState.falling);
bz_freePlayerRecord(pr);
return playerIsOnDeck;
}
DeckObject& AllHandsOnDeck::getTargetDeck(int playerID)
{
if (gameMode == AhodGameMode::MultipleDecks)
{
return teamDecks[bz_getPlayerTeam(playerID)];
}
return singleDeck;
}
// Check to see if there are enough players of a specified team on a deck
bool AllHandsOnDeck::enoughHandsOnDeck(bz_eTeamType team)
{
int teamCount = 0, teamTotal = bz_getTeamCount(team);
if (teamTotal < 2)
{
return false;
}
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerTeam(playerID) == team && isPlayerOnDeck(playerID))
{
teamCount++;
}
}
bz_deleteIntList(playerList);
return ((teamCount / (double)teamTotal) >= bz_getBZDBDouble("_ahodPercentage"));
}
<commit_msg>Sanity check for BZDB and fix incorrect warnings<commit_after>/*
All Hands On Deck
Copyright (C) 2015-2017 Vladimir "allejo" Jimenez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cmath>
#include <memory>
#include "bzfsAPI.h"
#include "plugin_files.h"
#include "plugin_utils.h"
// Define plugin name
const char* PLUGIN_NAME = "All Hands On Deck!";
// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 1;
const int REV = 0;
const int BUILD = 24;
static void killAllPlayers()
{
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerByIndex(playerID)->spawned && bz_killPlayer(playerID, false))
{
bz_incrementPlayerLosses(playerID, -1);
}
bz_setPlayerSpawnAtBase(playerID, true);
}
bz_deleteIntList(playerList);
}
static void sendToPlayers(bz_eTeamType team, const std::string &message)
{
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerByIndex(playerID)->team == team)
{
bz_sendTextMessagef(playerID, playerID, message.c_str());
}
}
bz_deleteIntList(playerList);
}
enum class AhodGameMode
{
Undefined = -1,
SingleDeck = 0, // Game mode where all teams need to go a neutral Deck in order to capture; requires an "AHOD" map object
MultipleDecks // Game mode where teams must have the entire team + enemy flag present on their own base to capture; no "AHOD" object allowed
};
class DeckObject : public bz_CustomZoneObject
{
public:
DeckObject() : bz_CustomZoneObject(),
defined(false),
team(eNoTeam)
{}
bool defined;
bz_eTeamType team;
};
class AllHandsOnDeck : public bz_Plugin, bz_CustomMapObjectHandler
{
public:
virtual const char* Name ();
virtual void Init(const char* config);
virtual void Event(bz_EventData *eventData);
virtual void Cleanup(void);
virtual bool MapObject(bz_ApiString object, bz_CustomMapObjectInfo *data);
private:
bool isPlayerOnDeck(int playerID);
bool enoughHandsOnDeck(bz_eTeamType team);
DeckObject& getTargetDeck(int playerID);
// Plug-in configuration
void handleCommandLine(const char* commandLine);
void configureGameMode(const std::string &gameModeLiteral);
void configureWelcomeMessage(const std::string &filepath);
// Game status information
bool enabled;
AhodGameMode gameMode;
// SingleDeck Mode data
DeckObject singleDeck;
// MultipleDecks Mode data
std::map<bz_eTeamType, bool> isCarryingEnemyFlag;
std::map<bz_eTeamType, DeckObject> teamDecks;
// Miscellaneous data
bz_eTeamType teamOne, teamTwo;
std::vector<std::string> introMessage;
};
BZ_PLUGIN(AllHandsOnDeck)
const char* AllHandsOnDeck::Name(void)
{
static const char* pluginBuild;
if (!pluginBuild)
{
pluginBuild = bz_format("%s %d.%d.%d (%d)", PLUGIN_NAME, MAJOR, MINOR, REV, BUILD);
}
return pluginBuild;
}
void AllHandsOnDeck::Init(const char* commandLine)
{
bz_registerCustomMapObject("AHOD", this);
bz_registerCustomMapObject("DECK", this);
enabled = false;
teamOne = teamTwo = eNoTeam;
gameMode = AhodGameMode::Undefined;
for (bz_eTeamType t = eRedTeam; t <= ePurpleTeam; t = (bz_eTeamType) (t + 1))
{
if (bz_getTeamPlayerLimit(t) > 0)
{
if (teamOne == eNoTeam) teamOne = t;
else if (teamTwo == eNoTeam) teamTwo = t;
}
}
handleCommandLine(commandLine);
Register(bz_eAllowCTFCaptureEvent);
Register(bz_eFlagGrabbedEvent);
Register(bz_eFlagDroppedEvent);
Register(bz_ePlayerJoinEvent);
Register(bz_ePlayerPausedEvent);
Register(bz_eTickEvent);
Register(bz_eWorldFinalized);
// Default to 100% of the team
if (!bz_BZDBItemExists("_ahodPercentage"))
{
bz_setBZDBDouble("_ahodPercentage", 1);
}
bz_setDefaultBZDBDouble("_ahodPercentage", 1);
}
void AllHandsOnDeck::Cleanup(void)
{
Flush();
bz_removeCustomMapObject("AHOD");
bz_removeCustomMapObject("DECK");
}
bool AllHandsOnDeck::MapObject(bz_ApiString object, bz_CustomMapObjectInfo *data)
{
if ((object != "AHOD" && object != "DECK") || !data)
{
return false;
}
if (object == "AHOD")
{
bz_debugMessagef(0, "WARNING :: %s :: The 'AHOD' object has been renamed to 'DECK'.", PLUGIN_NAME);
bz_debugMessagef(0, "WARNING :: %s :: Future versions of this plug-in will drop support for 'AHOD' objects.", PLUGIN_NAME);
}
if (gameMode == AhodGameMode::SingleDeck)
{
singleDeck.handleDefaultOptions(data);
singleDeck.defined = true;
}
else if (gameMode == AhodGameMode::MultipleDecks)
{
DeckObject teamDeck;
teamDeck.handleDefaultOptions(data);
teamDeck.defined = true;
for (unsigned int i = 0; i < data->data.size(); i++)
{
std::string line = data->data.get(i);
bz_APIStringList nubs;
nubs.tokenize(line.c_str(), " ", 0, true);
if (nubs.size() > 0)
{
std::string key = bz_toupper(nubs.get(0).c_str());
if (key == "COLOR")
{
teamDeck.team = (bz_eTeamType)atoi(nubs.get(1).c_str());
}
}
}
if (teamDecks.count(teamDeck.team) == 0)
{
teamDecks[teamDeck.team] = teamDeck;
}
else
{
bz_debugMessagef(0, "ERROR :: %s :: Multiple bases for %s team detected. Ignoring...", PLUGIN_NAME, bzu_GetTeamName(teamDeck.team));
}
}
return true;
}
void AllHandsOnDeck::Event(bz_EventData *eventData)
{
switch (eventData->eventType)
{
case bz_eAllowCTFCaptureEvent: // This event is called each time a flag is about to be captured
{
bz_AllowCTFCaptureEventData_V1* allowCtfData = (bz_AllowCTFCaptureEventData_V1*)eventData;
switch (gameMode)
{
case AhodGameMode::SingleDeck:
allowCtfData->allow = false;
break;
case AhodGameMode::MultipleDecks:
allowCtfData->allow = enoughHandsOnDeck(allowCtfData->teamCapping);
break;
default:
break;
}
}
break;
case bz_eFlagGrabbedEvent:
{
bz_FlagGrabbedEventData_V1 *data = (bz_FlagGrabbedEventData_V1*)eventData;
bz_BasePlayerRecord *pr = bz_getPlayerByIndex(data->playerID);
if (!pr)
{
return;
}
bz_eTeamType flagOwner = bzu_getTeamFromFlag(data->flagType);
isCarryingEnemyFlag[pr->team] = (pr->team != flagOwner);
bz_freePlayerRecord(pr);
}
break;
case bz_eFlagDroppedEvent:
{
bz_FlagDroppedEventData_V1 *data = (bz_FlagDroppedEventData_V1*)eventData;
isCarryingEnemyFlag[bz_getPlayerTeam(data->playerID)] = false;
}
break;
case bz_ePlayerJoinEvent: // This event is called each time a player joins the game
{
bz_PlayerJoinPartEventData_V1* joinData = (bz_PlayerJoinPartEventData_V1*)eventData;
int playerID = joinData->playerID;
for (auto line : introMessage)
{
bz_sendTextMessage(playerID, playerID, line.c_str());
}
if (!enabled)
{
bz_sendTextMessage(BZ_SERVER, playerID, "All Hands on Deck! has been disabled. Minimum of 2v2 is required.");
}
}
break;
case bz_ePlayerPausedEvent: // This event is called each time a playing tank is paused
{
bz_PlayerPausedEventData_V1* pauseData = (bz_PlayerPausedEventData_V1*)eventData;
if (isPlayerOnDeck(pauseData->playerID) && pauseData->pause)
{
bz_killPlayer(pauseData->playerID, false);
bz_sendTextMessage(BZ_SERVER, pauseData->playerID, "Pausing on the deck is not permitted.");
}
}
break;
case bz_eTickEvent: // This event is called once for each BZFS main loop
{
// AHOD is only enabled if there are at least 2 players per team
if (bz_getTeamCount(teamOne) < 2 || bz_getTeamCount(teamTwo) < 2)
{
if (enabled)
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "All Hands on Deck! has been disabled. Minimum of 2v2 is required.");
enabled = false;
}
return;
}
if (!enabled)
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "All Hands on Deck! has been enabled.");
enabled = true;
}
if (gameMode == AhodGameMode::SingleDeck)
{
bool teamOneAhod = enoughHandsOnDeck(teamOne);
bool teamTwoAhod = enoughHandsOnDeck(teamTwo);
if (teamOneAhod || teamTwoAhod)
{
bool teamOneHasEnemyFlag = isCarryingEnemyFlag[teamOne];
bool teamTwoHasEnemyFlag = isCarryingEnemyFlag[teamTwo];
if (teamOneHasEnemyFlag || teamTwoHasEnemyFlag)
{
if ((teamOneAhod && teamOneHasEnemyFlag) || (teamTwoAhod && teamTwoHasEnemyFlag))
{
bz_eTeamType victor = (teamOneHasEnemyFlag) ? teamOne : teamTwo;
bz_eTeamType loser = (teamOneHasEnemyFlag) ? teamTwo : teamOne;
killAllPlayers();
bz_incrementTeamWins(victor, 1);
bz_incrementTeamLosses(loser, 1);
bz_resetFlags(false);
sendToPlayers(loser, bz_format("Team flag captured by the %s team!", bzu_GetTeamName(victor)));
sendToPlayers(victor, std::string("Great teamwork! Don't let them capture your flag!"));
}
}
}
}
}
break;
case bz_eWorldFinalized:
{
if (gameMode == AhodGameMode::SingleDeck)
{
if (!singleDeck.defined)
{
bz_debugMessagef(0, "ERROR :: %s :: There was no AHOD zone defined for this AHOD style map.", PLUGIN_NAME);
}
}
else if (gameMode == AhodGameMode::MultipleDecks)
{
if (teamDecks.size() < 2)
{
bz_debugMessagef(0, "WARNING :: %s :: There were not enough bases found on this map for a MultipleDecks game mode.", PLUGIN_NAME);
}
}
}
break;
default:
break;
}
}
void AllHandsOnDeck::handleCommandLine(const char* commandLine)
{
if (!commandLine)
{
return;
}
bz_APIStringList cmdLineOptions;
cmdLineOptions.tokenize(commandLine, ",");
if (cmdLineOptions.size() != 1 && cmdLineOptions.size() != 2)
{
bz_debugMessagef(0, "ERROR :: %s :: Syntax usage:", PLUGIN_NAME);
bz_debugMessagef(0, "ERROR :: %s :: -loadplugin AllHandsOnDeck,<SingleDeck|MultipleDecks>", PLUGIN_NAME);
bz_debugMessagef(0, "ERROR :: %s :: -loadplugin AllHandsOnDeck,<SingleDeck|MultipleDecks>,<welcome message file path>", PLUGIN_NAME);
return;
}
configureGameMode(cmdLineOptions[0]);
if (cmdLineOptions.size() == 2)
{
configureWelcomeMessage(cmdLineOptions[1]);
}
}
void AllHandsOnDeck::configureGameMode(const std::string &gameModeLiteral)
{
if (gameModeLiteral == "SingleDeck")
{
gameMode = AhodGameMode::SingleDeck;
}
else if (gameModeLiteral == "MultipleDecks")
{
gameMode = AhodGameMode::MultipleDecks;
}
if (gameMode == AhodGameMode::Undefined)
{
bz_debugMessagef(0, "ERROR :: %s :: Ahod game mode is undefined! This plug-in will not work correctly.", PLUGIN_NAME);
}
}
void AllHandsOnDeck::configureWelcomeMessage(const std::string &filepath)
{
if (filepath.empty())
{
introMessage.push_back("********************************************************************");
introMessage.push_back(" ");
introMessage.push_back(" --- How To Play ---");
introMessage.push_back(" Take the enemy flag to the neutral base along with your entire");
introMessage.push_back(" team in order to cap. If any player is missing, you will not be");
introMessage.push_back(" able to cap. Teamwork matters!");
introMessage.push_back(" ");
introMessage.push_back("********************************************************************");
return;
}
introMessage = getFileTextLines(filepath);
}
bool AllHandsOnDeck::isPlayerOnDeck(int playerID)
{
bz_BasePlayerRecord *pr = bz_getPlayerByIndex(playerID);
if (!pr)
{
return false;
}
DeckObject& targetDeck = getTargetDeck(playerID);
// The player must match the following criteria
// 1. is inside the deck
// 2. is alive
// 3. is not jumping inside the deck
bool playerIsOnDeck = (targetDeck.pointInZone(pr->lastKnownState.pos) && pr->spawned && !pr->lastKnownState.falling);
bz_freePlayerRecord(pr);
return playerIsOnDeck;
}
DeckObject& AllHandsOnDeck::getTargetDeck(int playerID)
{
if (gameMode == AhodGameMode::MultipleDecks)
{
return teamDecks[bz_getPlayerTeam(playerID)];
}
return singleDeck;
}
// Check to see if there are enough players of a specified team on a deck
bool AllHandsOnDeck::enoughHandsOnDeck(bz_eTeamType team)
{
int teamCount = 0, teamTotal = bz_getTeamCount(team);
if (teamTotal < 2)
{
return false;
}
bz_APIIntList *playerList = bz_newIntList();
bz_getPlayerIndexList(playerList);
for (unsigned int i = 0; i < playerList->size(); i++)
{
int playerID = playerList->get(i);
if (bz_getPlayerTeam(playerID) == team && isPlayerOnDeck(playerID))
{
teamCount++;
}
}
bz_deleteIntList(playerList);
return ((teamCount / (double)teamTotal) >= std::min(std::abs(bz_getBZDBDouble("_ahodPercentage")), 1.0));
}
<|endoftext|> |
<commit_before>#include <memory>
#include <UnitTest++/UnitTest++.h>
#include "Article.h"
#include "ArticleCollection.h"
SUITE(CollectionTests)
{
using namespace WikiWalker;
TEST(MakeSureNoDuplicateArticlesExist)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King"),
la2 = std::make_shared<Article>("Queen"),
la3 = std::make_shared<Article>("Prince"),
la4 = std::make_shared<Article>("Queen");
CHECK(w.add(la1));
CHECK(w.add(la2));
CHECK_EQUAL(2, w.getNumArticles());
CHECK(w.add(la3));
CHECK_EQUAL(3, w.getNumArticles());
// must fail
CHECK(!w.add(la4));
CHECK_EQUAL(3, w.getNumArticles());
}
TEST(CollectionIsCaseInsensitive)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King"),
la2 = std::make_shared<Article>("Queen"),
la3 = std::make_shared<Article>("Prince"),
la4 = std::make_shared<Article>("queen");
w.add(la1);
w.add(la2);
CHECK_EQUAL(2, w.getNumArticles());
w.add(la3);
CHECK_EQUAL(3, w.getNumArticles());
w.add(la4);
CHECK_EQUAL(4, w.getNumArticles());
}
TEST(GetArticle_Existing_MustNotBeNull)
{
ArticleCollection w;
auto king = std::make_shared<Article>("King");
w.add(king);
CHECK(w.get("King") != nullptr);
}
TEST(GetArticle_NonExisting_MustBeNull)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King");
w.add(la1);
CHECK(w.get("Queen") == nullptr);
}
ArticleCollection GetArticleCollection()
{
ArticleCollection ac;
ac.add(std::make_shared<Article>("Foo"));
ac.add(std::make_shared<Article>("Bar"));
return ac;
}
TEST(ArticleCollection_CreationViaMoveConstructor)
{
auto ac = GetArticleCollection();
CHECK_EQUAL(2, ac.getNumArticles());
CHECK(ac.get("Foo") != nullptr);
}
TEST(ArticleCollection_TestMerge)
{
ArticleCollection ac1;
ac1.add(std::make_shared<Article>("ManaMana"));
ac1.add(std::make_shared<Article>("Dragon"));
ac1.add(std::make_shared<Article>("Cereals"));
{
ArticleCollection ac2;
ac2.add(std::make_shared<Article>("Dragon"));
ac2.add(std::make_shared<Article>("Git"));
ac2.add(std::make_shared<Article>("Stroustrup"));
ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(5, ac1.getNumArticles());
CHECK_EQUAL(3, ac2.getNumArticles());
}
// check again after scope is left
CHECK_EQUAL(5, ac1.getNumArticles());
}
}
<commit_msg>Add tests for "ignore" merge strategy<commit_after>#include <memory>
#include <UnitTest++/UnitTest++.h>
#include "Article.h"
#include "ArticleCollection.h"
#include "WalkerException.h"
SUITE(CollectionTests)
{
using namespace WikiWalker;
TEST(MakeSureNoDuplicateArticlesExist)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King"),
la2 = std::make_shared<Article>("Queen"),
la3 = std::make_shared<Article>("Prince"),
la4 = std::make_shared<Article>("Queen");
CHECK(w.add(la1));
CHECK(w.add(la2));
CHECK_EQUAL(2, w.getNumArticles());
CHECK(w.add(la3));
CHECK_EQUAL(3, w.getNumArticles());
// must fail
CHECK(!w.add(la4));
CHECK_EQUAL(3, w.getNumArticles());
}
TEST(CollectionIsCaseInsensitive)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King"),
la2 = std::make_shared<Article>("Queen"),
la3 = std::make_shared<Article>("Prince"),
la4 = std::make_shared<Article>("queen");
w.add(la1);
w.add(la2);
CHECK_EQUAL(2, w.getNumArticles());
w.add(la3);
CHECK_EQUAL(3, w.getNumArticles());
w.add(la4);
CHECK_EQUAL(4, w.getNumArticles());
}
TEST(GetArticle_Existing_MustNotBeNull)
{
ArticleCollection w;
auto king = std::make_shared<Article>("King");
w.add(king);
CHECK(w.get("King") != nullptr);
}
TEST(GetArticle_NonExisting_MustBeNull)
{
ArticleCollection w;
auto la1 = std::make_shared<Article>("King");
w.add(la1);
CHECK(w.get("Queen") == nullptr);
}
ArticleCollection GetArticleCollection()
{
ArticleCollection ac;
ac.add(std::make_shared<Article>("Foo"));
ac.add(std::make_shared<Article>("Bar"));
return ac;
}
TEST(ArticleCollection_CreationViaMoveConstructor)
{
auto ac = GetArticleCollection();
CHECK_EQUAL(2, ac.getNumArticles());
CHECK(ac.get("Foo") != nullptr);
}
// dragon -> treasure
// -> fire
// -> flying
// cat -> -
// apple -> fruit
// window -> outside
void createArticlesAndFillFirst(ArticleCollection & ac)
{
auto a1 = std::make_shared<Article>("Dragon");
auto a2 = std::make_shared<Article>("Treasure");
auto a3 = std::make_shared<Article>("Fire");
auto a4 = std::make_shared<Article>("Flying");
a1->addLink(a2);
a1->addLink(a3);
a1->addLink(a4);
auto a5 = std::make_shared<Article>("Cat");
auto a6 = std::make_shared<Article>("Apple");
auto a7 = std::make_shared<Article>("Fruit");
a6->addLink(a7);
auto a8 = std::make_shared<Article>("Window");
auto a9 = std::make_shared<Article>("Outside");
a8->addLink(a9);
ac.add(a1);
ac.add(a2);
ac.add(a3);
ac.add(a4);
ac.add(a5);
ac.add(a6);
ac.add(a7);
ac.add(a8);
ac.add(a9);
}
// dragon -> -
// cat -> milk
// -> lazy
// wood -> house
// window -> glass
// -> cleaning
void createArticlesAndFillSecond(ArticleCollection & ac)
{
auto b1 = std::make_shared<Article>("Dragon");
auto b2 = std::make_shared<Article>("Cat");
auto b9 = std::make_shared<Article>("Milk");
auto b3 = std::make_shared<Article>("Lazy");
b2->addLink(b3);
b2->addLink(b9);
auto b4 = std::make_shared<Article>("Wood");
auto b5 = std::make_shared<Article>("House");
b4->addLink(b5);
auto b6 = std::make_shared<Article>("Window");
auto b7 = std::make_shared<Article>("Glass");
auto b8 = std::make_shared<Article>("Cleaning");
b6->addLink(b7);
b6->addLink(b8);
ac.add(b1);
ac.add(b2);
ac.add(b3);
ac.add(b4);
ac.add(b5);
ac.add(b6);
ac.add(b7);
ac.add(b8);
ac.add(b9);
}
TEST(ArticleCollection_TestMergeIgnore)
{
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
a1.merge(a2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(15, a1.getNumArticles());
auto ptr = a1.get("Dragon");
CHECK(ptr != nullptr);
CHECK_EQUAL(3, ptr->getNumLinks());
ptr = a1.get("Cat");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = a1.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(1, ptr->getNumLinks());
}
{
ArticleCollection a1, a2;
createArticlesAndFillFirst(a1);
createArticlesAndFillSecond(a2);
// reverse merge
a2.merge(a1, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(15, a2.getNumArticles());
auto ptr = a2.get("Dragon");
CHECK(ptr != nullptr);
CHECK_THROW(ptr->getNumLinks(), WalkerException);
ptr = a2.get("Cat");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
ptr = a2.get("Window");
CHECK(ptr != nullptr);
CHECK_EQUAL(2, ptr->getNumLinks());
}
}
TEST(ArticleCollection_TestMerge)
{
ArticleCollection ac1;
ac1.add(std::make_shared<Article>("ManaMana"));
ac1.add(std::make_shared<Article>("Dragon"));
ac1.add(std::make_shared<Article>("Cereals"));
{
ArticleCollection ac2;
ac2.add(std::make_shared<Article>("Dragon"));
ac2.add(std::make_shared<Article>("Git"));
ac2.add(std::make_shared<Article>("Stroustrup"));
ac1.merge(ac2, ArticleCollection::MergeStrategy::IgnoreDuplicates);
CHECK_EQUAL(5, ac1.getNumArticles());
CHECK_EQUAL(3, ac2.getNumArticles());
}
// check again after scope is left
CHECK_EQUAL(5, ac1.getNumArticles());
}
}
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
#define DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
#include <dune/common/exceptions.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/stuff/la/container/eigen.hh>
#include <dune/stuff/function/nonparametric/expression.hh>
#include <dune/stuff/common/separable-container.hh>
namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
#if HAVE_EIGEN
template< class EigenContainerImp, class ParamFieldImp, int maxNumParams >
class Separable
: public Common::SeparableContainer< EigenContainerImp,
Dune::Stuff::Function::Coefficient< ParamFieldImp,
maxNumParams,
typename EigenContainerImp::ElementType >,
typename EigenContainerImp::size_type >
{
public:
typedef Common::SeparableContainer< EigenContainerImp,
Dune::Stuff::Function::Coefficient< ParamFieldImp,
maxNumParams,
typename EigenContainerImp::ElementType >,
typename EigenContainerImp::size_type >
BaseType;
typedef Separable< EigenContainerImp, ParamFieldImp, maxNumParams > ThisType;
typedef typename LA::Container::EigenInterface< typename EigenContainerImp::Traits >::derived_type ComponentType;
typedef Dune::Stuff::Function::Coefficient< ParamFieldImp,
maxNumParams,
typename EigenContainerImp::ElementType > CoefficientType;
typedef typename CoefficientType::ParamType ParamType;
typedef typename CoefficientType::size_type size_type;
private:
static std::vector< Dune::shared_ptr< const ComponentType > > constify_vector(std::vector< Dune::shared_ptr< ComponentType > > _vector)
{
std::vector< Dune::shared_ptr< const ComponentType > > ret(_vector.size());
for (typename std::vector< Dune::shared_ptr< ComponentType > >::size_type ii = 0; ii < _vector.size(); ++ii)
ret[ii] = _vector[ii];
return ret;
}
public:
Separable(const size_type _paramSize,
std::vector< Dune::shared_ptr< ComponentType > > _components,
const std::vector< Dune::shared_ptr< const CoefficientType > > _coefficients)
: BaseType(_paramSize, constify_vector(_components), _coefficients)
, components_(_components)
{}
Separable(Dune::shared_ptr< ComponentType > _component)
: BaseType(_component)
{
components_.push_back(_component);
}
std::vector< Dune::shared_ptr< ComponentType > > components()
{
return components_;
}
using BaseType::components;
Dune::shared_ptr< ComponentType > fix(const ParamType& _mu) const
{
assert(false && "Implement me!");
// assert(parametric() && "Call fix() instead of fix(mu) for nonparametric container!");
// assert(mu.size() == BaseType::paramSize());
// Dune::shared_ptr< ComponentType > ret = Dune::make_shared< ComponentType >(*(BaseType::components()[0]));
// // since we are parametric, at leas one coefficient has to exist
// ParamType coefficient = BaseType::coefficients()[0]->evaluate(mu);
// assert(coefficient.size() == 1);
// ret->backend() *= coefficient[0];
// size_type qq = 1;
// for (; qq < BaseType::numCoefficients(); ++qq) {
// coefficient = BaseType::coefficients()[qq]->evaluate(mu);
// assert(coefficient.size() == 1);
// ret->backend() += BaseType::components()[qq]->backend() * coefficient[0];
// }
// if (BaseType::numComponents() > qq)
// ret->backend() += BaseType::components()[qq + 1]->backend();
// return ret;
} // Dune::shared_ptr< ComponentType > fix(const ParamType& mu) const
// Dune::shared_ptr< ComponentType > fix() const
// {
// assert(BaseType::paramSize() == 0);
// assert(BaseType::numComponents() == 1);
// assert(BaseType::numCoefficients() == 0);
// return Dune::make_shared< ComponentType >(*(BaseType::components()[0]));
// }
private:
std::vector< Dune::shared_ptr< ComponentType > > components_;
}; // class Separable
#endif // HAVE_EIGEN
} // namespace Container
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
<commit_msg>[la.container.separable] update and get rid of common.separable-container<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
#define DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
#include <dune/common/exceptions.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/stuff/la/container/eigen.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/parametric/separable/coefficient.hh>
namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
#if HAVE_EIGEN
template< class EigenContainerImp >
class Separable
{
public:
typedef Separable< EigenContainerImp > ThisType;
typedef typename LA::Container::EigenInterface< typename EigenContainerImp::Traits >::derived_type ComponentType;
typedef Stuff::Function::Coefficient< typename EigenContainerImp::ElementType > CoefficientType;
typedef typename Stuff::Common::Parameter::Type ParamType;
public:
Separable(const size_t _paramSize,
std::vector< Dune::shared_ptr< ComponentType > >& _components,
const std::vector< Dune::shared_ptr< const CoefficientType > >& _coefficients)
: paramSize_(_paramSize)
, components_(_components)
, coefficients_(_coefficients)
{
// sanity checks
if (components_.size() < 1)
DUNE_THROW(Dune::RangeError,
"\nERROR: not enough '_components' given!");
if (!(coefficients_.size() == components_.size()
|| coefficients_.size() == (components_.size() - 1)))
DUNE_THROW(Dune::RangeError,
"\nERROR: wrong number of 'coefficients_' given!");
if (coefficients_.size() == 0) {
if (paramSize_ > 0)
DUNE_THROW(Dune::RangeError,
"\nERROR: '_paramSize' has to be zero!");
} else {
if (paramSize_ < 1)
DUNE_THROW(Dune::RangeError,
"\nERROR: '_paramSize' has to be positive!");
}
}
Separable(Dune::shared_ptr< ComponentType > _component)
: paramSize_(0)
{
components_.push_back(_component);
}
bool parametric() const
{
return numCoefficients() > 0;
}
const size_t paramSize() const
{
return paramSize_;
}
const size_t numComponents() const
{
return components_.size();
}
std::vector< Dune::shared_ptr< ComponentType > > components()
{
return components_;
}
const std::vector< Dune::shared_ptr< ComponentType > >& components() const
{
return components_;
}
const size_t numCoefficients() const
{
return coefficients_.size();
}
const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const
{
return coefficients_;
}
Dune::shared_ptr< ComponentType > fix(const ParamType& _mu) const
{
assert(false && "Implement me!");
// assert(parametric() && "Call fix() instead of fix(mu) for nonparametric container!");
// assert(mu.size() == BaseType::paramSize());
// Dune::shared_ptr< ComponentType > ret = Dune::make_shared< ComponentType >(*(BaseType::components()[0]));
// // since we are parametric, at leas one coefficient has to exist
// ParamType coefficient = BaseType::coefficients()[0]->evaluate(mu);
// assert(coefficient.size() == 1);
// ret->backend() *= coefficient[0];
// size_t qq = 1;
// for (; qq < BaseType::numCoefficients(); ++qq) {
// coefficient = BaseType::coefficients()[qq]->evaluate(mu);
// assert(coefficient.size() == 1);
// ret->backend() += BaseType::components()[qq]->backend() * coefficient[0];
// }
// if (BaseType::numComponents() > qq)
// ret->backend() += BaseType::components()[qq + 1]->backend();
// return ret;
} // Dune::shared_ptr< ComponentType > fix(const ParamType& mu) const
private:
const size_t paramSize_;
std::vector< Dune::shared_ptr< ComponentType > > components_;
const std::vector< Dune::shared_ptr< const CoefficientType > > coefficients_;
}; // class Separable
#endif // HAVE_EIGEN
} // namespace Container
} // namespace LA
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_LA_CONTAINER_SEPARABLE_HH
<|endoftext|> |
<commit_before>
#include <iostream>
#include <fstream>
#include <utility>
#include <ctime>
// TCLAP
#include "tclap/CmdLine.h"
#include <sdsl/bit_vectors.hpp>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <sparsepp/spp.h>
#include <boost/dynamic_bitset.hpp>
using spp::sparse_hash_map;
// Custom Headers
//#include "uint128_t.hpp"
//#include "debug.h"
#include "kmer.hpp"
//using namespace std;
//using namespace sdsl;
#include <cstdlib>
#include <sys/timeb.h>
#include "pack-color.hpp"
#include <bitset>
int getMilliCount()
{
timeb tb;
ftime(&tb);
int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
return nCount;
}
int getMilliSpan(int nTimeStart)
{
int nSpan = getMilliCount() - nTimeStart;
if(nSpan < 0)
nSpan += 0x100000 * 1000;
return nSpan;
}
std::string file_extension = ".<extension>";
void parse_arguments(int argc, char **argv, parameters_t & params)
{
TCLAP::CmdLine cmd("Cosmo Copyright (c) Alex Bowe (alexbowe.com) 2014", ' ', VERSION);
TCLAP::UnlabeledValueArg<std::string> input_filename_arg("input",
"Input file. Currently only supports DSK's binary format (for k<=64).", true, "", "input_file", cmd);
TCLAP::UnlabeledValueArg<std::string> num_colors_arg("num_colors",
"Number of colors", true, "", "num colors", cmd);
cmd.parse( argc, argv );
params.input_filename = input_filename_arg.getValue();
params.num_colors = atoi(num_colors_arg.getValue().c_str());
}
void deserialize_color_bv(std::ifstream &colorfile, color_bv &value)
{
colorfile.read((char *)&value, sizeof(color_bv));
}
int insertColorLabel(boost::dynamic_bitset<>& bs, unsigned num, int pos) {
// most significant bit of number goes down to the end of the bitset
do {
if (num&1) {
bs.set(pos);
}
num>>=1;
pos++;
} while(num);
return pos;
}
bool writeBitset(boost::dynamic_bitset<>& bs, std::ofstream& out) {
int bitctr{7};
unsigned char byte{0};
size_t bs_size = bs.size();
std::cout<<bs_size<<"\n";
out.write(reinterpret_cast<char*>(&bs_size), sizeof(bs_size));
for (size_t i = 0; i < bs.size(); ++i) {
byte |= (bs[i] << bitctr);
if (bitctr == 0) {
out.write(reinterpret_cast<char*>(&byte), sizeof(byte));
byte = 0;
bitctr = 8;
}
bitctr--;
}
if (bitctr > 0) {
out.write(reinterpret_cast<char*>(&byte), sizeof(byte));
}
return true;
}
int main(int argc, char * argv[])
{
std::cerr << "pack-color compiled with supported colors=" << NUM_COLS << std::endl;
std::cerr <<"Starting" << std::endl;
parameters_t params;
parse_arguments(argc, argv, params);
const char * file_name = params.input_filename.c_str();
std::cerr << "file name: " << file_name << std::endl;
// Open File
std::ifstream colorfile(file_name, std::ios::in|std::ios::binary);
colorfile.seekg(0, colorfile.end);
size_t end = colorfile.tellg();
colorfile.seekg(0, colorfile.beg);
std::cerr << "file size: " << end << std::endl;
std::cerr << "sizeof(color_bv): " << sizeof(color_bv) << std::endl;
size_t num_color = params.num_colors;
size_t num_edges = end / sizeof(color_bv);
size_t cnt0 = 0;
size_t cnt1 = 0;
std::cerr << "edges: " << num_edges << " colors: " << num_color << " Total: " << num_edges * num_color << std::endl;
sparse_hash_map<color_bv, int> eqCls;
for (size_t i=0; i < num_edges; i++) {
if (i % 100000000 == 0) {
std::cerr << "deserializing edge " << i
<< " cnt0: " << cnt0
<< " cnt1: " << cnt1 << std::endl;
}
color_bv value;
deserialize_color_bv(colorfile, value);
if (eqCls.find(value)==eqCls.end())
eqCls[value] = 1;
else
eqCls[value] = eqCls[value]+1;
}
std::cerr << "Succinct builder object allocated." << std::endl;
std::vector<std::pair<color_bv, int>> eqClsVec;
eqClsVec.reserve(eqCls.size());
for (const auto& c : eqCls) { eqClsVec.push_back(c); }
// sort the hashmap
auto cmp = [](std::pair<color_bv, int> const & a, std::pair<color_bv, int> const & b)
{
return a.second > b.second;
};
std::sort(eqClsVec.begin(), eqClsVec.end(), cmp);
boost::dynamic_bitset<> eqTable(eqCls.size()*num_color);
size_t i = 0;
for (const auto& c : eqClsVec) {
for (size_t j = 0; j < num_color; ++j) {
eqTable[i] = c.first[j];
i++;
}
}
std::cout<<"Eq. cls BV:\n"<<eqTable<<"\n";
// replacing labels instead of k-mer counts as the hash map values
int lbl = 0;
int totalBits = 0;
for (const auto& c : eqClsVec) {
//std::cerr <<"eq cls "<<lbl++<< ": "<<c.first<<" : "<<c.second << "\n";
totalBits += (lbl==0?c.second:ceil(log2(lbl+1))*c.second);
eqCls[c.first] = lbl++;
std::cout<<c.first<<":"<<eqCls[c.first];
}
size_t vecBits = totalBits;
totalBits *= 2;
totalBits += num_color * eqCls.size();
std::cerr << "total bits: " << totalBits << " or " << totalBits/(8*pow(1024,2)) << " MBs\n";
// creating bitvectors A and b
// A contains eq. class label for each k-mer in bits
// b is set in the start position of each k-mer in A
int sysTime = getMilliCount();
colorfile.seekg(0, colorfile.beg);
boost::dynamic_bitset<> A(vecBits);
boost::dynamic_bitset<> rnk(vecBits);
int curPos = 0;
for (size_t i=0; i < num_edges; i++) {
color_bv value;
deserialize_color_bv(colorfile, value);
// std::cout<<value<<":"<<eqCls[value]<<" ";
rnk.set(curPos);
curPos = insertColorLabel(A, eqCls[value], curPos);
// if we want to set the end, here we should say b.set(curPos-1);
}
std::cerr << "\nA, rnk & eq. cls BVs creation time : " << getMilliSpan(sysTime) << " ms\n";
std::cout<<"A.bitvec:";
std::ofstream Aout("A.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(A, Aout)) {
std::cerr << "Oh noes; couldn't write A!\n";
}
Aout.close();
std::cout<<"B.bitvec:";
std::ofstream Bout("B.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(rnk, Bout)) {
std::cerr << "Oh noes; couldn't write B!\n";
}
Bout.close();
std::cout<<"eqTable.bitvec:";
std::ofstream eqTableout("eqTable.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(eqTable, eqTableout)) {
std::cerr << "Oh noes; couldn't write eqTable!\n";
}
eqTableout.close();
//std::cerr << "********************** A ***********************\n" << A;
//std::cerr << "********************** rank ***********************\n" << rnk;
/*
sysTime = getMilliCount();
sd_vector<> sdb(b);
std::cerr << "SD Creation Time: " << getMilliSpan(sysTime) << endl;
sysTime = getMilliCount();
for (size_t i=0; i < num_edges*num_color; i++) {
sdb[i];
}
std::cerr << "SD Access Time: " << getMilliSpan(sysTime) << endl;
std::cerr << "SD Size (MB): " << size_in_mega_bytes(sdb) << endl;
sysTime = getMilliCount();
hyb_vector<> hyb(b);
std::cerr << "Hyb Creation Time: " << getMilliSpan(sysTime) << endl;
sysTime = getMilliCount();
for (size_t i=0; i < num_edges*num_color; i++) {
hyb[i];
}
std::cerr << "Hyb Access Time: " << getMilliSpan(sysTime) << endl;
std::cerr << "Hyb Size (MB): " << size_in_mega_bytes(hyb) << endl;
*/
}
<commit_msg>Change type of totalBits and curPos<commit_after>
#include <iostream>
#include <fstream>
#include <utility>
#include <ctime>
// TCLAP
#include "tclap/CmdLine.h"
#include <sdsl/bit_vectors.hpp>
#include <cstdio>
#include <cstdlib>
#include <libgen.h>
#include <sparsepp/spp.h>
#include <boost/dynamic_bitset.hpp>
using spp::sparse_hash_map;
// Custom Headers
//#include "uint128_t.hpp"
//#include "debug.h"
#include "kmer.hpp"
//using namespace std;
//using namespace sdsl;
#include <cstdlib>
#include <sys/timeb.h>
#include "pack-color.hpp"
#include <bitset>
int getMilliCount()
{
timeb tb;
ftime(&tb);
int nCount = tb.millitm + (tb.time & 0xfffff) * 1000;
return nCount;
}
int getMilliSpan(int nTimeStart)
{
int nSpan = getMilliCount() - nTimeStart;
if(nSpan < 0)
nSpan += 0x100000 * 1000;
return nSpan;
}
std::string file_extension = ".<extension>";
void parse_arguments(int argc, char **argv, parameters_t & params)
{
TCLAP::CmdLine cmd("Cosmo Copyright (c) Alex Bowe (alexbowe.com) 2014", ' ', VERSION);
TCLAP::UnlabeledValueArg<std::string> input_filename_arg("input",
"Input file. Currently only supports DSK's binary format (for k<=64).", true, "", "input_file", cmd);
TCLAP::UnlabeledValueArg<std::string> num_colors_arg("num_colors",
"Number of colors", true, "", "num colors", cmd);
cmd.parse( argc, argv );
params.input_filename = input_filename_arg.getValue();
params.num_colors = atoi(num_colors_arg.getValue().c_str());
}
void deserialize_color_bv(std::ifstream &colorfile, color_bv &value)
{
colorfile.read((char *)&value, sizeof(color_bv));
}
size_t insertColorLabel(boost::dynamic_bitset<>& bs, unsigned num, size_t pos) {
// most significant bit of number goes down to the end of the bitset
do {
if (num&1) {
bs.set(pos);
}
num>>=1;
pos++;
} while(num);
return pos;
}
bool writeBitset(boost::dynamic_bitset<>& bs, std::ofstream& out) {
int bitctr{7};
unsigned char byte{0};
size_t bs_size = bs.size();
std::cout<<bs_size<<"\n";
out.write(reinterpret_cast<char*>(&bs_size), sizeof(bs_size));
for (size_t i = 0; i < bs.size(); ++i) {
byte |= (bs[i] << bitctr);
if (bitctr == 0) {
out.write(reinterpret_cast<char*>(&byte), sizeof(byte));
byte = 0;
bitctr = 8;
}
bitctr--;
}
if (bitctr > 0) {
out.write(reinterpret_cast<char*>(&byte), sizeof(byte));
}
return true;
}
int main(int argc, char * argv[])
{
std::cerr << "pack-color compiled with supported colors=" << NUM_COLS << std::endl;
std::cerr <<"Starting" << std::endl;
parameters_t params;
parse_arguments(argc, argv, params);
const char * file_name = params.input_filename.c_str();
std::cerr << "file name: " << file_name << std::endl;
// Open File
std::ifstream colorfile(file_name, std::ios::in|std::ios::binary);
colorfile.seekg(0, colorfile.end);
size_t end = colorfile.tellg();
colorfile.seekg(0, colorfile.beg);
std::cerr << "file size: " << end << std::endl;
std::cerr << "sizeof(color_bv): " << sizeof(color_bv) << std::endl;
size_t num_color = params.num_colors;
size_t num_edges = end / sizeof(color_bv);
size_t cnt0 = 0;
size_t cnt1 = 0;
std::cerr << "edges: " << num_edges << " colors: " << num_color << " Total: " << num_edges * num_color << std::endl;
sparse_hash_map<color_bv, int> eqCls;
for (size_t i=0; i < num_edges; i++) {
if (i % 100000000 == 0) {
std::cerr << "deserializing edge " << i
<< " cnt0: " << cnt0
<< " cnt1: " << cnt1 << std::endl;
}
color_bv value;
deserialize_color_bv(colorfile, value);
if (eqCls.find(value)==eqCls.end())
eqCls[value] = 1;
else
eqCls[value] = eqCls[value]+1;
}
std::cerr << "Succinct builder object allocated." << std::endl;
std::vector<std::pair<color_bv, int>> eqClsVec;
eqClsVec.reserve(eqCls.size());
for (const auto& c : eqCls) { eqClsVec.push_back(c); }
// sort the hashmap
auto cmp = [](std::pair<color_bv, int> const & a, std::pair<color_bv, int> const & b)
{
return a.second > b.second;
};
std::sort(eqClsVec.begin(), eqClsVec.end(), cmp);
boost::dynamic_bitset<> eqTable(eqCls.size()*num_color);
size_t i = 0;
for (const auto& c : eqClsVec) {
for (size_t j = 0; j < num_color; ++j) {
eqTable[i] = c.first[j];
i++;
}
}
std::cout<<"Eq. cls BV:\n"<<eqTable<<"\n";
// replacing labels instead of k-mer counts as the hash map values
int lbl = 0;
size_t totalBits = 0;
for (const auto& c : eqClsVec) {
//std::cerr <<"eq cls "<<lbl++<< ": "<<c.first<<" : "<<c.second << "\n";
totalBits += (lbl==0?c.second:ceil(log2(lbl+1))*c.second);
eqCls[c.first] = lbl++;
std::cout<<c.first<<":"<<eqCls[c.first];
}
size_t vecBits = totalBits;
totalBits *= 2;
totalBits += num_color * eqCls.size();
std::cerr << "total bits: " << totalBits << " or " << totalBits/(8*pow(1024,2)) << " MBs\n";
// creating bitvectors A and b
// A contains eq. class label for each k-mer in bits
// b is set in the start position of each k-mer in A
int sysTime = getMilliCount();
colorfile.seekg(0, colorfile.beg);
boost::dynamic_bitset<> A(vecBits);
boost::dynamic_bitset<> rnk(vecBits);
size_t curPos = 0;
for (size_t i=0; i < num_edges; i++) {
color_bv value;
deserialize_color_bv(colorfile, value);
// std::cout<<value<<":"<<eqCls[value]<<" ";
rnk.set(curPos);
curPos = insertColorLabel(A, eqCls[value], curPos);
// if we want to set the end, here we should say b.set(curPos-1);
}
std::cerr << "\nA, rnk & eq. cls BVs creation time : " << getMilliSpan(sysTime) << " ms\n";
std::cout<<"A.bitvec:";
std::ofstream Aout("A.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(A, Aout)) {
std::cerr << "Oh noes; couldn't write A!\n";
}
Aout.close();
std::cout<<"B.bitvec:";
std::ofstream Bout("B.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(rnk, Bout)) {
std::cerr << "Oh noes; couldn't write B!\n";
}
Bout.close();
std::cout<<"eqTable.bitvec:";
std::ofstream eqTableout("eqTable.bitvec", std::ios::out|std::ios::binary);
if (!writeBitset(eqTable, eqTableout)) {
std::cerr << "Oh noes; couldn't write eqTable!\n";
}
eqTableout.close();
//std::cerr << "********************** A ***********************\n" << A;
//std::cerr << "********************** rank ***********************\n" << rnk;
/*
sysTime = getMilliCount();
sd_vector<> sdb(b);
std::cerr << "SD Creation Time: " << getMilliSpan(sysTime) << endl;
sysTime = getMilliCount();
for (size_t i=0; i < num_edges*num_color; i++) {
sdb[i];
}
std::cerr << "SD Access Time: " << getMilliSpan(sysTime) << endl;
std::cerr << "SD Size (MB): " << size_in_mega_bytes(sdb) << endl;
sysTime = getMilliCount();
hyb_vector<> hyb(b);
std::cerr << "Hyb Creation Time: " << getMilliSpan(sysTime) << endl;
sysTime = getMilliCount();
for (size_t i=0; i < num_edges*num_color; i++) {
hyb[i];
}
std::cerr << "Hyb Access Time: " << getMilliSpan(sysTime) << endl;
std::cerr << "Hyb Size (MB): " << size_in_mega_bytes(hyb) << endl;
*/
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.272); FILE MERGED 2005/09/05 14:01:06 rt 1.1.1.1.272.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2013-2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "utest/utest.h"
#include "unity/unity.h"
#if !DEVICE_LPTICKER
#error [NOT_SUPPORTED] Low power ticker not supported for this target
#endif
using utest::v1::Case;
static const int test_timeout = 10;
#define TICKER_COUNT 16
#define MULTI_TICKER_TIME_MS 100
/* Due to poor accuracy of LowPowerTicker on many platforms
there is no sense to tune tolerance value as it was in Ticker tests.
Tolerance value is set to 500us for measurement inaccuracy + 5% tolerance
for LowPowerTicker. */
#define TOLERANCE_US(DELAY) (500 + DELAY / 20)
volatile uint32_t ticker_callback_flag;
volatile uint32_t multi_counter;
Timer gtimer;
void sem_release(Semaphore *sem)
{
sem->release();
}
void stop_gtimer_set_flag(void)
{
gtimer.stop();
core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1);
}
void increment_multi_counter(void)
{
core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1);;
}
/** Test many tickers run one after the other
Given many Tickers
When schedule them one after the other with the same time intervals
Then tickers properly execute callbacks
When schedule them one after the other with the different time intervals
Then tickers properly execute callbacks
*/
void test_multi_ticker(void)
{
LowPowerTicker ticker[TICKER_COUNT];
const uint32_t extra_wait = 10; // extra 10ms wait time
multi_counter = 0;
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].attach_us(callback(increment_multi_counter), MULTI_TICKER_TIME_MS * 1000);
}
Thread::wait(MULTI_TICKER_TIME_MS + extra_wait);
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].detach();
}
TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter);
multi_counter = 0;
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].attach_us(callback(increment_multi_counter), (MULTI_TICKER_TIME_MS + i) * 1000);
}
Thread::wait(MULTI_TICKER_TIME_MS + TICKER_COUNT + extra_wait);
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].detach();
}
TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter);
}
/** Test multi callback time
Given a Ticker
When the callback is attached multiple times
Then ticker properly execute callback multiple times
*/
void test_multi_call_time(void)
{
LowPowerTicker ticker;
int time_diff;
const int attach_count = 10;
for (int i = 0; i < attach_count; i++) {
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000);
while(!ticker_callback_flag);
time_diff = gtimer.read_us();
TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US(MULTI_TICKER_TIME_MS * 1000), MULTI_TICKER_TIME_MS * 1000, time_diff);
}
}
/** Test if detach cancel scheduled callback event
Given a Ticker with callback attached
When the callback is detached
Then the callback is not being called
*/
void test_detach(void)
{
LowPowerTicker ticker;
int32_t ret;
const float ticker_time_s = 0.1f;
const uint32_t wait_time_ms = 500;
Semaphore sem(0, 1);
ticker.attach(callback(sem_release, &sem), ticker_time_s);
ret = sem.wait();
TEST_ASSERT_TRUE(ret > 0);
ret = sem.wait();
ticker.detach(); /* cancel */
TEST_ASSERT_TRUE(ret > 0);
ret = sem.wait(wait_time_ms);
TEST_ASSERT_EQUAL(0, ret);
}
/** Test single callback time via attach
Given a Ticker
When callback attached with time interval specified
Then ticker properly executes callback within a specified time interval
*/
template<us_timestamp_t DELAY_US>
void test_attach_time(void)
{
LowPowerTicker ticker;
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f);
while(!ticker_callback_flag);
ticker.detach();
const int time_diff = gtimer.read_us();
TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff);
}
/** Test single callback time via attach_us
Given a Ticker
When callback attached with time interval specified
Then ticker properly executes callback within a specified time interval
*/
template<us_timestamp_t DELAY_US>
void test_attach_us_time(void)
{
LowPowerTicker ticker;
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US);
while(!ticker_callback_flag);
ticker.detach();
const int time_diff = gtimer.read_us();
TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff);
}
// Test cases
Case cases[] = {
Case("Test attach for 0.001s and time measure", test_attach_time<1000>),
Case("Test attach_us for 1ms and time measure", test_attach_us_time<1000>),
Case("Test attach for 0.01s and time measure", test_attach_time<10000>),
Case("Test attach_us for 10ms and time measure", test_attach_us_time<10000>),
Case("Test attach for 0.1s and time measure", test_attach_time<100000>),
Case("Test attach_us for 100ms and time measure", test_attach_us_time<100000>),
Case("Test attach for 0.5s and time measure", test_attach_time<500000>),
Case("Test attach_us for 500ms and time measure", test_attach_us_time<500000>),
Case("Test detach", test_detach),
Case("Test multi call and time measure", test_multi_call_time),
Case("Test multi ticker", test_multi_ticker),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(test_timeout, "timing_drift_auto");
return utest::v1::greentea_test_setup_handler(number_of_cases);
}
utest::v1::Specification specification(greentea_test_setup, cases, utest::v1::greentea_test_teardown_handler);
int main()
{
utest::v1::Harness::run(specification);
}
<commit_msg>tests-mbed_drivers-lp_ticker: increase tolerance for NRF51_DK<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2013-2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "utest/utest.h"
#include "unity/unity.h"
#if !DEVICE_LPTICKER
#error [NOT_SUPPORTED] Low power ticker not supported for this target
#endif
using utest::v1::Case;
static const int test_timeout = 10;
#define TICKER_COUNT 16
#define MULTI_TICKER_TIME_MS 100
/* Due to poor accuracy of LowPowerTicker on many platforms
there is no sense to tune tolerance value as it was in Ticker tests.
Tolerance value is set to 600us for measurement inaccuracy + 5% tolerance
for LowPowerTicker. */
#define TOLERANCE_US(DELAY) (600 + DELAY / 20)
volatile uint32_t ticker_callback_flag;
volatile uint32_t multi_counter;
Timer gtimer;
void sem_release(Semaphore *sem)
{
sem->release();
}
void stop_gtimer_set_flag(void)
{
gtimer.stop();
core_util_atomic_incr_u32((uint32_t*)&ticker_callback_flag, 1);
}
void increment_multi_counter(void)
{
core_util_atomic_incr_u32((uint32_t*)&multi_counter, 1);;
}
/** Test many tickers run one after the other
Given many Tickers
When schedule them one after the other with the same time intervals
Then tickers properly execute callbacks
When schedule them one after the other with the different time intervals
Then tickers properly execute callbacks
*/
void test_multi_ticker(void)
{
LowPowerTicker ticker[TICKER_COUNT];
const uint32_t extra_wait = 10; // extra 10ms wait time
multi_counter = 0;
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].attach_us(callback(increment_multi_counter), MULTI_TICKER_TIME_MS * 1000);
}
Thread::wait(MULTI_TICKER_TIME_MS + extra_wait);
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].detach();
}
TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter);
multi_counter = 0;
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].attach_us(callback(increment_multi_counter), (MULTI_TICKER_TIME_MS + i) * 1000);
}
Thread::wait(MULTI_TICKER_TIME_MS + TICKER_COUNT + extra_wait);
for (int i = 0; i < TICKER_COUNT; i++) {
ticker[i].detach();
}
TEST_ASSERT_EQUAL(TICKER_COUNT, multi_counter);
}
/** Test multi callback time
Given a Ticker
When the callback is attached multiple times
Then ticker properly execute callback multiple times
*/
void test_multi_call_time(void)
{
LowPowerTicker ticker;
int time_diff;
const int attach_count = 10;
for (int i = 0; i < attach_count; i++) {
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach_us(callback(stop_gtimer_set_flag), MULTI_TICKER_TIME_MS * 1000);
while(!ticker_callback_flag);
time_diff = gtimer.read_us();
TEST_ASSERT_UINT32_WITHIN(TOLERANCE_US(MULTI_TICKER_TIME_MS * 1000), MULTI_TICKER_TIME_MS * 1000, time_diff);
}
}
/** Test if detach cancel scheduled callback event
Given a Ticker with callback attached
When the callback is detached
Then the callback is not being called
*/
void test_detach(void)
{
LowPowerTicker ticker;
int32_t ret;
const float ticker_time_s = 0.1f;
const uint32_t wait_time_ms = 500;
Semaphore sem(0, 1);
ticker.attach(callback(sem_release, &sem), ticker_time_s);
ret = sem.wait();
TEST_ASSERT_TRUE(ret > 0);
ret = sem.wait();
ticker.detach(); /* cancel */
TEST_ASSERT_TRUE(ret > 0);
ret = sem.wait(wait_time_ms);
TEST_ASSERT_EQUAL(0, ret);
}
/** Test single callback time via attach
Given a Ticker
When callback attached with time interval specified
Then ticker properly executes callback within a specified time interval
*/
template<us_timestamp_t DELAY_US>
void test_attach_time(void)
{
LowPowerTicker ticker;
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach(callback(stop_gtimer_set_flag), ((float)DELAY_US) / 1000000.0f);
while(!ticker_callback_flag);
ticker.detach();
const int time_diff = gtimer.read_us();
TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff);
}
/** Test single callback time via attach_us
Given a Ticker
When callback attached with time interval specified
Then ticker properly executes callback within a specified time interval
*/
template<us_timestamp_t DELAY_US>
void test_attach_us_time(void)
{
LowPowerTicker ticker;
ticker_callback_flag = 0;
gtimer.reset();
gtimer.start();
ticker.attach_us(callback(stop_gtimer_set_flag), DELAY_US);
while(!ticker_callback_flag);
ticker.detach();
const int time_diff = gtimer.read_us();
TEST_ASSERT_UINT64_WITHIN(TOLERANCE_US(DELAY_US), DELAY_US, time_diff);
}
// Test cases
Case cases[] = {
Case("Test attach for 0.001s and time measure", test_attach_time<1000>),
Case("Test attach_us for 1ms and time measure", test_attach_us_time<1000>),
Case("Test attach for 0.01s and time measure", test_attach_time<10000>),
Case("Test attach_us for 10ms and time measure", test_attach_us_time<10000>),
Case("Test attach for 0.1s and time measure", test_attach_time<100000>),
Case("Test attach_us for 100ms and time measure", test_attach_us_time<100000>),
Case("Test attach for 0.5s and time measure", test_attach_time<500000>),
Case("Test attach_us for 500ms and time measure", test_attach_us_time<500000>),
Case("Test detach", test_detach),
Case("Test multi call and time measure", test_multi_call_time),
Case("Test multi ticker", test_multi_ticker),
};
utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(test_timeout, "timing_drift_auto");
return utest::v1::greentea_test_setup_handler(number_of_cases);
}
utest::v1::Specification specification(greentea_test_setup, cases, utest::v1::greentea_test_teardown_handler);
int main()
{
utest::v1::Harness::run(specification);
}
<|endoftext|> |
<commit_before>/*
** Copyright 2015 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#include <cstdlib>
#include <iostream>
#include <sstream>
#include "test/cbd.hh"
#include "test/centengine.hh"
#include "test/centengine_config.hh"
#include "test/db.hh"
#include "test/file.hh"
#include "test/misc.hh"
#include "test/predicate.hh"
#include "test/time_points.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define TEST_NAME "rtmonitoring_v2_hostgroups"
#define DB_NAME "broker_" TEST_NAME
// Check count.
static int check_number(0);
/**
* Precheck routine.
*/
static void precheck(test::time_points& tpoints, char const* name) {
++check_number;
std::cout << "check #" << check_number << " (" << name << ")\n";
tpoints.store();
return ;
}
/**
* Postcheck routine.
*/
static void postcheck(
test::centengine& engine,
test::time_points& tpoints,
test::db& db,
test::predicate expected_groups[][2],
test::predicate expected_members[][2]) {
static std::string group_query(
"SELECT hostgroup_id, name"
" FROM hostgroups"
" ORDER BY hostgroup_id ASC");
static std::string member_query(
"SELECT hostgroup_id, host_id"
" FROM hosts_hostgroups"
" ORDER BY hostgroup_id ASC, host_id ASC");
engine.reload();
test::sleep_for(3);
tpoints.store();
db.check_content(group_query, expected_groups);
db.check_content(member_query, expected_members);
std::cout << " passed\n";
return ;
}
/**
* Check that the hostgroups and the hosts_hostgroups tables are
* working properly.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Error flag.
bool error(true);
try {
// Database.
char const* tables[] = {
"instances", "hosts", "hostgroups", "hosts_hostgroups", NULL
};
test::db db(DB_NAME, tables);
// Monitoring broker.
test::file cbd_cfg;
cbd_cfg.set_template(
PROJECT_SOURCE_DIR "/test/cfg/sql.xml.in");
cbd_cfg.set("BROKER_ID", "84");
cbd_cfg.set("BROKER_NAME", TEST_NAME "-cbd");
cbd_cfg.set("POLLER_ID", "42");
cbd_cfg.set("POLLER_NAME", "my-poller");
cbd_cfg.set("TCP_PORT", "5573");
cbd_cfg.set("DB_NAME", DB_NAME);
cbd_cfg.set(
"SQL_ADDITIONAL",
"<write_filters>"
" <category>neb:instance</category>"
" <category>neb:instance_status</category>"
" <category>neb:host</category>"
" <category>neb:host_check</category>"
" <category>neb:host_status</category>"
" <category>neb:host_group</category>"
" <category>neb:host_group_member</category>"
"</write_filters>");
test::cbd broker;
broker.set_config_file(cbd_cfg.generate());
broker.start();
test::sleep_for(1);
// Monitoring engine.
test::file cbmod_cfg;
cbmod_cfg.set_template(
PROJECT_SOURCE_DIR "/test/cfg/tcp.xml.in");
cbmod_cfg.set("BROKER_ID", "83");
cbmod_cfg.set("BROKER_NAME", TEST_NAME "-cbmod");
cbmod_cfg.set("POLLER_ID", "42");
cbmod_cfg.set("POLLER_NAME", "my-poller");
cbmod_cfg.set("TCP_HOST", "localhost");
cbmod_cfg.set("TCP_PORT", "5573");
test::centengine_config engine_config;
engine_config.generate_hosts(10);
engine_config.generate_services(2);
for (int i(0); i < 5; ++i) {
test::centengine_object
group(test::centengine_object::hostgroup_type);
{
std::ostringstream group_name;
group_name << "group" << i + 1;
group.set("hostgroup_name", group_name.str());
}
{
std::ostringstream group_id;
group_id << i + 1;
group.set("hostgroup_id", group_id.str());
}
{
std::ostringstream members;
members << i * 2 + 1 << "," << i * 2 + 2;
group.set("members", members.str());
}
engine_config.get_host_groups().push_back(group);
}
engine_config.set_cbmod_cfg_file(cbmod_cfg.generate());
test::centengine engine(&engine_config);
// Time points.
test::time_points tpoints;
// Check default entries.
precheck(tpoints, "hostgroups");
engine.start();
test::sleep_for(1);
test::predicate expected_groups[][2] = {
{ 1, "group1" },
{ 2, "group2" },
{ 3, "group3" },
{ 4, "group4" },
{ 5, "group5" },
{ test::predicate() }
};
test::predicate expected_members[][2] = {
{ 1, 1 },
{ 1, 2 },
{ 2, 3 },
{ 2, 4 },
{ 3, 5 },
{ 3, 6 },
{ 4, 7 },
{ 4, 8 },
{ 5, 9 },
{ 5, 10 },
{ test::predicate() }
};
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Change host group name.
// Add members.
// Remove members.
// Remove all members.
// Success.
error = false;
db.set_remove_db_on_close(true);
broker.stop();
}
catch (std::exception const& e) {
std::cout << " " << e.what() << "\n";
}
catch (...) {
std::cout << " unknown exception\n";
}
return (error ? EXIT_FAILURE : EXIT_SUCCESS);
}
<commit_msg>test: host groups test is working.<commit_after>/*
** Copyright 2015 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/
#include <cstdlib>
#include <iostream>
#include <sstream>
#include "test/cbd.hh"
#include "test/centengine.hh"
#include "test/centengine_config.hh"
#include "test/db.hh"
#include "test/file.hh"
#include "test/misc.hh"
#include "test/predicate.hh"
#include "test/time_points.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define TEST_NAME "rtmonitoring_v2_hostgroups"
#define DB_NAME "broker_" TEST_NAME
// Check count.
static int check_number(0);
/**
* Precheck routine.
*/
static void precheck(test::time_points& tpoints, char const* name) {
++check_number;
std::cout << "check #" << check_number << " (" << name << ")\n";
tpoints.store();
return ;
}
/**
* Postcheck routine.
*/
static void postcheck(
test::centengine& engine,
test::time_points& tpoints,
test::db& db,
test::predicate expected_groups[][2],
test::predicate expected_members[][2]) {
static std::string group_query(
"SELECT hostgroup_id, name"
" FROM hostgroups"
" ORDER BY hostgroup_id ASC");
static std::string member_query(
"SELECT hostgroup_id, host_id"
" FROM hosts_hostgroups"
" ORDER BY hostgroup_id ASC, host_id ASC");
engine.reload();
test::sleep_for(3);
tpoints.store();
db.check_content(group_query, expected_groups);
db.check_content(member_query, expected_members);
std::cout << " passed\n";
return ;
}
/**
* Check that the hostgroups and the hosts_hostgroups tables are
* working properly.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Error flag.
bool error(true);
try {
// Database.
char const* tables[] = {
"instances", "hosts", "hostgroups", "hosts_hostgroups", NULL
};
test::db db(DB_NAME, tables);
// Monitoring broker.
test::file cbd_cfg;
cbd_cfg.set_template(
PROJECT_SOURCE_DIR "/test/cfg/sql.xml.in");
cbd_cfg.set("BROKER_ID", "84");
cbd_cfg.set("BROKER_NAME", TEST_NAME "-cbd");
cbd_cfg.set("POLLER_ID", "42");
cbd_cfg.set("POLLER_NAME", "my-poller");
cbd_cfg.set("TCP_PORT", "5573");
cbd_cfg.set("DB_NAME", DB_NAME);
cbd_cfg.set(
"SQL_ADDITIONAL",
"<write_filters>"
" <category>neb:instance</category>"
" <category>neb:instance_status</category>"
" <category>neb:host</category>"
" <category>neb:host_check</category>"
" <category>neb:host_status</category>"
" <category>neb:host_group</category>"
" <category>neb:host_group_member</category>"
"</write_filters>");
test::cbd broker;
broker.set_config_file(cbd_cfg.generate());
broker.start();
test::sleep_for(1);
// Monitoring engine.
test::file cbmod_cfg;
cbmod_cfg.set_template(
PROJECT_SOURCE_DIR "/test/cfg/tcp.xml.in");
cbmod_cfg.set("BROKER_ID", "83");
cbmod_cfg.set("BROKER_NAME", TEST_NAME "-cbmod");
cbmod_cfg.set("POLLER_ID", "42");
cbmod_cfg.set("POLLER_NAME", "my-poller");
cbmod_cfg.set("TCP_HOST", "localhost");
cbmod_cfg.set("TCP_PORT", "5573");
test::centengine_config engine_config;
engine_config.generate_hosts(10);
engine_config.generate_services(2);
for (int i(0); i < 5; ++i) {
test::centengine_object
group(test::centengine_object::hostgroup_type);
{
std::ostringstream group_name;
group_name << "group" << i + 1;
group.set("hostgroup_name", group_name.str());
}
{
std::ostringstream group_id;
group_id << i + 1;
group.set("hostgroup_id", group_id.str());
}
{
std::ostringstream members;
members << i * 2 + 1 << "," << i * 2 + 2;
group.set("members", members.str());
}
engine_config.get_host_groups().push_back(group);
}
engine_config.set_cbmod_cfg_file(cbmod_cfg.generate());
test::centengine engine(&engine_config);
// Time points.
test::time_points tpoints;
// Check default entries.
precheck(tpoints, "hostgroups.insert");
engine.start();
test::sleep_for(1);
test::predicate expected_groups[][2] = {
{ 1, "group1" },
{ 2, "group2" },
{ 3, "group3" },
{ 4, "group4" },
{ 5, "group5" },
{ test::predicate() }
};
test::predicate expected_members[20][2] = {
{ 1, 1 },
{ 1, 2 },
{ 2, 3 },
{ 2, 4 },
{ 3, 5 },
{ 3, 6 },
{ 4, 7 },
{ 4, 8 },
{ 5, 9 },
{ 5, 10 },
{ test::predicate() }
};
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Change host group name.
precheck(tpoints, "hostgroups.update");
test::centengine_object&
hg(engine_config.get_host_groups().front());
hg.set("hostgroup_name", "renamed");
expected_groups[0][1] = "renamed";
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Add members.
precheck(tpoints, "hosts_hostgroups.insert");
hg.set("members", "1,3,5,7,9");
// The first 5 entries will be the members of group 1. All other
// entries will remain valid but have to be moved at the end of the
// array.
for (int i(7); i >= 0; --i) {
expected_members[i + 5][0] = expected_members[i + 2][0];
expected_members[i + 5][1] = expected_members[i + 2][1];
}
for (int i(0); i < 5; ++i) {
expected_members[i][0] = 1;
expected_members[i][1] = i * 2 + 1;
}
expected_members[13][0] = test::predicate();
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Remove members.
precheck(tpoints, "hosts_hostgroups.delete");
hg.set("members", "5");
// Move entries.
for (int i(0); i < 8; ++i) {
expected_members[i + 1][0] = expected_members[i + 5][0];
expected_members[i + 1][1] = expected_members[i + 5][1];
}
expected_members[0][0] = 1;
expected_members[0][1] = 5;
expected_members[9][0] = test::predicate();
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Remove all members.
precheck(tpoints, "hostgroups.delete");
for (test::centengine_config::objlist::iterator
it(engine_config.get_host_groups().begin()),
end(engine_config.get_host_groups().end());
it != end;
++it)
it->set("members", "");
expected_groups[0][0] = test::predicate();
expected_members[0][0] = test::predicate();
postcheck(engine, tpoints, db, expected_groups, expected_members);
// Success.
error = false;
db.set_remove_db_on_close(true);
broker.stop();
}
catch (std::exception const& e) {
std::cout << " " << e.what() << "\n";
}
catch (...) {
std::cout << " unknown exception\n";
}
return (error ? EXIT_FAILURE : EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
using namespace std;
void callback(const sensor_msgs::PointCloud2ConstPtr& cloud) {
ROS_INFO("Callback! %d %d", cloud->width, cloud->height);
pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "stairwaydetector");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2>("/camera/depth/points", 1, callback);
ros::spin();
return 0;
}
<commit_msg>[stairs] much more plane detection<commit_after>#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/visualization/cloud_viewer.h>
using namespace std;
ros::Publisher pub;
void callback(const sensor_msgs::PointCloud2ConstPtr& input) {
ROS_INFO("Callback! %d %d", input->width, input->height);
// convert from ros::pointcloud2 to pcl::pointcloud2
pcl::PCLPointCloud2* unfilteredCloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr unfilteredCloudPtr(unfilteredCloud);
pcl_conversions::toPCL(*input, *unfilteredCloud);
// create a voxelgrid to downsample the input data to speed things up.
pcl::PCLPointCloud2::Ptr cloudBlob (new pcl::PCLPointCloud2);
pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud(unfilteredCloudPtr);
sor.setLeafSize(0.01f, 0.01f, 0.01f);
sor.filter(*cloudBlob);
// convert to pointcloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(*cloudBlob, *cloud);
// Does the parametric segmentation
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
pcl::SACSegmentation<pcl::PointXYZ> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMaxIterations(1000);
seg.setDistanceThreshold(0.01);
pcl::ExtractIndices<pcl::PointXYZ> extract;
// while 30% of the original cloud is still there
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>),
cloud2(new pcl::PointCloud<pcl::PointXYZ>);
unsigned int i = 0, pointsAtStart = cloud->points.size();
//while (cloud->points.size() > 0.3 * pointsAtStart) {
seg.setInputCloud(cloud);
seg.segment(*inliers, *coefficients);
if (inliers->indices.size() == 0) {
ROS_WARN("Could not estimate a planar model for the given dataset.");
//break;
}
// extract the inliers
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(false);
extract.filter(*cloud1);
std::cerr << "PointCloud representing the planar component: " << cloud1->width * cloud1->height
<< " data points." << std::endl;
std::cerr << "Model coefficients: " << coefficients->values[0] << " "
<< coefficients->values[1] << " "
<< coefficients->values[2] << " "
<< coefficients->values[3] << std::endl;
extract.setNegative(true);
extract.filter(*cloud2);
cloud.swap(cloud2);
i++;
//}
//exit(0);
sensor_msgs::PointCloud2 output;
pcl::toROSMsg(*cloud1, output);
pub.publish(output);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "stairwaydetector");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2>("/camera/depth/points", 1, callback);
pub = nh.advertise<sensor_msgs::PointCloud2>("/output", 1);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#include "Polymer.h"
#include<cmath>
#include<iostream>
#include<stdlib.h>
void Polymer::Initiate_monomer_array(double pos, double vel) {
delete A_monomer;
A_monomer = new Monomer [A_length];
if (pos != 0 && vel != 0)
for (int i=0;i<A_length;i++)
A_monomer[i].Set_pos_vel((rand()%5)*9./10,0);//A_monomer[i].Set_pos_vel(pos,vel);
}
void Polymer::Initiate_polymer_std() {
A_length=0;
A_monomer=0;
Temp_soll=0;
Ekin=Epot=0;
}
Polymer::Polymer() {
Initiate_polymer_std();
Initiate_monomer_array(0,0);
}
Polymer::Polymer(int len) {
Initiate_polymer_std();
A_length=len;
Initiate_monomer_array(0,0);
}
Polymer::Polymer(int len,double pos, double vel) {
Initiate_polymer_std();
A_length=len;
Initiate_monomer_array(pos,vel);
}
Polymer::~Polymer() { delete[] A_monomer; A_monomer = 0;}
std::ostream & Polymer::Print(std::ostream &os) const {
for (int i=0;i<A_length;i++) {
A_monomer[i].Print(os);
os << std::endl;
}
return os;
}
double Polymer::Force(double r) {
double s=1, e=1, sr6=pow(s/r,6);
if (r==0)
return 0;
return -24*e*(2*pow(sr6,2)/r-sr6/r);
}
void Polymer::Calculate_force() {
int i=0, force_buf=0;
//wahrscheinlich durch Optimierung der nächsten Schleife unnötig
for (i=0;i<A_length;i++)
A_monomer[i].Reset_force();
for (i=1;i<A_length;i++) {
force_buf=Force(A_monomer[i-1]-A_monomer[i]);
A_monomer[i-1].Add_force(force_buf); //bin mir da mit dem Vorzeichen nicht sicher!
A_monomer[i].Add_force(-force_buf);
}
force_buf=Force(A_monomer[A_length-1]-A_monomer[0]);
A_monomer[A_length-1].Add_force(force_buf); //bin mir da mit dem Vorzeichen nicht sicher!
A_monomer[0].Add_force(-force_buf);
}
void Polymer::Next_position(double dt){
for (int i=0;i<A_length;i++)
A_monomer[i].Next_position(dt);
}
void Polymer::Next_velocity(double dt){
for (int i=0;i<A_length;i++)
A_monomer[i].Next_velocity(dt);
}
<commit_msg>mehr Formatierung<commit_after>#include "Polymer.h"
#include<cmath>
#include<iostream>
#include<stdlib.h>
void Polymer::Initiate_monomer_array(double pos, double vel) {
delete A_monomer;
A_monomer = new Monomer[A_length];
if (pos != 0 && vel != 0)
for (int i = 0; i < A_length; i++)
A_monomer[i].Set_pos_vel((rand() % 5)*9. / 10, 0);//A_monomer[i].Set_pos_vel(pos,vel);
}
void Polymer::Initiate_polymer_std() {
A_length = 0;
A_monomer = 0;
Temp_soll = 0;
Ekin = Epot = 0;
}
Polymer::Polymer() {
Initiate_polymer_std();
Initiate_monomer_array(0, 0);
}
Polymer::Polymer(int len) {
Initiate_polymer_std();
A_length = len;
Initiate_monomer_array(0, 0);
}
Polymer::Polymer(int len, double pos, double vel) {
Initiate_polymer_std();
A_length = len;
Initiate_monomer_array(pos, vel);
}
Polymer::~Polymer() { delete[] A_monomer; A_monomer = 0; }
std::ostream & Polymer::Print(std::ostream &os) const {
for (int i = 0; i < A_length; i++) {
A_monomer[i].Print(os);
os << std::endl;
}
return os;
}
double Polymer::Force(double r) {
double s = 1, e = 1, sr6 = pow(s / r, 6);
if (r == 0)
return 0;
return -24 * e*(2 * pow(sr6, 2) / r - sr6 / r);
}
void Polymer::Calculate_force() {
int i = 0, force_buf = 0;
//wahrscheinlich durch Optimierung der nächsten Schleife unnötig
for (i = 0; i < A_length; i++)
A_monomer[i].Reset_force();
for (i = 1; i < A_length; i++) {
force_buf = Force(A_monomer[i - 1] - A_monomer[i]);
A_monomer[i - 1].Add_force(force_buf); //bin mir da mit dem Vorzeichen nicht sicher!
A_monomer[i].Add_force(-force_buf);
}
force_buf = Force(A_monomer[A_length - 1] - A_monomer[0]);
A_monomer[A_length - 1].Add_force(force_buf); //bin mir da mit dem Vorzeichen nicht sicher!
A_monomer[0].Add_force(-force_buf);
}
void Polymer::Next_position(double dt){
for (int i = 0; i < A_length; i++)
A_monomer[i].Next_position(dt);
}
void Polymer::Next_velocity(double dt){
for (int i = 0; i < A_length; i++)
A_monomer[i].Next_velocity(dt);
}
<|endoftext|> |
<commit_before>#include <ContentForgeTool.h>
#include <Utils.h>
#include <HRDParser.h>
//#include <CLI11.hpp>
#include <thread>
//#include <mutex>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/effects
class CEffectTool : public CContentForgeTool
{
private:
// FIXME: common threadsafe logger for tasks instead of cout
//std::mutex COutMutex;
public:
CEffectTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual int Init() override
{
return 0;
}
virtual bool SupportsMultithreading() const override
{
// FIXME: must handle duplicate targets (for example 2 metafiles writing the same resulting file, like depth_atest_ps)
return false;
}
//virtual void ProcessCommandLine(CLI::App& CLIApp) override
//{
// CContentForgeTool::ProcessCommandLine(CLIApp);
// CLIApp.add_option("--db", _DBPath, "Shader DB file path");
// CLIApp.add_option("--is,--inputsig", _InputSignaturesDir, "Folder where input signature binaries will be saved");
//}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
// TODO: check whether the metafile can be processed by this tool
const std::string Output = GetParam<std::string>(Task.Params, "Output", std::string{});
const std::string TaskID(Task.TaskID.CStr());
const auto DestPath = fs::path(Output) / (TaskID + ".eff");
// FIXME: must be thread-safe, also can move to the common code
const auto LineEnd = std::cout.widen('\n');
if (_LogVerbosity >= EVerbosity::Debug)
{
std::cout << "Source: " << Task.SrcFilePath.generic_string() << LineEnd;
std::cout << "Task: " << Task.TaskID.CStr() << LineEnd;
std::cout << "Thread: " << std::this_thread::get_id() << LineEnd;
}
// Read effect hrd
Data::CParams Desc;
{
std::vector<char> In;
if (!ReadAllFile(Task.SrcFilePath.string().c_str(), In, false))
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << Task.SrcFilePath.generic_string() << " reading error" << LineEnd;
return false;
}
Data::CHRDParser Parser;
if (!Parser.ParseBuffer(In.data(), In.size(), Desc))
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << Task.SrcFilePath.generic_string() << " HRD parsing error" << LineEnd;
return false;
}
}
// Get and validate material type
const CStrID MaterialType = GetParam<CStrID>(Desc, "Type", CStrID::Empty);
if (!MaterialType)
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Material type not specified" << LineEnd;
return false;
}
// Get and validate global and material params
auto ItGlobalParams = Desc.find(CStrID("GlobalParams"));
const bool HasGlobalParams = (ItGlobalParams != Desc.cend() && !ItGlobalParams->second.IsVoid());
if (HasGlobalParams && !ItGlobalParams->second.IsA<Data::CDataArray>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'GlobalParams' must be an array of CStringID" << LineEnd;
return false;
}
auto ItMaterialParams = Desc.find(CStrID("MaterialParams"));
const bool HasMaterialParams = (ItMaterialParams != Desc.cend() && !ItMaterialParams->second.IsVoid());
if (HasMaterialParams && !ItMaterialParams->second.IsA<Data::CParams>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'MaterialParams' must be a section" << LineEnd;
return false;
}
if (HasGlobalParams && HasMaterialParams)
{
// Check intersections between global and material params
bool HasErrors = false;
const Data::CDataArray& GlobalParams = ItGlobalParams->second.GetValue<Data::CDataArray>();
const Data::CParams& MaterialParams = ItMaterialParams->second.GetValue<Data::CParams>();
for (const auto& Global : GlobalParams)
{
if (!Global.IsA<CStrID>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'GlobalParams' can contain only CStringID elements (single-quoted strings)" << LineEnd;
HasErrors = true;
}
const CStrID ParamID = Global.GetValue<CStrID>();
if (MaterialParams.find(ParamID) != MaterialParams.cend())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << '\'' << ParamID.CStr() << "' appears in both global and material params" << LineEnd;
HasErrors = true;
}
}
}
// Parse, validate and sort techniques
auto ItRenderStates = Desc.find(CStrID("RenderStates"));
if (ItRenderStates == Desc.cend() || !ItRenderStates->second.IsA<Data::CParams>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'RenderStates' must be a section" << LineEnd;
return false;
}
auto ItTechs = Desc.find(CStrID("Techniques"));
if (ItTechs == Desc.cend() || !ItTechs->second.IsA<Data::CParams>() || ItTechs->second.GetValue<Data::CParams>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'Techniques' must be a section and contain at least one input set" << LineEnd;
return false;
}
struct CRenderState
{
// pipeline settings
// shader data
uint32_t ShaderFormatFourCC;
uint8_t LightCount;
bool IsValid;
};
std::map<CStrID, CRenderState> RSCache;
const auto& RenderStates = ItRenderStates->second.GetValue<Data::CParams>();
const auto& InputSets = ItTechs->second.GetValue<Data::CParams>();
for (const auto& InputSet : InputSets)
{
if (!InputSet.second.IsA<Data::CParams>() || InputSet.second.GetValue<Data::CParams>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Input set '" << InputSet.first.CStr() << "' must be a section containing at least one technique" << LineEnd;
return false;
}
const auto& Techs = InputSet.second.GetValue<Data::CParams>();
for (const auto& Tech : Techs)
{
if (!Tech.second.IsA<Data::CDataArray>() || Tech.second.GetValue<Data::CDataArray>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "' must be an array containing at least one render state ID" << LineEnd;
return false;
}
// TODO:
// parse passes //???before techs to handle references properly?
// if has invalid or inexistent passes, write error
// if tech mixes shader formats, fail (or allow say DXBC+DXIL for D3D12? use newer format as tech format? DXIL in this case)
// if tech became empty, discard it
const auto& Passes = Tech.second.GetValue<Data::CDataArray>();
for (const auto& Pass : Passes)
{
const CStrID RenderStateID = Pass.GetValue<CStrID>();
if (_LogVerbosity >= EVerbosity::Debug)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "', pass '" << RenderStateID.CStr() << '\'' << LineEnd;
auto ItRS = RSCache.find(RenderStateID);
if (ItRS == RSCache.cend())
{
CRenderState NewState;
// load (base + overrides)
NewState.IsValid = false;
// get shader formats for all specified shaders
// if shader doesn't exist, fail
// if pass mixes shader formats, fail (or allow say DXBC+DXIL for D3D12? use newer format as tech format? DXIL in this case)
// collect feature level (max through all used shaders) - only for DX? additional fields can be based on tech format
// get max light count of all shaders in all passes (-1 = any, 0 = no lights in this pass)
// shader switching is costly, so we don't build per-light-count variations, but instead
// create the shader with max light count only
//???how to claculate max light count and whether the shader uses lights at all?
ItRS = RSCache.emplace(RenderStateID, std::move(NewState)).first;
}
const auto& RS = ItRS->second;
if (!RS.IsValid)
{
// Can discard only this tech, but for now issue an error and stop
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "' uses invalid render state in a pass '" << RenderStateID.CStr() << '\'' << LineEnd;
return false;
}
// collect info from the render state:
// shader format
// feature level
// light count
}
}
// All techs of the input set:
// sort techs by the feature level (descending), so that first loaded tech is the best
//???sort by shader format?
}
// FIXME: must be thread-safe, also can move to the common code
//if (_LogVerbosity >= EVerbosity::Debug)
// std::cout << "Status: " << (Ok ? "OK" : "FAIL") << LineEnd << LineEnd;
return true;
}
};
int main(int argc, const char** argv)
{
CEffectTool Tool("cf-effect", "DeusExMachina rendering effect compiler", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
<commit_msg>cf-effect render state loading WIP 2<commit_after>#include <ContentForgeTool.h>
#include <Utils.h>
#include <HRDParser.h>
//#include <CLI11.hpp>
#include <thread>
//#include <mutex>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
// Set working directory to $(TargetDir)
// Example args:
// -s src/effects
struct CRenderState
{
// pipeline settings
// shader data
uint32_t ShaderFormatFourCC = 0;
uint32_t MinFeatureLevel = 0;
uint32_t RequiresFlags = 0;
int8_t LightCount = -1;
bool IsValid = false;
};
class CEffectTool : public CContentForgeTool
{
private:
// FIXME: common threadsafe logger for tasks instead of cout
//std::mutex COutMutex;
public:
CEffectTool(const std::string& Name, const std::string& Desc, CVersion Version) :
CContentForgeTool(Name, Desc, Version)
{
// Set default before parsing command line
_RootDir = "../../../content";
}
virtual int Init() override
{
return 0;
}
virtual bool SupportsMultithreading() const override
{
// FIXME: must handle duplicate targets (for example 2 metafiles writing the same resulting file, like depth_atest_ps)
return false;
}
//virtual void ProcessCommandLine(CLI::App& CLIApp) override
//{
// CContentForgeTool::ProcessCommandLine(CLIApp);
// CLIApp.add_option("--db", _DBPath, "Shader DB file path");
// CLIApp.add_option("--is,--inputsig", _InputSignaturesDir, "Folder where input signature binaries will be saved");
//}
virtual bool ProcessTask(CContentForgeTask& Task) override
{
// TODO: check whether the metafile can be processed by this tool
const std::string Output = GetParam<std::string>(Task.Params, "Output", std::string{});
const std::string TaskID(Task.TaskID.CStr());
const auto DestPath = fs::path(Output) / (TaskID + ".eff");
// FIXME: must be thread-safe, also can move to the common code
const auto LineEnd = std::cout.widen('\n');
if (_LogVerbosity >= EVerbosity::Debug)
{
std::cout << "Source: " << Task.SrcFilePath.generic_string() << LineEnd;
std::cout << "Task: " << Task.TaskID.CStr() << LineEnd;
std::cout << "Thread: " << std::this_thread::get_id() << LineEnd;
}
// Read effect hrd
Data::CParams Desc;
{
std::vector<char> In;
if (!ReadAllFile(Task.SrcFilePath.string().c_str(), In, false))
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << Task.SrcFilePath.generic_string() << " reading error" << LineEnd;
return false;
}
Data::CHRDParser Parser;
if (!Parser.ParseBuffer(In.data(), In.size(), Desc))
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << Task.SrcFilePath.generic_string() << " HRD parsing error" << LineEnd;
return false;
}
}
// Get and validate material type
const CStrID MaterialType = GetParam<CStrID>(Desc, "Type", CStrID::Empty);
if (!MaterialType)
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Material type not specified" << LineEnd;
return false;
}
// Get and validate global and material params
auto ItGlobalParams = Desc.find(CStrID("GlobalParams"));
const bool HasGlobalParams = (ItGlobalParams != Desc.cend() && !ItGlobalParams->second.IsVoid());
if (HasGlobalParams && !ItGlobalParams->second.IsA<Data::CDataArray>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'GlobalParams' must be an array of CStringID" << LineEnd;
return false;
}
auto ItMaterialParams = Desc.find(CStrID("MaterialParams"));
const bool HasMaterialParams = (ItMaterialParams != Desc.cend() && !ItMaterialParams->second.IsVoid());
if (HasMaterialParams && !ItMaterialParams->second.IsA<Data::CParams>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'MaterialParams' must be a section" << LineEnd;
return false;
}
if (HasGlobalParams && HasMaterialParams)
{
// Check intersections between global and material params
bool HasErrors = false;
const Data::CDataArray& GlobalParams = ItGlobalParams->second.GetValue<Data::CDataArray>();
const Data::CParams& MaterialParams = ItMaterialParams->second.GetValue<Data::CParams>();
for (const auto& Global : GlobalParams)
{
if (!Global.IsA<CStrID>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'GlobalParams' can contain only CStringID elements (single-quoted strings)" << LineEnd;
HasErrors = true;
}
const CStrID ParamID = Global.GetValue<CStrID>();
if (MaterialParams.find(ParamID) != MaterialParams.cend())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << '\'' << ParamID.CStr() << "' appears in both global and material params" << LineEnd;
HasErrors = true;
}
}
}
// Parse, validate and sort techniques
auto ItRenderStates = Desc.find(CStrID("RenderStates"));
if (ItRenderStates == Desc.cend() || !ItRenderStates->second.IsA<Data::CParams>())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'RenderStates' must be a section" << LineEnd;
return false;
}
auto ItTechs = Desc.find(CStrID("Techniques"));
if (ItTechs == Desc.cend() || !ItTechs->second.IsA<Data::CParams>() || ItTechs->second.GetValue<Data::CParams>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "'Techniques' must be a section and contain at least one input set" << LineEnd;
return false;
}
std::map<CStrID, CRenderState> RSCache;
const auto& RenderStates = ItRenderStates->second.GetValue<Data::CParams>();
const auto& InputSets = ItTechs->second.GetValue<Data::CParams>();
for (const auto& InputSet : InputSets)
{
if (!InputSet.second.IsA<Data::CParams>() || InputSet.second.GetValue<Data::CParams>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Input set '" << InputSet.first.CStr() << "' must be a section containing at least one technique" << LineEnd;
return false;
}
const auto& Techs = InputSet.second.GetValue<Data::CParams>();
for (const auto& Tech : Techs)
{
if (!Tech.second.IsA<Data::CDataArray>() || Tech.second.GetValue<Data::CDataArray>().empty())
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "' must be an array containing at least one render state ID" << LineEnd;
return false;
}
// TODO:
// parse passes //???before techs to handle references properly?
// if tech mixes shader formats, fail (or allow say DXBC+DXIL for D3D12? use newer format as tech format? DXIL in this case)
// if tech became empty, discard it
uint32_t ShaderFormatFourCC = 0;
uint32_t MinFeatureLevel = 0;
uint32_t RequiresFlags = 0;
const auto& Passes = Tech.second.GetValue<Data::CDataArray>();
for (const auto& Pass : Passes)
{
const CStrID RenderStateID = Pass.GetValue<CStrID>();
if (_LogVerbosity >= EVerbosity::Debug)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "', pass '" << RenderStateID.CStr() << '\'' << LineEnd;
auto ItRS = RSCache.find(RenderStateID);
if (ItRS == RSCache.cend())
{
LoadRenderState(RSCache, RenderStateID, RenderStates);
auto ItRS = RSCache.find(RenderStateID);
}
const auto& RS = ItRS->second;
if (!RS.IsValid)
{
// Can discard only this tech, but for now issue an error and stop
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Tech '" << InputSet.first.CStr() << '.' << Tech.first.CStr() << "' uses invalid render state in a pass '" << RenderStateID.CStr() << '\'' << LineEnd;
return false;
}
// collect info from the render state:
// shader format
// feature level
// light count
}
}
// All techs of the input set:
// sort techs by the feature level (descending), so that first loaded tech is the best
//???sort by shader format?
}
// FIXME: must be thread-safe, also can move to the common code
//if (_LogVerbosity >= EVerbosity::Debug)
// std::cout << "Status: " << (Ok ? "OK" : "FAIL") << LineEnd << LineEnd;
return true;
}
bool LoadRenderState(std::map<CStrID, CRenderState>& RSCache, CStrID ID, const Data::CParams& RenderStates)
{
// Insert invalid render state initially not to do it in every 'return false' below.
// We want to have a record for each parsed RS, not only for valid ones.
CRenderState& RS = RSCache.emplace(ID, CRenderState{}).first->second;
const auto LineEnd = std::cout.widen('\n');
// Get a descripting HRD section
auto It = RenderStates.find(ID);
if (It == RenderStates.cend() || !It->second.IsA<Data::CParams>)
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Render state '" << ID.CStr() << "' not found or is not a section" << LineEnd;
return false;
}
const auto& Desc = It->second.GetValue<Data::CParams>();
// Load base state if specified
const CStrID BaseID = GetParam(Desc, "Base", CStrID::Empty);
if (BaseID)
{
auto ItRS = RSCache.find(BaseID);
if (ItRS == RSCache.cend())
{
LoadRenderState(RSCache, BaseID, RenderStates);
auto ItRS = RSCache.find(BaseID);
}
const auto& BaseRS = ItRS->second;
if (!BaseRS.IsValid)
{
if (_LogVerbosity >= EVerbosity::Errors)
std::cout << "Render state '" << ID.CStr() << "' has invalid base state '" << BaseID.CStr() << '\'' << LineEnd;
return false;
}
// Copy base state to the current, so all parameters in the current desc will override base values
RS = BaseRS;
}
// Load explicit state
//...
// Process shaders
// ...
// store only explicitly defined values? easier loading, engine supplies defaults
// loop through specified shaders
// - if no shader resource, fail
// - if unsupported format mixing, fail
// - load metadata (separate codepath for each metadata format)
// get shader formats for all specified shaders
// if shader doesn't exist, fail
// if pass mixes shader formats, fail (or allow say DXBC+DXIL for D3D12? use newer format as tech format? DXIL in this case)
// collect feature level (max through all used shaders) - only for DX? additional fields can be based on tech format
// get max light count of all shaders in all passes (-1 = any, 0 = no lights in this pass)
// shader switching is costly, so we don't build per-light-count variations, but instead
// create the shader with max light count only
//???how to claculate max light count and whether the shader uses lights at all?
RSCache.emplace(ID, std::move(RS));
RS.IsValid = true;
return true;
}
};
int main(int argc, const char** argv)
{
CEffectTool Tool("cf-effect", "DeusExMachina rendering effect compiler", { 0, 1, 0 });
return Tool.Execute(argc, argv);
}
<|endoftext|> |
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "entityx/System.h"
#include "Transform.h"
#include "cinder/Perlin.h"
#include "cinder/Rand.h"
#include "Components.h"
#include "Systems.h"
#include "Expires.h"
#include "ExpiresSystem.h"
#include "Behavior.h"
#include "BehaviorSystem.h"
#include "Behaviors.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
// Wraps positions to stay within a rectangle.
const auto borderWrap = createWrapFunction(Rectf(0, 0, 640, 480));
///
/// @file EntityCreationApp demonstrates creation of entities and some of the uses of components and systems.
/// This application, as a teaching tool, is much more heavily commented than a production codebase.
///
class EntityCreationApp : public App {
public:
EntityCreationApp();
void setup() override;
void mouseDown(MouseEvent event) override;
void mouseDrag(MouseEvent event) override;
void mouseUp(MouseEvent event) override;
void keyDown(KeyEvent event) override;
void update() override;
void draw() override;
entityx::Entity createDot(const ci::vec2 &position, const ci::vec2 &direction, float diameter);
private:
entityx::EventManager events;
entityx::EntityManager entities;
entityx::SystemManager systems;
uint32_t num_dots = 0;
static const uint32_t max_dots = 1024;
ci::vec2 mouse, mouse_prev;
bool do_clear = true;
};
// Initialize our EntityManager and SystemManager to know about events and each other.
EntityCreationApp::EntityCreationApp()
: entities(events),
systems(entities, events)
{}
void EntityCreationApp::setup()
{
// Create our systems for controlling entity behavior.
// We also use free functions for entity behavior, which don't need to be instantiated.
systems.add<ExpiresSystem>();
systems.add<BehaviorSystem>(entities);
systems.configure();
// Create an initial dot on screen
createDot(getWindowCenter(), vec2(1, 0), 36.0f);
}
entityx::Entity EntityCreationApp::createDot(const ci::vec2 &position, const ci::vec2 &direction, float diameter)
{
// Keep track of the number of dots created so we don't have way too many.
if (num_dots > max_dots) {
return entityx::Entity(); // return an invalid entity
}
num_dots += 1;
// Create an entity, managed by `entities`.
auto dot = entities.create();
// Assign the components we care about
dot.assign<Position>(position);
dot.assign<Circle>(diameter);
dot.assign<Motion>(direction, 250.0f);
// Assign an Expires component and store a handle to it in `exp`
auto exp = dot.assign<Expires>(randFloat(4.0f, 6.0f));
// Set a function to call when the Expires component runs out of time//
// Called last_wish, since it happens just before the entity is destroyed.
exp->last_wish = [this, diameter, direction] (entityx::Entity e) {
num_dots -= 1;
if (diameter > 8.0f) {
// If we weren't too small, create some smaller dots where we were destroyed.
auto pos = e.component<Position>()->position;
auto dir = glm::rotate<float>(direction, M_PI / 2);
createDot(pos, dir, diameter * 0.66f);
createDot(pos, - dir, diameter * 0.66f);
}
};
return dot;
}
void EntityCreationApp::mouseDown(MouseEvent event)
{
// Create an entity that tracks the mouse.
auto mouse_entity = entities.create();
mouse_entity.assign<Position>(event.getPos());
mouse_entity.assign<Circle>(49.0f, Color::gray(0.5f));
// The DragTracker behavior will destroy its entity when the drag ends.
assignBehavior<DragTracker>(mouse_entity);
}
void EntityCreationApp::mouseDrag( MouseEvent event )
{
// Keep track of the mouse position.
// This could be better done in a behavior or component (say, when DragTracker is destroyed)
// Dear reader: try modifying the DragTracker behavior so it calls a function on destruction.
// Use that function to create a dot where the tracker was last seen.
mouse_prev = mouse;
mouse = event.getPos();
}
void EntityCreationApp::mouseUp(MouseEvent event)
{
mouse = event.getPos();
auto delta = mouse - mouse_prev;
auto len = length(delta);
if (length(delta) > std::numeric_limits<float>::epsilon()) {
delta /= len;
}
else {
delta = vec2(1, 0);
}
createDot(mouse, delta, 49.0f);
}
void EntityCreationApp::keyDown(KeyEvent event)
{
if (event.getCode() == KeyEvent::KEY_c) {
do_clear = ! do_clear;
}
}
void EntityCreationApp::update()
{
auto dt = 1.0 / 60.0;
// Update all of our systems.
systems.update<ExpiresSystem>(dt);
systems.update<BehaviorSystem>(dt);
// Apply functions to the entities. See Systems.h for these function definitions.
slowDownWithAge(entities);
applyMotion(entities, dt);
borderWrap(entities);
if (! do_clear) {
fadeWithAge(entities);
}
}
void EntityCreationApp::draw()
{
if (do_clear) {
gl::clear( Color( 0, 0, 0 ) );
}
gl::disableDepthRead();
gl::setMatricesWindowPersp(getWindowSize());
// Below, we loop through and draw every entity that has both a position and a circle component.
// This is a bit more interesting than having a custom draw function for every entity,
// because it allows us to do smart things based on what we know about our world.
entityx::ComponentHandle<Circle> ch;
entityx::ComponentHandle<Position> ph;
gl::ScopedColor color(Color::white());
for (auto __unused e : entities.entities_with_components(ch, ph)) {
gl::color(ch->color);
gl::drawSolidCircle(ph->position, ch->radius());
}
}
CINDER_APP( EntityCreationApp, RendererGl(RendererGl::Options().msaa(4)) )
<commit_msg>Expand play area.<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "entityx/System.h"
#include "Transform.h"
#include "cinder/Perlin.h"
#include "cinder/Rand.h"
#include "Components.h"
#include "Systems.h"
#include "Expires.h"
#include "ExpiresSystem.h"
#include "Behavior.h"
#include "BehaviorSystem.h"
#include "Behaviors.h"
using namespace ci;
using namespace ci::app;
using namespace std;
using namespace soso;
// Wraps positions to stay within a rectangle.
const auto borderWrap = createWrapFunction(Rectf(0, 0, 660, 500));
///
/// @file EntityCreationApp demonstrates creation of entities and some of the uses of components and systems.
/// This application, as a teaching tool, is much more heavily commented than a production codebase.
///
class EntityCreationApp : public App {
public:
EntityCreationApp();
void setup() override;
void mouseDown(MouseEvent event) override;
void mouseDrag(MouseEvent event) override;
void mouseUp(MouseEvent event) override;
void keyDown(KeyEvent event) override;
void update() override;
void draw() override;
entityx::Entity createDot(const ci::vec2 &position, const ci::vec2 &direction, float diameter);
private:
entityx::EventManager events;
entityx::EntityManager entities;
entityx::SystemManager systems;
uint32_t num_dots = 0;
static const uint32_t max_dots = 1024;
ci::vec2 mouse, mouse_prev;
bool do_clear = true;
};
// Initialize our EntityManager and SystemManager to know about events and each other.
EntityCreationApp::EntityCreationApp()
: entities(events),
systems(entities, events)
{}
void EntityCreationApp::setup()
{
// Create our systems for controlling entity behavior.
// We also use free functions for entity behavior, which don't need to be instantiated.
systems.add<ExpiresSystem>();
systems.add<BehaviorSystem>(entities);
systems.configure();
// Create an initial dot on screen
createDot(getWindowCenter(), vec2(1, 0), 36.0f);
}
entityx::Entity EntityCreationApp::createDot(const ci::vec2 &position, const ci::vec2 &direction, float diameter)
{
// Keep track of the number of dots created so we don't have way too many.
if (num_dots > max_dots) {
return entityx::Entity(); // return an invalid entity
}
num_dots += 1;
// Create an entity, managed by `entities`.
auto dot = entities.create();
// Assign the components we care about
dot.assign<Position>(position);
dot.assign<Circle>(diameter);
dot.assign<Motion>(direction, 250.0f);
// Assign an Expires component and store a handle to it in `exp`
auto exp = dot.assign<Expires>(randFloat(4.0f, 6.0f));
// Set a function to call when the Expires component runs out of time//
// Called last_wish, since it happens just before the entity is destroyed.
exp->last_wish = [this, diameter, direction] (entityx::Entity e) {
num_dots -= 1;
if (diameter > 8.0f) {
// If we weren't too small, create some smaller dots where we were destroyed.
auto pos = e.component<Position>()->position;
auto dir = glm::rotate<float>(direction, M_PI / 2);
createDot(pos, dir, diameter * 0.66f);
createDot(pos, - dir, diameter * 0.66f);
}
};
return dot;
}
void EntityCreationApp::mouseDown(MouseEvent event)
{
// Create an entity that tracks the mouse.
auto mouse_entity = entities.create();
mouse_entity.assign<Position>(event.getPos());
mouse_entity.assign<Circle>(49.0f, Color::gray(0.5f));
// The DragTracker behavior will destroy its entity when the drag ends.
assignBehavior<DragTracker>(mouse_entity);
}
void EntityCreationApp::mouseDrag( MouseEvent event )
{
// Keep track of the mouse position.
// This could be better done in a behavior or component (say, when DragTracker is destroyed)
// Dear reader: try modifying the DragTracker behavior so it calls a function on destruction.
// Use that function to create a dot where the tracker was last seen.
mouse_prev = mouse;
mouse = event.getPos();
}
void EntityCreationApp::mouseUp(MouseEvent event)
{
mouse = event.getPos();
auto delta = mouse - mouse_prev;
auto len = length(delta);
if (length(delta) > std::numeric_limits<float>::epsilon()) {
delta /= len;
}
else {
delta = vec2(1, 0);
}
createDot(mouse, delta, 49.0f);
}
void EntityCreationApp::keyDown(KeyEvent event)
{
if (event.getCode() == KeyEvent::KEY_c) {
do_clear = ! do_clear;
}
}
void EntityCreationApp::update()
{
auto dt = 1.0 / 60.0;
// Update all of our systems.
systems.update<ExpiresSystem>(dt);
systems.update<BehaviorSystem>(dt);
// Apply functions to the entities. See Systems.h for these function definitions.
slowDownWithAge(entities);
applyMotion(entities, dt);
borderWrap(entities);
if (! do_clear) {
fadeWithAge(entities);
}
}
void EntityCreationApp::draw()
{
if (do_clear) {
gl::clear( Color( 0, 0, 0 ) );
}
gl::disableDepthRead();
gl::setMatricesWindowPersp(getWindowSize());
// Below, we loop through and draw every entity that has both a position and a circle component.
// This is a bit more interesting than having a custom draw function for every entity,
// because it allows us to do smart things based on what we know about our world.
entityx::ComponentHandle<Circle> ch;
entityx::ComponentHandle<Position> ph;
gl::ScopedColor color(Color::white());
for (auto __unused e : entities.entities_with_components(ch, ph)) {
gl::color(ch->color);
gl::drawSolidCircle(ph->position, ch->radius());
}
}
CINDER_APP( EntityCreationApp, RendererGl(RendererGl::Options().msaa(4)) )
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <io/InputStream.h>
#include <io/BufferedInputStream.h>
#include <io/MslArray.h>
#include <io/MslEncoderFactory.h>
#include <io/MslEncoderFormat.h>
#include <io/MslObject.h>
#include <iomanip>
#include <iosfwd>
#include <sstream>
#define TIMEOUT 60000
using namespace std;
namespace netflix {
namespace msl {
namespace io {
//static
string MslEncoderFactory::quote(const std::string& string)
{
ostringstream oss;
// Return "" zero-length string.
if (string.length() == 0) {
oss << "\"\"";
return oss.str();
}
oss << '"';
char c = 0;
for (string::const_iterator it = string.begin(); it != string.end(); ++it)
{
const char b = c;
c = *it;
switch (c) {
case '\\':
case '"':
oss << '\\';
oss << c;
break;
case '/':
if (b == '<') {
oss << '\\';
}
oss << c;
break;
case '\b':
oss << "\\b";
break;
case '\t':
oss << "\\t";
break;
case '\n':
oss << "\\n";
break;
case '\f':
oss << "\\f";
break;
case '\r':
oss << "\\r";
break;
default:
// FIXME
// if (c < ' ' || (c >= '\x80' && c < '\xa0')) {
// // || (c >= '\u2000' && c < '\u2100')) FIXME??
// oss << "\\u" << setfill('0') << setw(4) << hex << c;
// } else {
oss << c;
// }
}
}
oss << '"';
return oss.str();
}
//static
string MslEncoderFactory::stringify(const Variant& value)
{
if (value.isType<MslObject>()) {
return stringify(value.get<shared_ptr<MslObject>>());
} else if (value.isType<MslArray>()) {
return stringify(value.get<shared_ptr<MslArray>>());
} else {
return value.toString();
}
}
MslEncoderFormat MslEncoderFactory::parseFormat(shared_ptr<ByteArray> encoding)
{
// Fail if the encoding is too short.
if (encoding->size() < 1)
throw MslEncoderException("No encoding identifier found.");
// Identify the encoder format.
const uint8_t id = (*encoding)[0];
const MslEncoderFormat format = MslEncoderFormat::getFormat(id);
if (format == MslEncoderFormat::INVALID) {
stringstream ss;
ss << "Unidentified encoder format ID: (byte)0x" << hex << static_cast<unsigned>(id) << ".";
throw MslEncoderException(ss.str());
}
return format;
}
shared_ptr<MslTokenizer> MslEncoderFactory::createTokenizer(shared_ptr<InputStream> source)
{
// Read the byte stream identifier (and only the identifier).
shared_ptr<InputStream> bufferedSource = source->markSupported() ? source : make_shared<BufferedInputStream>(source);
const int WIDTH = 1;
ByteArray buffer(WIDTH);
source->mark(1);
const int count = source->read(buffer, 0, WIDTH, TIMEOUT); // TODO: Someone has to tell me this timeout.
if (count == -1)
throw new MslEncoderException("End of stream reached when attempting to read the byte stream identifier.");
if (count == 0)
throw new MslEncoderException("Timeout when attempting to read the byte stream identifier.");
// Identify the encoder format.
const uint8_t id = buffer[0];
const MslEncoderFormat format = MslEncoderFormat::getFormat(id);
if (format == MslEncoderFormat::INVALID) {
stringstream ss;
ss << "Unidentified encoder format ID: (byte)0x" << hex << static_cast<unsigned>(id) << ".";
throw MslEncoderException(ss.str());
}
// Reset the input stream and return the tokenizer.
source->reset();
return generateTokenizer(source, format);
}
}}} // namespace netflix::msl::io
<commit_msg>Fix bug: use buffered source and not source.<commit_after>/**
* Copyright (c) 2016-2018 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <io/InputStream.h>
#include <io/BufferedInputStream.h>
#include <io/MslArray.h>
#include <io/MslEncoderFactory.h>
#include <io/MslEncoderFormat.h>
#include <io/MslObject.h>
#include <iomanip>
#include <iosfwd>
#include <sstream>
#define TIMEOUT 60000
using namespace std;
namespace netflix {
namespace msl {
namespace io {
//static
string MslEncoderFactory::quote(const std::string& string)
{
ostringstream oss;
// Return "" zero-length string.
if (string.length() == 0) {
oss << "\"\"";
return oss.str();
}
oss << '"';
char c = 0;
for (string::const_iterator it = string.begin(); it != string.end(); ++it)
{
const char b = c;
c = *it;
switch (c) {
case '\\':
case '"':
oss << '\\';
oss << c;
break;
case '/':
if (b == '<') {
oss << '\\';
}
oss << c;
break;
case '\b':
oss << "\\b";
break;
case '\t':
oss << "\\t";
break;
case '\n':
oss << "\\n";
break;
case '\f':
oss << "\\f";
break;
case '\r':
oss << "\\r";
break;
default:
// FIXME
// if (c < ' ' || (c >= '\x80' && c < '\xa0')) {
// // || (c >= '\u2000' && c < '\u2100')) FIXME??
// oss << "\\u" << setfill('0') << setw(4) << hex << c;
// } else {
oss << c;
// }
}
}
oss << '"';
return oss.str();
}
//static
string MslEncoderFactory::stringify(const Variant& value)
{
if (value.isType<MslObject>()) {
return stringify(value.get<shared_ptr<MslObject>>());
} else if (value.isType<MslArray>()) {
return stringify(value.get<shared_ptr<MslArray>>());
} else {
return value.toString();
}
}
MslEncoderFormat MslEncoderFactory::parseFormat(shared_ptr<ByteArray> encoding)
{
// Fail if the encoding is too short.
if (encoding->size() < 1)
throw MslEncoderException("No encoding identifier found.");
// Identify the encoder format.
const uint8_t id = (*encoding)[0];
const MslEncoderFormat format = MslEncoderFormat::getFormat(id);
if (format == MslEncoderFormat::INVALID) {
stringstream ss;
ss << "Unidentified encoder format ID: (byte)0x" << hex << static_cast<unsigned>(id) << ".";
throw MslEncoderException(ss.str());
}
return format;
}
shared_ptr<MslTokenizer> MslEncoderFactory::createTokenizer(shared_ptr<InputStream> source)
{
// Read the byte stream identifier (and only the identifier).
shared_ptr<InputStream> bufferedSource = source->markSupported() ? source : make_shared<BufferedInputStream>(source);
const int WIDTH = 1;
ByteArray buffer(WIDTH);
bufferedSource->mark(1);
const int count = bufferedSource->read(buffer, 0, WIDTH, TIMEOUT); // TODO: Someone has to tell me this timeout.
if (count == -1)
throw new MslEncoderException("End of stream reached when attempting to read the byte stream identifier.");
if (count == 0)
throw new MslEncoderException("Timeout when attempting to read the byte stream identifier.");
// Identify the encoder format.
const uint8_t id = buffer[0];
const MslEncoderFormat format = MslEncoderFormat::getFormat(id);
if (format == MslEncoderFormat::INVALID) {
stringstream ss;
ss << "Unidentified encoder format ID: (byte)0x" << hex << static_cast<unsigned>(id) << ".";
throw MslEncoderException(ss.str());
}
// Reset the input stream and return the tokenizer.
bufferedSource->reset();
return generateTokenizer(bufferedSource, format);
}
}}} // namespace netflix::msl::io
<|endoftext|> |
<commit_before>//===--- TextInput.cpp - Main Interface -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the main interface for the TextInput library.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TextInput.h"
#include "textinput/Display.h"
#include "textinput/Reader.h"
#include "textinput/Color.h"
#include "textinput/Editor.h"
#include "textinput/History.h"
#include "textinput/KeyBinding.h"
#include "textinput/TextInputContext.h"
#include "textinput/SignalHandler.h"
#include <algorithm>
#include <functional>
namespace textinput {
TextInput::TextInput(Reader& reader, Display& display,
const char* HistFile /* = 0 */):
fHidden(false),
fAutoHistAdd(true),
fLastKey(0),
fMaxChars(0),
fLastReadResult(kRRNone),
fActive(false)
{
fContext = new TextInputContext(this, HistFile);
fContext->AddDisplay(display);
fContext->AddReader(reader);
}
TextInput::~TextInput() {
delete fContext;
}
void
TextInput::TakeInput(std::string &input) {
if (fLastReadResult != kRRReadEOLDelimiter
&& fLastReadResult != kRREOF) {
input.clear();
return;
}
input = fContext->GetLine().GetText();
while (!input.empty() && input[input.length() - 1] == 13) {
input.erase(input.length() - 1);
}
fContext->GetEditor()->ResetText();
// Signal displays that the input got taken.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyResetInput));
ReleaseInputOutput();
if (fLastReadResult == kRRReadEOLDelimiter) {
// Input has been taken, we can continue reading.
fLastReadResult = kRRNone;
} // else keep EOF.
}
bool
TextInput::HavePendingInput() const {
if (!fActive) {
GrabInputOutput();
}
for (std::vector<Reader*>::const_iterator iR = fContext->GetReaders().begin(),
iE = fContext->GetReaders().end(); iR != iE; ++iR) {
if ((*iR)->HavePendingInput(false))
return true;
}
return false;
}
TextInput::EReadResult
TextInput::ReadInput() {
// Read more input.
// Don't read if we are at the end; force call to TakeInput().
if (fLastReadResult == kRRReadEOLDelimiter
|| fLastReadResult == kRREOF)
return fLastReadResult;
if (fLastReadResult == kRRNone) {
GrabInputOutput();
UpdateDisplay(EditorRange(Range::AllText(), Range::AllWithPrompt()));
}
size_t nRead = 0;
size_t nMax = GetMaxPendingCharsToRead();
if (nMax == 0) nMax = (size_t) -1; // aka "all"
InputData in;
EditorRange R;
size_t OldCursorPos = fContext->GetCursor();
// Allow the reader to select() if we want a single line, and we want it
// only from one reader
bool waitForInput = IsBlockingUntilEOL()
&& fContext->GetReaders().size() == 1;
for (std::vector<Reader*>::const_iterator iR
= fContext->GetReaders().begin(),
iE = fContext->GetReaders().end();
iR != iE && nRead < nMax; ++iR) {
while ((IsBlockingUntilEOL() && (fLastReadResult == kRRNone))
|| (nRead < nMax && (*iR)->HavePendingInput(waitForInput))) {
if ((*iR)->ReadInput(nRead, in)) {
ProcessNewInput(in, R);
DisplayNewInput(R, OldCursorPos);
if (fLastReadResult == kRREOF
|| fLastReadResult == kRRReadEOLDelimiter)
break;
}
}
}
if (fLastReadResult == kRRNone) {
if (nRead == nMax) {
fLastReadResult = kRRCharLimitReached;
} else {
fLastReadResult = kRRNoMorePendingInput;
}
}
return fLastReadResult;
}
void
TextInput::ProcessNewInput(const InputData& in, EditorRange& R) {
// in was read, process it.
fLastKey = in.GetRaw(); // rough approximation
Editor::Command Cmd = fContext->GetKeyBinding()->ToCommand(in);
if (Cmd.GetKind() == Editor::kCKControl
&& (Cmd.GetChar() == 3 || Cmd.GetChar() == 26)) {
// If there are modifications in the queue, process them now.
UpdateDisplay(R);
EmitSignal(Cmd.GetChar(), R);
} else if (Cmd.GetKind() == Editor::kCKCommand
&& Cmd.GetCommandID() == Editor::kCmdWindowResize) {
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyWindowChange));
} else {
if (!in.IsRaw() && in.GetExtendedInput() == InputData::kEIEOF) {
fLastReadResult = kRREOF;
return;
} else {
Editor::EProcessResult Res = fContext->GetEditor()->Process(Cmd, R);
if (Res == Editor::kPRError) {
// Signal displays that an error has occurred.
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyError));
} else if (Cmd.GetKind() == Editor::kCKCommand
&& (Cmd.GetCommandID() == Editor::kCmdEnter ||
Cmd.GetCommandID() == Editor::kCmdHistReplay)) {
fLastReadResult = kRRReadEOLDelimiter;
return;
}
}
}
}
void
TextInput::DisplayNewInput(EditorRange& R, size_t& oldCursorPos) {
// Display what has been entered.
if (fContext->GetColorizer() && oldCursorPos != fContext->GetCursor()) {
fContext->GetColorizer()->ProcessCursorChange(fContext->GetCursor(),
fContext->GetLine(),
R.fDisplay);
}
UpdateDisplay(R);
if (oldCursorPos != fContext->GetCursor()) {
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyCursorChange));
}
oldCursorPos = fContext->GetCursor();
}
void
TextInput::Redraw() {
// Attach and redraw.
GrabInputOutput();
UpdateDisplay(EditorRange(Range::AllText(), Range::AllWithPrompt()));
}
void
TextInput::UpdateDisplay(const EditorRange& R) {
// Update changed ranges if attached.
if (!fActive) {
return;
}
EditorRange ColModR(R);
if (!R.fDisplay.IsEmpty() && fContext->GetColorizer()) {
fContext->GetColorizer()->ProcessTextChange(ColModR, fContext->GetLine());
}
if (!ColModR.fDisplay.IsEmpty()
|| ColModR.fDisplay.fPromptUpdate != Range::kNoPromptUpdate) {
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::bind2nd(std::mem_fun(&Display::NotifyTextChange), ColModR.fDisplay));
}
}
void
TextInput::EmitSignal(char C, EditorRange& R) {
ReleaseInputOutput();
SignalHandler* Signal = fContext->GetSignalHandler();
if (C == 3)
Signal->EmitCtrlC();
else if (C == 26)
Signal->EmitCtrlZ();
GrabInputOutput();
// Already done by GrabInputOutput():
//R.Display = Range::AllText();
// Immediate refresh.
//std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
// std::bind2nd(std::mem_fun(&Display::NotifyTextChange),
// R.Display));
// Empty range.
R.fDisplay = Range::Empty();
}
void
TextInput::SetPrompt(const char *P) {
fContext->SetPrompt(P);
if (fContext->GetColorizer()) {
fContext->GetColorizer()->ProcessPromptChange(fContext->GetPrompt());
}
if (!fActive) return;
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::bind2nd(std::mem_fun(&Display::NotifyTextChange),
Range::AllWithPrompt()));
}
void
TextInput::SetColorizer(Colorizer* c) {
fContext->SetColorizer(c);
}
void
TextInput::SetCompletion(TabCompletion* tc) {
// Set the completion handler.
fContext->SetCompletion(tc);
}
void
TextInput::SetFunctionKeyHandler(FunKey* fc) {
fContext->SetFunctionKeyHandler(fc);
}
void
TextInput::GrabInputOutput() const {
if (fActive) return;
// Signal readers that we are about to read.
std::for_each(fContext->GetReaders().begin(), fContext->GetReaders().end(),
std::mem_fun(&Reader::GrabInputFocus));
// Signal displays that we are about to display.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::Attach));
fActive = true;
}
void
TextInput::ReleaseInputOutput() const {
// Signal readers that we are done reading.
if (!fActive) return;
std::for_each(fContext->GetReaders().begin(), fContext->GetReaders().end(),
std::mem_fun(&Reader::ReleaseInputFocus));
// Signal displays that we are done displaying.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::Detach));
fActive = false;
}
void
TextInput::DisplayInfo(const std::vector<std::string>& lines) {
// Display an informational message at the prompt. Acts like
// a pop-up. Used e.g. for tab-completion.
// foreach fails to build the reference in GCC 4.1.
// Iterate manually instead.
for (std::vector<Display*>::const_iterator i = fContext->GetDisplays().begin(),
e = fContext->GetDisplays().end(); i != e; ++i) {
(*i)->DisplayInfo(lines);
}
}
void
TextInput::HandleResize() {
// Resize signal was emitted, tell the displays.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyWindowChange));
}
void
TextInput::AddHistoryLine(const char* line) {
if (!line) return;
std::string sLine(line);
while (sLine[sLine.length() - 1] == '\n'
|| sLine[sLine.length() - 1] == '\r') {
sLine.erase(sLine.length() - 1);
}
fContext->GetHistory()->AddLine(sLine);
}
}
<commit_msg>From Bertrand and me: don't access character [-1] for empty strings.<commit_after>//===--- TextInput.cpp - Main Interface -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the main interface for the TextInput library.
//
// Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/TextInput.h"
#include "textinput/Display.h"
#include "textinput/Reader.h"
#include "textinput/Color.h"
#include "textinput/Editor.h"
#include "textinput/History.h"
#include "textinput/KeyBinding.h"
#include "textinput/TextInputContext.h"
#include "textinput/SignalHandler.h"
#include <algorithm>
#include <functional>
namespace textinput {
TextInput::TextInput(Reader& reader, Display& display,
const char* HistFile /* = 0 */):
fHidden(false),
fAutoHistAdd(true),
fLastKey(0),
fMaxChars(0),
fLastReadResult(kRRNone),
fActive(false)
{
fContext = new TextInputContext(this, HistFile);
fContext->AddDisplay(display);
fContext->AddReader(reader);
}
TextInput::~TextInput() {
delete fContext;
}
void
TextInput::TakeInput(std::string &input) {
if (fLastReadResult != kRRReadEOLDelimiter
&& fLastReadResult != kRREOF) {
input.clear();
return;
}
input = fContext->GetLine().GetText();
while (!input.empty() && input[input.length() - 1] == 13) {
input.erase(input.length() - 1);
}
fContext->GetEditor()->ResetText();
// Signal displays that the input got taken.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyResetInput));
ReleaseInputOutput();
if (fLastReadResult == kRRReadEOLDelimiter) {
// Input has been taken, we can continue reading.
fLastReadResult = kRRNone;
} // else keep EOF.
}
bool
TextInput::HavePendingInput() const {
if (!fActive) {
GrabInputOutput();
}
for (std::vector<Reader*>::const_iterator iR = fContext->GetReaders().begin(),
iE = fContext->GetReaders().end(); iR != iE; ++iR) {
if ((*iR)->HavePendingInput(false))
return true;
}
return false;
}
TextInput::EReadResult
TextInput::ReadInput() {
// Read more input.
// Don't read if we are at the end; force call to TakeInput().
if (fLastReadResult == kRRReadEOLDelimiter
|| fLastReadResult == kRREOF)
return fLastReadResult;
if (fLastReadResult == kRRNone) {
GrabInputOutput();
UpdateDisplay(EditorRange(Range::AllText(), Range::AllWithPrompt()));
}
size_t nRead = 0;
size_t nMax = GetMaxPendingCharsToRead();
if (nMax == 0) nMax = (size_t) -1; // aka "all"
InputData in;
EditorRange R;
size_t OldCursorPos = fContext->GetCursor();
// Allow the reader to select() if we want a single line, and we want it
// only from one reader
bool waitForInput = IsBlockingUntilEOL()
&& fContext->GetReaders().size() == 1;
for (std::vector<Reader*>::const_iterator iR
= fContext->GetReaders().begin(),
iE = fContext->GetReaders().end();
iR != iE && nRead < nMax; ++iR) {
while ((IsBlockingUntilEOL() && (fLastReadResult == kRRNone))
|| (nRead < nMax && (*iR)->HavePendingInput(waitForInput))) {
if ((*iR)->ReadInput(nRead, in)) {
ProcessNewInput(in, R);
DisplayNewInput(R, OldCursorPos);
if (fLastReadResult == kRREOF
|| fLastReadResult == kRRReadEOLDelimiter)
break;
}
}
}
if (fLastReadResult == kRRNone) {
if (nRead == nMax) {
fLastReadResult = kRRCharLimitReached;
} else {
fLastReadResult = kRRNoMorePendingInput;
}
}
return fLastReadResult;
}
void
TextInput::ProcessNewInput(const InputData& in, EditorRange& R) {
// in was read, process it.
fLastKey = in.GetRaw(); // rough approximation
Editor::Command Cmd = fContext->GetKeyBinding()->ToCommand(in);
if (Cmd.GetKind() == Editor::kCKControl
&& (Cmd.GetChar() == 3 || Cmd.GetChar() == 26)) {
// If there are modifications in the queue, process them now.
UpdateDisplay(R);
EmitSignal(Cmd.GetChar(), R);
} else if (Cmd.GetKind() == Editor::kCKCommand
&& Cmd.GetCommandID() == Editor::kCmdWindowResize) {
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyWindowChange));
} else {
if (!in.IsRaw() && in.GetExtendedInput() == InputData::kEIEOF) {
fLastReadResult = kRREOF;
return;
} else {
Editor::EProcessResult Res = fContext->GetEditor()->Process(Cmd, R);
if (Res == Editor::kPRError) {
// Signal displays that an error has occurred.
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyError));
} else if (Cmd.GetKind() == Editor::kCKCommand
&& (Cmd.GetCommandID() == Editor::kCmdEnter ||
Cmd.GetCommandID() == Editor::kCmdHistReplay)) {
fLastReadResult = kRRReadEOLDelimiter;
return;
}
}
}
}
void
TextInput::DisplayNewInput(EditorRange& R, size_t& oldCursorPos) {
// Display what has been entered.
if (fContext->GetColorizer() && oldCursorPos != fContext->GetCursor()) {
fContext->GetColorizer()->ProcessCursorChange(fContext->GetCursor(),
fContext->GetLine(),
R.fDisplay);
}
UpdateDisplay(R);
if (oldCursorPos != fContext->GetCursor()) {
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyCursorChange));
}
oldCursorPos = fContext->GetCursor();
}
void
TextInput::Redraw() {
// Attach and redraw.
GrabInputOutput();
UpdateDisplay(EditorRange(Range::AllText(), Range::AllWithPrompt()));
}
void
TextInput::UpdateDisplay(const EditorRange& R) {
// Update changed ranges if attached.
if (!fActive) {
return;
}
EditorRange ColModR(R);
if (!R.fDisplay.IsEmpty() && fContext->GetColorizer()) {
fContext->GetColorizer()->ProcessTextChange(ColModR, fContext->GetLine());
}
if (!ColModR.fDisplay.IsEmpty()
|| ColModR.fDisplay.fPromptUpdate != Range::kNoPromptUpdate) {
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::bind2nd(std::mem_fun(&Display::NotifyTextChange), ColModR.fDisplay));
}
}
void
TextInput::EmitSignal(char C, EditorRange& R) {
ReleaseInputOutput();
SignalHandler* Signal = fContext->GetSignalHandler();
if (C == 3)
Signal->EmitCtrlC();
else if (C == 26)
Signal->EmitCtrlZ();
GrabInputOutput();
// Already done by GrabInputOutput():
//R.Display = Range::AllText();
// Immediate refresh.
//std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
// std::bind2nd(std::mem_fun(&Display::NotifyTextChange),
// R.Display));
// Empty range.
R.fDisplay = Range::Empty();
}
void
TextInput::SetPrompt(const char *P) {
fContext->SetPrompt(P);
if (fContext->GetColorizer()) {
fContext->GetColorizer()->ProcessPromptChange(fContext->GetPrompt());
}
if (!fActive) return;
std::for_each(fContext->GetDisplays().begin(),
fContext->GetDisplays().end(),
std::bind2nd(std::mem_fun(&Display::NotifyTextChange),
Range::AllWithPrompt()));
}
void
TextInput::SetColorizer(Colorizer* c) {
fContext->SetColorizer(c);
}
void
TextInput::SetCompletion(TabCompletion* tc) {
// Set the completion handler.
fContext->SetCompletion(tc);
}
void
TextInput::SetFunctionKeyHandler(FunKey* fc) {
fContext->SetFunctionKeyHandler(fc);
}
void
TextInput::GrabInputOutput() const {
if (fActive) return;
// Signal readers that we are about to read.
std::for_each(fContext->GetReaders().begin(), fContext->GetReaders().end(),
std::mem_fun(&Reader::GrabInputFocus));
// Signal displays that we are about to display.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::Attach));
fActive = true;
}
void
TextInput::ReleaseInputOutput() const {
// Signal readers that we are done reading.
if (!fActive) return;
std::for_each(fContext->GetReaders().begin(), fContext->GetReaders().end(),
std::mem_fun(&Reader::ReleaseInputFocus));
// Signal displays that we are done displaying.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::Detach));
fActive = false;
}
void
TextInput::DisplayInfo(const std::vector<std::string>& lines) {
// Display an informational message at the prompt. Acts like
// a pop-up. Used e.g. for tab-completion.
// foreach fails to build the reference in GCC 4.1.
// Iterate manually instead.
for (std::vector<Display*>::const_iterator i = fContext->GetDisplays().begin(),
e = fContext->GetDisplays().end(); i != e; ++i) {
(*i)->DisplayInfo(lines);
}
}
void
TextInput::HandleResize() {
// Resize signal was emitted, tell the displays.
std::for_each(fContext->GetDisplays().begin(), fContext->GetDisplays().end(),
std::mem_fun(&Display::NotifyWindowChange));
}
void
TextInput::AddHistoryLine(const char* line) {
if (!line) return;
std::string sLine(line);
while (!sLine.empty()
&& (sLine[sLine.length() - 1] == '\n'
|| sLine[sLine.length() - 1] == '\r')) {
sLine.erase(sLine.length() - 1);
}
if (!sLine.empty()) {
fContext->GetHistory()->AddLine(sLine);
}
}
}
<|endoftext|> |
<commit_before>#include "merkle_server.h"
#include "dhash.h"
// ---------------------------------------------------------------------------
// merkle_send_range
// This class
// 1) sends all the keys returned by the database iterator
// 2) and then deletes itself
// It limits itself to at max 64 outstanding sends.
class merkle_send_range {
private:
db_iterator *iter;
u_int num_sends_pending;
sndblkfnc2_t sndblkfnc;
chordID dstID;
void
go ()
{
while (iter->more () && num_sends_pending < 64) {
merkle_hash key = iter->next ();
num_sends_pending++;
XXX_SENDBLOCK_ARGS a (dstID, tobigint (key), !iter->more(),
wrap (this, &merkle_send_range::sendcb));
(*sndblkfnc) (&a);
}
if (!iter->more () && num_sends_pending == 0)
delete this;
}
void
sendcb ()
{
num_sends_pending--;
go ();
}
public:
merkle_send_range (db_iterator *iter, sndblkfnc2_t sndblkfnc, chordID dstID)
: iter (iter), num_sends_pending (0), sndblkfnc (sndblkfnc), dstID (dstID)
{
go ();
}
};
// ---------------------------------------------------------------------------
// util junk
// XXX CODE DUPLICATED IN MERKLE_SYNCER.C
static qhash<merkle_hash, bool> *
make_set (rpc_vec<merkle_hash, 64> &v)
{
qhash<merkle_hash, bool> *s = New qhash<merkle_hash, bool> ();
for (u_int i = 0; i < v.size (); i++)
s->insert (v[i], true);
return s;
}
static void
ignorecb ()
{
}
// ---------------------------------------------------------------------------
// merkle_server
merkle_server::merkle_server (merkle_tree *ltree, vnode *host_node, sndblkfnc2_t sndblkfnc)
: ltree (ltree), host_node (host_node), sndblkfnc (sndblkfnc)
{
host_node->addHandler (merklesync_program_1, wrap(this, &merkle_server::dispatch));
}
static void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_isleaf.setsize (64);
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++) {
const merkle_node *child = node->child (i);
rpcnode->child_isleaf[i] = child->isleaf ();
rpcnode->child_hash[i] = child->hash;
}
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
assert (keys.size () == rpcnode->count);
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
void
merkle_server::dispatch (svccb *sbp)
{
if (!sbp)
return;
switch (sbp->proc ()) {
case MERKLESYNC_GETNODE:
// request a node of the merkle tree
{
getnode_arg *arg = sbp->template getarg<getnode_arg> ();
merkle_node *lnode;
u_int lnode_depth;
merkle_hash lnode_prefix;
lnode = ltree->lookup (&lnode_depth, arg->depth, arg->prefix);
lnode_prefix = arg->prefix;
lnode_prefix.clear_suffix (lnode_depth);
getnode_res res (MERKLE_OK);
format_rpcnode (ltree, lnode_depth, lnode_prefix, lnode, &res.resok->node);
sbp->reply (&res);
break;
}
case MERKLESYNC_GETBLOCKLIST:
// request a list of blocks
{
//warn << (u_int) this << " dis..GETBLOCKLIST\n";
getblocklist_arg *arg = sbp->template getarg<getblocklist_arg> ();
ref<getblocklist_arg> arg_copy = New refcounted <getblocklist_arg> (*arg);
getblocklist_res res (MERKLE_OK);
chordID srcID = arg->srcID; // MUST be before sbp->reply
sbp->reply (&res);
// XXX DEADLOCK: if the blocks arrive before res, the remote side gets stuck.
for (u_int i = 0; i < arg_copy->keys.size (); i++) {
merkle_hash key = arg_copy->keys[i];
bool last = (i + 1 == arg_copy->keys.size ());
XXX_SENDBLOCK_ARGS a (srcID, tobigint (key), last, wrap (&ignorecb));
(*sndblkfnc) (&a);
}
break;
}
case MERKLESYNC_GETBLOCKRANGE:
// request all blocks in a given range, excluding a list of blocks (xkeys)
{
//warn << (u_int) this << " dis..GETBLOCKRANGE\n";
getblockrange_arg *arg = sbp->template getarg<getblockrange_arg> ();
getblockrange_res res (MERKLE_OK);
if (arg->bidirectional) {
res.resok->desired_xkeys.setsize (arg->xkeys.size ());
for (u_int i = 0; i < arg->xkeys.size (); i++) {
ptr<dbrec> blk = database_lookup (ltree->db, arg->xkeys[i]);
res.resok->desired_xkeys[i] = (blk == NULL);
}
}
db_iterator *iter;
iter = New db_range_xiterator (ltree->db, arg->depth, arg->prefix,
make_set (arg->xkeys), arg->rngmin,
arg->rngmax);
res.resok->will_send_blocks = iter->more ();
sbp->reply (&res);
// XXX DEADLOCK: if the blocks arrive before 'res'...remote gets stuck
vNew merkle_send_range (iter, sndblkfnc, arg->srcID);
break;
}
default:
assert (0);
sbp->reject (PROC_UNAVAIL);
break;
}
}
<commit_msg>don't reference freed memory<commit_after>#include "merkle_server.h"
#include "dhash.h"
// ---------------------------------------------------------------------------
// merkle_send_range
// This class
// 1) sends all the keys returned by the database iterator
// 2) and then deletes itself
// It limits itself to at max 64 outstanding sends.
class merkle_send_range {
private:
db_iterator *iter;
u_int num_sends_pending;
sndblkfnc2_t sndblkfnc;
chordID dstID;
void
go ()
{
while (iter->more () && num_sends_pending < 64) {
merkle_hash key = iter->next ();
num_sends_pending++;
XXX_SENDBLOCK_ARGS a (dstID, tobigint (key), !iter->more(),
wrap (this, &merkle_send_range::sendcb));
(*sndblkfnc) (&a);
}
if (!iter->more () && num_sends_pending == 0)
delete this;
}
void
sendcb ()
{
num_sends_pending--;
go ();
}
public:
merkle_send_range (db_iterator *iter, sndblkfnc2_t sndblkfnc, chordID dstID)
: iter (iter), num_sends_pending (0), sndblkfnc (sndblkfnc), dstID (dstID)
{
go ();
}
};
// ---------------------------------------------------------------------------
// util junk
// XXX CODE DUPLICATED IN MERKLE_SYNCER.C
static qhash<merkle_hash, bool> *
make_set (rpc_vec<merkle_hash, 64> &v)
{
qhash<merkle_hash, bool> *s = New qhash<merkle_hash, bool> ();
for (u_int i = 0; i < v.size (); i++)
s->insert (v[i], true);
return s;
}
static void
ignorecb ()
{
}
// ---------------------------------------------------------------------------
// merkle_server
merkle_server::merkle_server (merkle_tree *ltree, vnode *host_node, sndblkfnc2_t sndblkfnc)
: ltree (ltree), host_node (host_node), sndblkfnc (sndblkfnc)
{
host_node->addHandler (merklesync_program_1, wrap(this, &merkle_server::dispatch));
}
static void
format_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,
const merkle_node *node, merkle_rpc_node *rpcnode)
{
rpcnode->depth = depth;
rpcnode->prefix = prefix;
rpcnode->count = node->count;
rpcnode->hash = node->hash;
rpcnode->isleaf = node->isleaf ();
if (!node->isleaf ()) {
rpcnode->child_isleaf.setsize (64);
rpcnode->child_hash.setsize (64);
for (int i = 0; i < 64; i++) {
const merkle_node *child = node->child (i);
rpcnode->child_isleaf[i] = child->isleaf ();
rpcnode->child_hash[i] = child->hash;
}
} else {
vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);
assert (keys.size () == rpcnode->count);
rpcnode->child_hash.setsize (keys.size ());
for (u_int i = 0; i < keys.size (); i++) {
rpcnode->child_hash[i] = keys[i];
}
}
}
void
merkle_server::dispatch (svccb *sbp)
{
if (!sbp)
return;
switch (sbp->proc ()) {
case MERKLESYNC_GETNODE:
// request a node of the merkle tree
{
getnode_arg *arg = sbp->template getarg<getnode_arg> ();
merkle_node *lnode;
u_int lnode_depth;
merkle_hash lnode_prefix;
lnode = ltree->lookup (&lnode_depth, arg->depth, arg->prefix);
lnode_prefix = arg->prefix;
lnode_prefix.clear_suffix (lnode_depth);
getnode_res res (MERKLE_OK);
format_rpcnode (ltree, lnode_depth, lnode_prefix, lnode, &res.resok->node);
sbp->reply (&res);
break;
}
case MERKLESYNC_GETBLOCKLIST:
// request a list of blocks
{
//warn << (u_int) this << " dis..GETBLOCKLIST\n";
getblocklist_arg *arg = sbp->template getarg<getblocklist_arg> ();
ref<getblocklist_arg> arg_copy = New refcounted <getblocklist_arg> (*arg);
getblocklist_res res (MERKLE_OK);
chordID srcID = arg->srcID; // MUST be before sbp->reply
sbp->reply (&res);
// XXX DEADLOCK: if the blocks arrive before res, the remote side gets stuck.
for (u_int i = 0; i < arg_copy->keys.size (); i++) {
merkle_hash key = arg_copy->keys[i];
bool last = (i + 1 == arg_copy->keys.size ());
XXX_SENDBLOCK_ARGS a (srcID, tobigint (key), last, wrap (&ignorecb));
(*sndblkfnc) (&a);
}
break;
}
case MERKLESYNC_GETBLOCKRANGE:
// request all blocks in a given range, excluding a list of blocks (xkeys)
{
//warn << (u_int) this << " dis..GETBLOCKRANGE\n";
getblockrange_arg *arg = sbp->template getarg<getblockrange_arg> ();
getblockrange_res res (MERKLE_OK);
if (arg->bidirectional) {
res.resok->desired_xkeys.setsize (arg->xkeys.size ());
for (u_int i = 0; i < arg->xkeys.size (); i++) {
ptr<dbrec> blk = database_lookup (ltree->db, arg->xkeys[i]);
res.resok->desired_xkeys[i] = (blk == NULL);
}
}
db_iterator *iter;
iter = New db_range_xiterator (ltree->db, arg->depth, arg->prefix,
make_set (arg->xkeys), arg->rngmin,
arg->rngmax);
res.resok->will_send_blocks = iter->more ();
bigint srcID = arg->srcID;
sbp->reply (&res); // DONT REF arg AFTER THIS POINT!!!!
// XXX DEADLOCK: if the blocks arrive before 'res'...remote gets stuck
vNew merkle_send_range (iter, sndblkfnc, srcID);
break;
}
default:
assert (0);
sbp->reject (PROC_UNAVAIL);
break;
}
}
<|endoftext|> |
<commit_before><commit_msg>Contributions to tests by David Hoerl<commit_after><|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Thibaut Gridel <tgridel@free.fr>
//
#include <QtTest/QtTest>
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "MarbleMap.h"
#include "MarbleModel.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLineString.h"
namespace Marble
{
class ProjectionTest : public QObject
{
Q_OBJECT
private slots:
void drawLineString_data();
void drawLineString();
void setInvalidRadius();
private:
ViewportParams viewport;
};
void ProjectionTest::drawLineString_data()
{
QTest::addColumn<Marble::Projection>( "projection" );
QTest::addColumn<Marble::TessellationFlags>( "tessellation" );
QTest::addColumn<GeoDataLineString>( "line" );
QTest::addColumn<int>( "size" );
GeoDataCoordinates::Unit deg = GeoDataCoordinates::Degree;
GeoDataLineString longitudeLine;
longitudeLine << GeoDataCoordinates(185, 5, 0, deg )
<< GeoDataCoordinates(185, 15, 0, deg );
GeoDataLineString diagonalLine;
diagonalLine << GeoDataCoordinates(-185, 5, 0, deg )
<< GeoDataCoordinates(185, 15, 0, deg );
GeoDataLineString latitudeLine;
latitudeLine << GeoDataCoordinates(-185, 5, 0, deg )
<< GeoDataCoordinates(185, 5, 0, deg );
Projection projection = Mercator;
TessellationFlags flags = NoTessellation;
QTest::newRow("Mercator NoTesselation Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator NoTesselation Diagonal IDL")
<< projection << flags << diagonalLine << 2;
QTest::newRow("Mercator NoTesselation Latitude IDL")
<< projection << flags << latitudeLine << 2;
flags = Tessellate;
QTest::newRow("Mercator Tesselate Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator Tesselate Diagonal IDL")
<< projection << flags << diagonalLine << 4;
QTest::newRow("Mercator Tesselate Latitude IDL")
<< projection << flags << latitudeLine << 4;
flags = Tessellate | RespectLatitudeCircle;
QTest::newRow("Mercator LatitudeCircle Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator LatitudeCircle Diagonal IDL")
<< projection << flags << diagonalLine << 4;
QTest::newRow("Mercator LatitudeCircle Latitude IDL")
<< projection << flags << latitudeLine << 2;
projection = Spherical;
flags = NoTessellation;
QTest::newRow("Spherical NoTesselation Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical NoTesselation Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical NoTesselation Latitude IDL")
<< projection << flags << latitudeLine << 1;
flags = Tessellate;
QTest::newRow("Spherical Tesselate Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical Tesselate Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical Tesselate Latitude IDL")
<< projection << flags << latitudeLine << 1;
flags = Tessellate | RespectLatitudeCircle;
QTest::newRow("Spherical LatitudeCircle Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical LatitudeCircle Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical LatitudeCircle Latitude IDL")
<< projection << flags << latitudeLine << 1;
}
void ProjectionTest::drawLineString()
{
QFETCH( Marble::Projection, projection );
QFETCH( Marble::TessellationFlags, tessellation );
QFETCH( GeoDataLineString, line );
QFETCH( int, size );
viewport.setProjection( projection );
viewport.setRadius( 360 / 4 ); // for easy mapping of lon <-> x
viewport.centerOn(185 * DEG2RAD, 0);
line.setTessellationFlags( tessellation );
QVector<QPolygonF*> polys;
viewport.screenCoordinates(line, polys);
foreach (QPolygonF* poly, polys) {
// at least 2 points in one poly
QVERIFY( poly->size() > 1 );
QPointF oldCoord = poly->first();
poly->pop_front();
foreach(QPointF coord, *poly) {
// no 2 same points
QVERIFY( (coord-oldCoord) != QPointF() );
// no 2 consecutive points should be more than 90° apart
QVERIFY( (coord-oldCoord).manhattanLength() < viewport.radius() );
oldCoord = coord;
}
}
// check the provided number of polys
QCOMPARE( polys.size(), size );
}
void ProjectionTest::setInvalidRadius()
{
QVERIFY( viewport.radius() > 0 );
viewport.setRadius( 0 );
QVERIFY( viewport.radius() > 0 );
}
}
Q_DECLARE_METATYPE( Marble::Projection )
Q_DECLARE_METATYPE( Marble::TessellationFlag )
Q_DECLARE_METATYPE( Marble::TessellationFlags )
QTEST_MAIN( Marble::ProjectionTest )
#include "ProjectionTest.moc"
<commit_msg>make test cases truly independent<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Thibaut Gridel <tgridel@free.fr>
//
#include <QtTest/QtTest>
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "MarbleMap.h"
#include "MarbleModel.h"
#include "GeoDataCoordinates.h"
#include "GeoDataLineString.h"
namespace Marble
{
class ProjectionTest : public QObject
{
Q_OBJECT
private slots:
void drawLineString_data();
void drawLineString();
void setInvalidRadius();
};
void ProjectionTest::drawLineString_data()
{
QTest::addColumn<Marble::Projection>( "projection" );
QTest::addColumn<Marble::TessellationFlags>( "tessellation" );
QTest::addColumn<GeoDataLineString>( "line" );
QTest::addColumn<int>( "size" );
GeoDataCoordinates::Unit deg = GeoDataCoordinates::Degree;
GeoDataLineString longitudeLine;
longitudeLine << GeoDataCoordinates(185, 5, 0, deg )
<< GeoDataCoordinates(185, 15, 0, deg );
GeoDataLineString diagonalLine;
diagonalLine << GeoDataCoordinates(-185, 5, 0, deg )
<< GeoDataCoordinates(185, 15, 0, deg );
GeoDataLineString latitudeLine;
latitudeLine << GeoDataCoordinates(-185, 5, 0, deg )
<< GeoDataCoordinates(185, 5, 0, deg );
Projection projection = Mercator;
TessellationFlags flags = NoTessellation;
QTest::newRow("Mercator NoTesselation Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator NoTesselation Diagonal IDL")
<< projection << flags << diagonalLine << 2;
QTest::newRow("Mercator NoTesselation Latitude IDL")
<< projection << flags << latitudeLine << 2;
flags = Tessellate;
QTest::newRow("Mercator Tesselate Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator Tesselate Diagonal IDL")
<< projection << flags << diagonalLine << 4;
QTest::newRow("Mercator Tesselate Latitude IDL")
<< projection << flags << latitudeLine << 4;
flags = Tessellate | RespectLatitudeCircle;
QTest::newRow("Mercator LatitudeCircle Longitude")
<< projection << flags << longitudeLine << 2;
QTest::newRow("Mercator LatitudeCircle Diagonal IDL")
<< projection << flags << diagonalLine << 4;
QTest::newRow("Mercator LatitudeCircle Latitude IDL")
<< projection << flags << latitudeLine << 2;
projection = Spherical;
flags = NoTessellation;
QTest::newRow("Spherical NoTesselation Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical NoTesselation Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical NoTesselation Latitude IDL")
<< projection << flags << latitudeLine << 1;
flags = Tessellate;
QTest::newRow("Spherical Tesselate Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical Tesselate Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical Tesselate Latitude IDL")
<< projection << flags << latitudeLine << 1;
flags = Tessellate | RespectLatitudeCircle;
QTest::newRow("Spherical LatitudeCircle Longitude")
<< projection << flags << longitudeLine << 1;
QTest::newRow("Spherical LatitudeCircle Diagonal IDL")
<< projection << flags << diagonalLine << 1;
QTest::newRow("Spherical LatitudeCircle Latitude IDL")
<< projection << flags << latitudeLine << 1;
}
void ProjectionTest::drawLineString()
{
QFETCH( Marble::Projection, projection );
QFETCH( Marble::TessellationFlags, tessellation );
QFETCH( GeoDataLineString, line );
QFETCH( int, size );
ViewportParams viewport;
viewport.setProjection( projection );
viewport.setRadius( 360 / 4 ); // for easy mapping of lon <-> x
viewport.centerOn(185 * DEG2RAD, 0);
line.setTessellationFlags( tessellation );
QVector<QPolygonF*> polys;
viewport.screenCoordinates(line, polys);
foreach (QPolygonF* poly, polys) {
// at least 2 points in one poly
QVERIFY( poly->size() > 1 );
QPointF oldCoord = poly->first();
poly->pop_front();
foreach(QPointF coord, *poly) {
// no 2 same points
QVERIFY( (coord-oldCoord) != QPointF() );
// no 2 consecutive points should be more than 90° apart
QVERIFY( (coord-oldCoord).manhattanLength() < viewport.radius() );
oldCoord = coord;
}
}
// check the provided number of polys
QCOMPARE( polys.size(), size );
}
void ProjectionTest::setInvalidRadius()
{
ViewportParams viewport;
QVERIFY( viewport.radius() > 0 );
viewport.setRadius( 0 );
QVERIFY( viewport.radius() > 0 );
}
}
Q_DECLARE_METATYPE( Marble::Projection )
Q_DECLARE_METATYPE( Marble::TessellationFlag )
Q_DECLARE_METATYPE( Marble::TessellationFlags )
QTEST_MAIN( Marble::ProjectionTest )
#include "ProjectionTest.moc"
<|endoftext|> |
<commit_before>/*! \file uobject-common.cc
*******************************************************************************
File: uobject-common.cc\n
Implementation of the UObject class.
This file is part of LIBURBI\n
Copyright (c) 2004, 2005, 2006, 2007, 2008 Jean-Christophe Baillie.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.com
**************************************************************************** */
#include <list>
#include "urbi/uobject.hh"
namespace urbi
{
STATIC_INSTANCE(UStartlist, objectlist);
STATIC_INSTANCE(UStartlistHub, objecthublist);
// Lists and hashtables used.
STATIC_INSTANCE(UTable, accessmap);
STATIC_INSTANCE(UTable, eventendmap);
STATIC_INSTANCE(UTable, eventmap);
STATIC_INSTANCE(UTable, functionmap);
STATIC_INSTANCE(UTable, monitormap);
STATIC_INSTANCE(UVarTable, varmap);
// Timer and update maps.
STATIC_INSTANCE(UTimerTable, timermap);
STATIC_INSTANCE(UTimerTable, updatemap);
//! Clean a callback UTable from all callbacks linked to the
//! object whose name is 'name'
void
cleanTable(UTable &t, const std::string& name)
{
std::list<UTable::iterator> todelete;
for (UTable::iterator i = t.begin(); i != t.end(); ++i)
{
std::list<UGenericCallback*>& tocheck = i->second;
for (std::list<UGenericCallback*>::iterator j = tocheck.begin();
j != tocheck.end();
)
{
if ((*j)->objname == name)
{
delete *j;
j = tocheck.erase(j);
}
else
++j;
}
if (tocheck.empty())
todelete.push_back(i);
}
for (std::list<UTable::iterator>::iterator i = todelete.begin();
i != todelete.end();
++i)
t.erase(*i);
}
} // namespace urbi
<commit_msg>Use STATIC_INSTANCE_NS.<commit_after>/*! \file uobject-common.cc
*******************************************************************************
File: uobject-common.cc\n
Implementation of the UObject class.
This file is part of LIBURBI\n
Copyright (c) 2004, 2005, 2006, 2007, 2008 Jean-Christophe Baillie.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.com
**************************************************************************** */
#include <list>
#include "urbi/uobject.hh"
// These calls are made out of any namespace due to vcxx error C2888
// cf: http://msdn.microsoft.com/en-us/library/27zksbks(VS.80).aspx
STATIC_INSTANCE_NS(UStartlist, objectlist, urbi);
STATIC_INSTANCE_NS(UStartlistHub, objecthublist, urbi);
// Lists and hashtables used.
STATIC_INSTANCE_NS(UTable, accessmap, urbi);
STATIC_INSTANCE_NS(UTable, eventendmap, urbi);
STATIC_INSTANCE_NS(UTable, eventmap, urbi);
STATIC_INSTANCE_NS(UTable, functionmap, urbi);
STATIC_INSTANCE_NS(UTable, monitormap, urbi);
STATIC_INSTANCE_NS(UVarTable, varmap, urbi);
// Timer and update maps.
STATIC_INSTANCE_NS(UTimerTable, timermap, urbi);
STATIC_INSTANCE_NS(UTimerTable, updatemap, urbi);
namespace urbi
{
//! Clean a callback UTable from all callbacks linked to the
//! object whose name is 'name'
void
cleanTable(UTable &t, const std::string& name)
{
std::list<UTable::iterator> todelete;
for (UTable::iterator i = t.begin(); i != t.end(); ++i)
{
std::list<UGenericCallback*>& tocheck = i->second;
for (std::list<UGenericCallback*>::iterator j = tocheck.begin();
j != tocheck.end();
)
{
if ((*j)->objname == name)
{
delete *j;
j = tocheck.erase(j);
}
else
++j;
}
if (tocheck.empty())
todelete.push_back(i);
}
for (std::list<UTable::iterator>::iterator i = todelete.begin();
i != todelete.end();
++i)
t.erase(*i);
}
} // namespace urbi
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <ttl/mmap.h>
using namespace thalhammer;
TEST(MMAPTest, MapFile) {
const std::string data = "Hello World, how are you ?";
mmap map;
ASSERT_EQ(nullptr, map.data());
ASSERT_FALSE(map.is_valid());
ASSERT_TRUE(map.open("test_data/mmap_test.txt"));
ASSERT_TRUE(map.is_valid());
ASSERT_NE(nullptr, map.data());
ASSERT_EQ(map.data(), &map[0]);
ASSERT_EQ(map.data(), &map.at(0));
ASSERT_EQ(data.size(), map.size());
ASSERT_TRUE(memcmp(data.data(), map.data(), map.size()) == 0);
}
TEST(MMAPTest, MapFileFailed) {
mmap map;
ASSERT_EQ(nullptr, map.data());
ASSERT_FALSE(map.is_valid());
ASSERT_FALSE(map.open("test_data/mmap_test_not_existent.txt"));
ASSERT_FALSE(map.is_valid());
ASSERT_EQ(nullptr, map.data());
}
TEST(MMAPTest, MapFileConstructor) {
const std::string data = "Hello World, how are you ?";
ASSERT_THROW([]() {
mmap map("test_data/mmap_test_not_existent.txt");
}(), std::runtime_error);
mmap map("test_data/mmap_test.txt");
ASSERT_TRUE(map.is_valid());
ASSERT_NE(nullptr, map.data());
ASSERT_EQ(map.data(), &map[0]);
ASSERT_EQ(map.data(), &map.at(0));
ASSERT_EQ(data.size(), map.size());
ASSERT_TRUE(memcmp(data.data(), map.data(), map.size()) == 0);
}<commit_msg>Fix linux build errors<commit_after>#include <gtest/gtest.h>
#include <ttl/mmap.h>
using namespace thalhammer;
TEST(MMAPTest, MapFile) {
const std::string data = "Hello World, how are you ?";
thalhammer::mmap map;
ASSERT_EQ(nullptr, map.data());
ASSERT_FALSE(map.is_valid());
ASSERT_TRUE(map.open("test_data/mmap_test.txt"));
ASSERT_TRUE(map.is_valid());
ASSERT_NE(nullptr, map.data());
ASSERT_EQ(map.data(), &map[0]);
ASSERT_EQ(map.data(), &map.at(0));
ASSERT_EQ(data.size(), map.size());
ASSERT_TRUE(memcmp(data.data(), map.data(), map.size()) == 0);
}
TEST(MMAPTest, MapFileFailed) {
thalhammer::mmap map;
ASSERT_EQ(nullptr, map.data());
ASSERT_FALSE(map.is_valid());
ASSERT_FALSE(map.open("test_data/mmap_test_not_existent.txt"));
ASSERT_FALSE(map.is_valid());
ASSERT_EQ(nullptr, map.data());
}
TEST(MMAPTest, MapFileConstructor) {
const std::string data = "Hello World, how are you ?";
ASSERT_THROW([]() {
thalhammer::mmap map("test_data/mmap_test_not_existent.txt");
}(), std::runtime_error);
thalhammer::mmap map("test_data/mmap_test.txt");
ASSERT_TRUE(map.is_valid());
ASSERT_NE(nullptr, map.data());
ASSERT_EQ(map.data(), &map[0]);
ASSERT_EQ(map.data(), &map.at(0));
ASSERT_EQ(data.size(), map.size());
ASSERT_TRUE(memcmp(data.data(), map.data(), map.size()) == 0);
}<|endoftext|> |
<commit_before>/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <functional>
#ifdef _WIN32
#include <Windows.h>
#endif
using namespace Aws::Utils;
void StringUtils::Replace(Aws::String& s, const char* search, const char* replace)
{
if(!search || !replace)
{
return;
}
size_t replaceLength = strlen(replace);
size_t searchLength = strlen(search);
for (std::size_t pos = 0;; pos += replaceLength)
{
pos = s.find(search, pos);
if (pos == Aws::String::npos)
break;
s.erase(pos, searchLength);
s.insert(pos, replace);
}
}
Aws::String StringUtils::ToLower(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::tolower(c); });
return copy;
}
Aws::String StringUtils::ToUpper(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::toupper(c); });
return copy;
}
bool StringUtils::CaselessCompare(const char* value1, const char* value2)
{
Aws::String value1Lower = ToLower(value1);
Aws::String value2Lower = ToLower(value2);
return value1Lower == value2Lower;
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)
{
return Split(toSplit, splitOn, SIZE_MAX);
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn, size_t numOfTargetParts)
{
Aws::Vector<Aws::String> returnValues;
Aws::StringStream input(toSplit);
Aws::String item;
while(returnValues.size() < numOfTargetParts - 1 && std::getline(input, item, splitOn))
{
if (item.size())
{
returnValues.emplace_back(std::move(item));
}
}
if (std::getline(input, item, static_cast<char>(EOF)) && item.size())
{
returnValues.emplace_back(std::move(item));
}
return returnValues;
}
Aws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while (std::getline(input, item))
{
if (item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::String StringUtils::URLEncode(const char* unsafe)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unsafe);
for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= 0 && (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~'))
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << '%' << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::UTF8Escape(const char* unicodeString, const char* delimiter)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unicodeString);
for (auto i = unicodeString, n = unicodeString + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= ' ' && c < 127 )
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << delimiter << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::URLEncode(double unsafe)
{
char buffer[32];
#if defined(_MSC_VER) && _MSC_VER < 1900
_snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "%g", unsafe);
#else
snprintf(buffer, sizeof(buffer), "%g", unsafe);
#endif
return StringUtils::URLEncode(buffer);
}
Aws::String StringUtils::URLDecode(const char* safe)
{
Aws::StringStream unescaped;
unescaped.fill('0');
unescaped << std::hex;
size_t safeLength = strlen(safe);
for (auto i = safe, n = safe + safeLength; i != n; ++i)
{
char c = *i;
if(c == '%')
{
char hex[3];
hex[0] = *(i + 1);
hex[1] = *(i + 2);
hex[2] = 0;
i += 2;
auto hexAsInteger = strtol(hex, nullptr, 16);
unescaped << (char)hexAsInteger;
}
else
{
unescaped << *i;
}
}
return unescaped.str();
}
Aws::String StringUtils::LTrim(const char* source)
{
Aws::String copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), [](int ch) { return !::isspace(ch); }));
return copy;
}
// trim from end
Aws::String StringUtils::RTrim(const char* source)
{
Aws::String copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), [](int ch) { return !::isspace(ch); }).base(), copy.end());
return copy;
}
// trim from both ends
Aws::String StringUtils::Trim(const char* source)
{
return LTrim(RTrim(source).c_str());
}
long long StringUtils::ConvertToInt64(const char* source)
{
if(!source)
{
return 0;
}
#ifdef __ANDROID__
return atoll(source);
#else
return std::atoll(source);
#endif // __ANDROID__
}
long StringUtils::ConvertToInt32(const char* source)
{
if (!source)
{
return 0;
}
return std::atol(source);
}
bool StringUtils::ConvertToBool(const char* source)
{
if(!source)
{
return false;
}
Aws::String strValue = ToLower(source);
if(strValue == "true" || strValue == "1")
{
return true;
}
return false;
}
double StringUtils::ConvertToDouble(const char* source)
{
if(!source)
{
return 0.0;
}
return std::strtod(source, NULL);
}
#ifdef _WIN32
Aws::WString StringUtils::ToWString(const char* source)
{
const auto len = static_cast<int>(std::strlen(source));
Aws::WString outString;
outString.resize(len); // there is no way UTF-16 would require _more_ code-points than UTF-8 for the _same_ string
const auto result = MultiByteToWideChar(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpMultiByteStr*/,
len /*cbMultiByte*/,
&outString[0] /*lpWideCharStr*/,
static_cast<int>(outString.length())/*cchWideChar*/);
if (!result)
{
return L"";
}
outString.resize(result);
return outString;
}
Aws::String StringUtils::FromWString(const wchar_t* source)
{
const auto len = static_cast<int>(std::wcslen(source));
Aws::String output;
if (int requiredSizeInBytes = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
nullptr /*lpMultiByteStr*/,
0 /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/))
{
output.resize(requiredSizeInBytes);
}
const auto result = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
&output[0] /*lpMultiByteStr*/,
static_cast<int>(output.length()) /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/);
if (!result)
{
return "";
}
output.resize(result);
return output;
}
#endif
<commit_msg>Ensure input to isspace is within the right limits<commit_after>/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <functional>
#ifdef _WIN32
#include <Windows.h>
#endif
using namespace Aws::Utils;
void StringUtils::Replace(Aws::String& s, const char* search, const char* replace)
{
if(!search || !replace)
{
return;
}
size_t replaceLength = strlen(replace);
size_t searchLength = strlen(search);
for (std::size_t pos = 0;; pos += replaceLength)
{
pos = s.find(search, pos);
if (pos == Aws::String::npos)
break;
s.erase(pos, searchLength);
s.insert(pos, replace);
}
}
Aws::String StringUtils::ToLower(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::tolower(c); });
return copy;
}
Aws::String StringUtils::ToUpper(const char* source)
{
Aws::String copy;
size_t sourceLength = strlen(source);
copy.resize(sourceLength);
//appease the latest whims of the VC++ 2017 gods
std::transform(source, source + sourceLength, copy.begin(), [](unsigned char c) { return (char)::toupper(c); });
return copy;
}
bool StringUtils::CaselessCompare(const char* value1, const char* value2)
{
Aws::String value1Lower = ToLower(value1);
Aws::String value2Lower = ToLower(value2);
return value1Lower == value2Lower;
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)
{
return Split(toSplit, splitOn, SIZE_MAX);
}
Aws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn, size_t numOfTargetParts)
{
Aws::Vector<Aws::String> returnValues;
Aws::StringStream input(toSplit);
Aws::String item;
while(returnValues.size() < numOfTargetParts - 1 && std::getline(input, item, splitOn))
{
if (item.size())
{
returnValues.emplace_back(std::move(item));
}
}
if (std::getline(input, item, static_cast<char>(EOF)) && item.size())
{
returnValues.emplace_back(std::move(item));
}
return returnValues;
}
Aws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)
{
Aws::StringStream input(toSplit);
Aws::Vector<Aws::String> returnValues;
Aws::String item;
while (std::getline(input, item))
{
if (item.size() > 0)
{
returnValues.push_back(item);
}
}
return returnValues;
}
Aws::String StringUtils::URLEncode(const char* unsafe)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unsafe);
for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= 0 && (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~'))
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << '%' << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::UTF8Escape(const char* unicodeString, const char* delimiter)
{
Aws::StringStream escaped;
escaped.fill('0');
escaped << std::hex << std::uppercase;
size_t unsafeLength = strlen(unicodeString);
for (auto i = unicodeString, n = unicodeString + unsafeLength; i != n; ++i)
{
int c = *i;
//MSVC 2015 has an assertion that c is positive in isalnum(). This breaks unicode support.
//bypass that with the first check.
if (c >= ' ' && c < 127 )
{
escaped << (char)c;
}
else
{
//this unsigned char cast allows us to handle unicode characters.
escaped << delimiter << std::setw(2) << int((unsigned char)c) << std::setw(0);
}
}
return escaped.str();
}
Aws::String StringUtils::URLEncode(double unsafe)
{
char buffer[32];
#if defined(_MSC_VER) && _MSC_VER < 1900
_snprintf_s(buffer, sizeof(buffer), _TRUNCATE, "%g", unsafe);
#else
snprintf(buffer, sizeof(buffer), "%g", unsafe);
#endif
return StringUtils::URLEncode(buffer);
}
Aws::String StringUtils::URLDecode(const char* safe)
{
Aws::StringStream unescaped;
unescaped.fill('0');
unescaped << std::hex;
size_t safeLength = strlen(safe);
for (auto i = safe, n = safe + safeLength; i != n; ++i)
{
char c = *i;
if(c == '%')
{
char hex[3];
hex[0] = *(i + 1);
hex[1] = *(i + 2);
hex[2] = 0;
i += 2;
auto hexAsInteger = strtol(hex, nullptr, 16);
unescaped << (char)hexAsInteger;
}
else
{
unescaped << *i;
}
}
return unescaped.str();
}
static bool IsSpace(int ch)
{
if (ch < -1 || ch > 255)
{
return false;
}
return ::isspace(ch) != 0;
}
Aws::String StringUtils::LTrim(const char* source)
{
Aws::String copy(source);
copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), [](int ch) { return !IsSpace(ch); }));
return copy;
}
// trim from end
Aws::String StringUtils::RTrim(const char* source)
{
Aws::String copy(source);
copy.erase(std::find_if(copy.rbegin(), copy.rend(), [](int ch) { return !IsSpace(ch); }).base(), copy.end());
return copy;
}
// trim from both ends
Aws::String StringUtils::Trim(const char* source)
{
return LTrim(RTrim(source).c_str());
}
long long StringUtils::ConvertToInt64(const char* source)
{
if(!source)
{
return 0;
}
#ifdef __ANDROID__
return atoll(source);
#else
return std::atoll(source);
#endif // __ANDROID__
}
long StringUtils::ConvertToInt32(const char* source)
{
if (!source)
{
return 0;
}
return std::atol(source);
}
bool StringUtils::ConvertToBool(const char* source)
{
if(!source)
{
return false;
}
Aws::String strValue = ToLower(source);
if(strValue == "true" || strValue == "1")
{
return true;
}
return false;
}
double StringUtils::ConvertToDouble(const char* source)
{
if(!source)
{
return 0.0;
}
return std::strtod(source, NULL);
}
#ifdef _WIN32
Aws::WString StringUtils::ToWString(const char* source)
{
const auto len = static_cast<int>(std::strlen(source));
Aws::WString outString;
outString.resize(len); // there is no way UTF-16 would require _more_ code-points than UTF-8 for the _same_ string
const auto result = MultiByteToWideChar(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpMultiByteStr*/,
len /*cbMultiByte*/,
&outString[0] /*lpWideCharStr*/,
static_cast<int>(outString.length())/*cchWideChar*/);
if (!result)
{
return L"";
}
outString.resize(result);
return outString;
}
Aws::String StringUtils::FromWString(const wchar_t* source)
{
const auto len = static_cast<int>(std::wcslen(source));
Aws::String output;
if (int requiredSizeInBytes = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
nullptr /*lpMultiByteStr*/,
0 /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/))
{
output.resize(requiredSizeInBytes);
}
const auto result = WideCharToMultiByte(CP_UTF8 /*CodePage*/,
0 /*dwFlags*/,
source /*lpWideCharStr*/,
len /*cchWideChar*/,
&output[0] /*lpMultiByteStr*/,
static_cast<int>(output.length()) /*cbMultiByte*/,
nullptr /*lpDefaultChar*/,
nullptr /*lpUsedDefaultChar*/);
if (!result)
{
return "";
}
output.resize(result);
return output;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "FormData.h"
#include "HTTPHeaderMap.h"
#include "ResourceRequest.h"
#undef LOG
#include "base/logging.h"
#include "googleurl/src/gurl.h"
#include "net/base/upload_data.h"
#include "webkit/glue/weburlrequest_impl.h"
#include "webkit/glue/glue_serialize.h"
#include "webkit/glue/glue_util.h"
using WebCore::FormData;
using WebCore::FormDataElement;
using WebCore::HTTPHeaderMap;
using WebCore::ResourceRequest;
using WebCore::ResourceRequestCachePolicy;
using WebCore::String;
// WebRequest -----------------------------------------------------------------
WebRequestImpl::WebRequestImpl() {
}
WebRequestImpl::WebRequestImpl(const GURL& url)
: request_(ResourceRequest(webkit_glue::GURLToKURL(url))) {
}
WebRequestImpl::WebRequestImpl(const ResourceRequest& request)
: request_(request) {
}
WebRequest* WebRequestImpl::Clone() const {
return new WebRequestImpl(*this);
}
GURL WebRequestImpl::GetURL() const {
return webkit_glue::KURLToGURL(request_.url());
}
void WebRequestImpl::SetURL(const GURL& url) {
request_.setURL(webkit_glue::GURLToKURL(url));
}
GURL WebRequestImpl::GetFirstPartyForCookies() const {
return webkit_glue::KURLToGURL(
request_.resourceRequest().firstPartyForCookies());
}
void WebRequestImpl::SetFirstPartyForCookies(const GURL& url) {
request_.resourceRequest().setFirstPartyForCookies(
webkit_glue::GURLToKURL(url));
}
WebRequestCachePolicy WebRequestImpl::GetCachePolicy() const {
// WebRequestCachePolicy mirrors ResourceRequestCachePolicy
return static_cast<WebRequestCachePolicy>(request_.cachePolicy());
}
void WebRequestImpl::SetCachePolicy(WebRequestCachePolicy policy) {
// WebRequestCachePolicy mirrors ResourceRequestCachePolicy
request_.setCachePolicy(
static_cast<ResourceRequestCachePolicy>(policy));
}
std::string WebRequestImpl::GetHttpMethod() const {
return webkit_glue::StringToStdString(request_.httpMethod());
}
void WebRequestImpl::SetHttpMethod(const std::string& method) {
request_.setHTTPMethod(webkit_glue::StdStringToString(method));
}
std::string WebRequestImpl::GetHttpHeaderValue(const std::string& field) const {
return webkit_glue::StringToStdString(
request_.httpHeaderField(webkit_glue::StdStringToString(field)));
}
void WebRequestImpl::SetHttpHeaderValue(const std::string& field,
const std::string& value) {
request_.setHTTPHeaderField(
webkit_glue::StdStringToString(field),
webkit_glue::StdStringToString(value));
}
void WebRequestImpl::GetHttpHeaders(HeaderMap* headers) const {
headers->clear();
const HTTPHeaderMap& map = request_.httpHeaderFields();
HTTPHeaderMap::const_iterator end = map.end();
HTTPHeaderMap::const_iterator it = map.begin();
for (; it != end; ++it) {
headers->insert(std::make_pair(
webkit_glue::StringToStdString(it->first),
webkit_glue::StringToStdString(it->second)));
}
}
void WebRequestImpl::SetHttpHeaders(const HeaderMap& headers) {
HeaderMap::const_iterator end = headers.end();
HeaderMap::const_iterator it = headers.begin();
for (; it != end; ++it) {
request_.setHTTPHeaderField(
webkit_glue::StdStringToString(it->first),
webkit_glue::StdStringToString(it->second));
}
}
std::string WebRequestImpl::GetHttpReferrer() const {
return webkit_glue::StringToStdString(request_.httpReferrer());
}
std::string WebRequestImpl::GetSecurityInfo() const {
return webkit_glue::CStringToStdString(request_.securityInfo());
}
void WebRequestImpl::SetSecurityInfo(const std::string& value) {
request_.setSecurityInfo(webkit_glue::StdStringToCString(value));
}
bool WebRequestImpl::HasUploadData() const {
FormData* formdata = request_.httpBody();
return formdata && !formdata->isEmpty();
}
void WebRequestImpl::GetUploadData(net::UploadData* data) const {
FormData* formdata = request_.httpBody();
if (!formdata)
return;
const Vector<FormDataElement>& elements = formdata->elements();
Vector<FormDataElement>::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
const FormDataElement& element = (*it);
if (element.m_type == FormDataElement::data) {
data->AppendBytes(element.m_data.data(), element.m_data.size());
} else if (element.m_type == FormDataElement::encodedFile) {
data->AppendFile(
FilePath(webkit_glue::StringToFilePathString(element.m_filename)));
} else {
NOTREACHED();
}
}
data->set_identifier(formdata->identifier());
}
void WebRequestImpl::SetUploadData(const net::UploadData& data)
{
RefPtr<FormData> formdata = FormData::create();
const std::vector<net::UploadData::Element>& elements = data.elements();
std::vector<net::UploadData::Element>::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
const net::UploadData::Element& element = (*it);
if (element.type() == net::UploadData::TYPE_BYTES) {
formdata->appendData(
std::string(element.bytes().begin(), element.bytes().end()).c_str(),
element.bytes().size());
} else if (element.type() == net::UploadData::TYPE_FILE) {
formdata->appendFile(
webkit_glue::FilePathStringToString(element.file_path().value()));
} else {
NOTREACHED();
}
}
formdata->setIdentifier(data.identifier());
request_.setHTTPBody(formdata);
}
void WebRequestImpl::SetRequestorID(int requestor_id) {
request_.setRequestorID(requestor_id);
}
// static
WebRequest* WebRequest::Create(const GURL& url) {
return new WebRequestImpl(url);
}
<commit_msg>Fix merge.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "FormData.h"
#include "HTTPHeaderMap.h"
#include "ResourceRequest.h"
#undef LOG
#include "base/logging.h"
#include "googleurl/src/gurl.h"
#include "net/base/upload_data.h"
#include "webkit/glue/weburlrequest_impl.h"
#include "webkit/glue/glue_serialize.h"
#include "webkit/glue/glue_util.h"
using WebCore::FormData;
using WebCore::FormDataElement;
using WebCore::HTTPHeaderMap;
using WebCore::ResourceRequest;
using WebCore::ResourceRequestCachePolicy;
using WebCore::String;
// WebRequest -----------------------------------------------------------------
WebRequestImpl::WebRequestImpl() {
}
WebRequestImpl::WebRequestImpl(const GURL& url)
: request_(ResourceRequest(webkit_glue::GURLToKURL(url))) {
}
WebRequestImpl::WebRequestImpl(const ResourceRequest& request)
: request_(request) {
}
WebRequest* WebRequestImpl::Clone() const {
return new WebRequestImpl(*this);
}
GURL WebRequestImpl::GetURL() const {
return webkit_glue::KURLToGURL(request_.url());
}
void WebRequestImpl::SetURL(const GURL& url) {
request_.setURL(webkit_glue::GURLToKURL(url));
}
GURL WebRequestImpl::GetFirstPartyForCookies() const {
return webkit_glue::KURLToGURL(request_.firstPartyForCookies());
}
void WebRequestImpl::SetFirstPartyForCookies(const GURL& url) {
request_.setFirstPartyForCookies(webkit_glue::GURLToKURL(url));
}
WebRequestCachePolicy WebRequestImpl::GetCachePolicy() const {
// WebRequestCachePolicy mirrors ResourceRequestCachePolicy
return static_cast<WebRequestCachePolicy>(request_.cachePolicy());
}
void WebRequestImpl::SetCachePolicy(WebRequestCachePolicy policy) {
// WebRequestCachePolicy mirrors ResourceRequestCachePolicy
request_.setCachePolicy(
static_cast<ResourceRequestCachePolicy>(policy));
}
std::string WebRequestImpl::GetHttpMethod() const {
return webkit_glue::StringToStdString(request_.httpMethod());
}
void WebRequestImpl::SetHttpMethod(const std::string& method) {
request_.setHTTPMethod(webkit_glue::StdStringToString(method));
}
std::string WebRequestImpl::GetHttpHeaderValue(const std::string& field) const {
return webkit_glue::StringToStdString(
request_.httpHeaderField(webkit_glue::StdStringToString(field)));
}
void WebRequestImpl::SetHttpHeaderValue(const std::string& field,
const std::string& value) {
request_.setHTTPHeaderField(
webkit_glue::StdStringToString(field),
webkit_glue::StdStringToString(value));
}
void WebRequestImpl::GetHttpHeaders(HeaderMap* headers) const {
headers->clear();
const HTTPHeaderMap& map = request_.httpHeaderFields();
HTTPHeaderMap::const_iterator end = map.end();
HTTPHeaderMap::const_iterator it = map.begin();
for (; it != end; ++it) {
headers->insert(std::make_pair(
webkit_glue::StringToStdString(it->first),
webkit_glue::StringToStdString(it->second)));
}
}
void WebRequestImpl::SetHttpHeaders(const HeaderMap& headers) {
HeaderMap::const_iterator end = headers.end();
HeaderMap::const_iterator it = headers.begin();
for (; it != end; ++it) {
request_.setHTTPHeaderField(
webkit_glue::StdStringToString(it->first),
webkit_glue::StdStringToString(it->second));
}
}
std::string WebRequestImpl::GetHttpReferrer() const {
return webkit_glue::StringToStdString(request_.httpReferrer());
}
std::string WebRequestImpl::GetSecurityInfo() const {
return webkit_glue::CStringToStdString(request_.securityInfo());
}
void WebRequestImpl::SetSecurityInfo(const std::string& value) {
request_.setSecurityInfo(webkit_glue::StdStringToCString(value));
}
bool WebRequestImpl::HasUploadData() const {
FormData* formdata = request_.httpBody();
return formdata && !formdata->isEmpty();
}
void WebRequestImpl::GetUploadData(net::UploadData* data) const {
FormData* formdata = request_.httpBody();
if (!formdata)
return;
const Vector<FormDataElement>& elements = formdata->elements();
Vector<FormDataElement>::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
const FormDataElement& element = (*it);
if (element.m_type == FormDataElement::data) {
data->AppendBytes(element.m_data.data(), element.m_data.size());
} else if (element.m_type == FormDataElement::encodedFile) {
data->AppendFile(
FilePath(webkit_glue::StringToFilePathString(element.m_filename)));
} else {
NOTREACHED();
}
}
data->set_identifier(formdata->identifier());
}
void WebRequestImpl::SetUploadData(const net::UploadData& data)
{
RefPtr<FormData> formdata = FormData::create();
const std::vector<net::UploadData::Element>& elements = data.elements();
std::vector<net::UploadData::Element>::const_iterator it = elements.begin();
for (; it != elements.end(); ++it) {
const net::UploadData::Element& element = (*it);
if (element.type() == net::UploadData::TYPE_BYTES) {
formdata->appendData(
std::string(element.bytes().begin(), element.bytes().end()).c_str(),
element.bytes().size());
} else if (element.type() == net::UploadData::TYPE_FILE) {
formdata->appendFile(
webkit_glue::FilePathStringToString(element.file_path().value()));
} else {
NOTREACHED();
}
}
formdata->setIdentifier(data.identifier());
request_.setHTTPBody(formdata);
}
void WebRequestImpl::SetRequestorID(int requestor_id) {
request_.setRequestorID(requestor_id);
}
// static
WebRequest* WebRequest::Create(const GURL& url) {
return new WebRequestImpl(url);
}
<|endoftext|> |
<commit_before>/*!
* \page batch_travelccm_cpp Command-Line Utility to Demonstrate Typical TravelCCM Usage
* \code
*/
// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Boost (Extended STL)
#include <boost/program_options.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TravelCCM
#include <travelccm/TRAVELCCM_Service.hpp>
#include <travelccm/config/travelccm-paths.hpp>
// //////// Constants //////
/** Default name and location for the log file. */
const std::string K_TRAVELCCM_DEFAULT_LOG_FILENAME ("travelccm.log");
/** Default name and location for the (CSV) input file. */
const std::string K_TRAVELCCM_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR
"/ccm_01.csv");
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/** Early return status (so that it can be differentiated from an error). */
const int K_TRAVELCCM_EARLY_RETURN_STATUS = 99;
/** Read and parse the command line options. */
int readConfiguration (int argc, char* argv[], std::string& lInputFilename,
std::string& lLogFilename) {
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("input,i",
boost::program_options::value< std::string >(&lInputFilename)->default_value(K_TRAVELCCM_DEFAULT_INPUT_FILENAME),
"(CVS) input file for customer choice")
("log,l",
boost::program_options::value< std::string >(&lLogFilename)->default_value(K_TRAVELCCM_DEFAULT_LOG_FILENAME),
"Filename for the logs")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("travelccm.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("input")) {
lInputFilename = vm["input"].as< std::string >();
std::cout << "Input filename is: " << lInputFilename << std::endl;
}
if (vm.count ("log")) {
lLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << lLogFilename << std::endl;
}
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
// Input file name
std::string lInputFilename;
// Output log File
std::string lLogFilename;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, lInputFilename, lLogFilename);
if (lOptionParserStatus == K_TRAVELCCM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the service context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
// Build the BOM tree
TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to TravelCCM");
// Build a list of travel solutions
const stdair::BookingRequestStruct& lBookingRequest =
travelccmService.buildSampleBookingRequest();
// DEBUG
STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display());
// Build the sample BOM tree
stdair::TravelSolutionList_T lTSList;
travelccmService.buildSampleTravelSolutions (lTSList);
// DEBUG: Display the list of travel solutions
const std::string& lCSVDump = travelccmService.csvDisplay (lTSList);
STDAIR_LOG_DEBUG (lCSVDump);
// Choose a travel solution
const stdair::TravelSolutionStruct* lTS_ptr =
travelccmService.chooseTravelSolution (lTSList, lBookingRequest);
if (lTS_ptr != NULL) {
// DEBUG
STDAIR_LOG_DEBUG ("Chosen travel solution: " << lTS_ptr->display());
} else {
// DEBUG
STDAIR_LOG_DEBUG ("No travel solution can be found for "
<< lBookingRequest.display()
<< " within the following list of travel solutions");
STDAIR_LOG_DEBUG (lCSVDump);
}
// Close the Log outputFile
logOutputFile.close();
/*
Note: as that program is not intended to be run on a server in
production, it is better not to catch the exceptions. When it
happens (that an exception is throwned), that way we get the
call stack.
*/
return 0;
}
<commit_msg>[TravelCCM][Dev][Doc] Added the built-in option to the batch and improved the base documentation.<commit_after>/*!
* \page batch_travelccm_cpp Command-Line Utility to Demonstrate Typical TravelCCM Usage
* \code
*/
// STL
#include <cassert>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
// Boost (Extended STL)
#include <boost/program_options.hpp>
// StdAir
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/bom/TravelSolutionStruct.hpp>
#include <stdair/service/Logger.hpp>
// TravelCCM
#include <travelccm/TRAVELCCM_Service.hpp>
#include <travelccm/config/travelccm-paths.hpp>
// //////// Constants //////
/**
* Default name and location for the log file.
*/
const std::string K_TRAVELCCM_DEFAULT_LOG_FILENAME ("travelccm.log");
/**
* Default name and location for the (CSV) input file.
*/
const std::string K_TRAVELCCM_DEFAULT_INPUT_FILENAME (STDAIR_SAMPLE_DIR
"/ccm_01.csv");
/**
* Default for the input type. It can be either built-in or provided by an
* input file. That latter must then be given with the -i option.
*/
const bool K_TRAVELCCM_DEFAULT_BUILT_IN_INPUT = false;
/**
* Early return status (so that it can be differentiated from an error).
*/
const int K_TRAVELCCM_EARLY_RETURN_STATUS = 99;
// ///////// Parsing of Options & Configuration /////////
// A helper function to simplify the main part.
template<class T> std::ostream& operator<< (std::ostream& os,
const std::vector<T>& v) {
std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, " "));
return os;
}
/**
* Read and parse the command line options.
*/
int readConfiguration (int argc, char* argv[], bool& ioIsBuiltin,
stdair::Filename_T& lInputFilename,
stdair::Filename_T& lLogFilename) {
// Default for the built-in input
ioIsBuiltin = K_TRAVELCCM_DEFAULT_BUILT_IN_INPUT;
// Declare a group of options that will be allowed only on command line
boost::program_options::options_description generic ("Generic options");
generic.add_options()
("prefix", "print installation prefix")
("version,v", "print version string")
("help,h", "produce help message");
// Declare a group of options that will be allowed both on command
// line and in config file
boost::program_options::options_description config ("Configuration");
config.add_options()
("builtin,b",
"The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i/--input option")
("input,i",
boost::program_options::value< std::string >(&lInputFilename)->default_value(K_TRAVELCCM_DEFAULT_INPUT_FILENAME),
"(CSV) input file for the customer choice rule sets")
("log,l",
boost::program_options::value< std::string >(&lLogFilename)->default_value(K_TRAVELCCM_DEFAULT_LOG_FILENAME),
"Filename for the logs")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
boost::program_options::options_description hidden ("Hidden options");
hidden.add_options()
("copyright",
boost::program_options::value< std::vector<std::string> >(),
"Show the copyright (license)");
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(config).add(hidden);
boost::program_options::options_description config_file_options;
config_file_options.add(config).add(hidden);
boost::program_options::options_description visible ("Allowed options");
visible.add(generic).add(config);
boost::program_options::positional_options_description p;
p.add ("copyright", -1);
boost::program_options::variables_map vm;
boost::program_options::
store (boost::program_options::command_line_parser (argc, argv).
options (cmdline_options).positional(p).run(), vm);
std::ifstream ifs ("travelccm.cfg");
boost::program_options::store (parse_config_file (ifs, config_file_options),
vm);
boost::program_options::notify (vm);
if (vm.count ("help")) {
std::cout << visible << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("version")) {
std::cout << PACKAGE_NAME << ", version " << PACKAGE_VERSION << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("prefix")) {
std::cout << "Installation prefix: " << PREFIXDIR << std::endl;
return K_TRAVELCCM_EARLY_RETURN_STATUS;
}
if (vm.count ("builtin")) {
ioIsBuiltin = true;
}
const std::string isBuiltinStr = (ioIsBuiltin == true)?"yes":"no";
std::cout << "The BOM should be built-in? " << isBuiltinStr << std::endl;
if (ioIsBuiltin == false) {
// The BOM tree should be built from parsing a customer-choice rule file
if (vm.count ("input")) {
lInputFilename = vm["input"].as< std::string >();
std::cout << "Input filename is: " << lInputFilename << std::endl;
} else {
// The built-in option is not selected. However, no demand input file
// is specified
std::cerr << "Either one among the -b/--builtin and -i/--input "
<< "options must be specified" << std::endl;
}
}
if (vm.count ("log")) {
lLogFilename = vm["log"].as< std::string >();
std::cout << "Log filename is: " << lLogFilename << std::endl;
}
return 0;
}
// ///////// M A I N ////////////
int main (int argc, char* argv[]) {
// State whether the BOM tree should be built-in or parsed from an input file
bool isBuiltin;
// Input file name
stdair::Filename_T lInputFilename;
// Output log File
stdair::Filename_T lLogFilename;
// Call the command-line option parser
const int lOptionParserStatus =
readConfiguration (argc, argv, isBuiltin, lInputFilename, lLogFilename);
if (lOptionParserStatus == K_TRAVELCCM_EARLY_RETURN_STATUS) {
return 0;
}
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the service context
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
// Build the BOM tree
TRAVELCCM::TRAVELCCM_Service travelccmService (lLogParams);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to TravelCCM");
// Check wether or not a (CSV) input file should be read
if (isBuiltin == true) {
// Create a sample Customer-Choice rule object, and insert it
// within the BOM tree
travelccmService.buildSampleBom();
} else {
/**
* Create the Customer-Choice rule objects, and insert them within
* the BOM tree.
*
* \note For now, there is no input file parser.
*/
// travelccmService.parseAndLoad (lInputFilename);
}
// Build a list of travel solutions
const stdair::BookingRequestStruct& lBookingRequest =
travelccmService.buildSampleBookingRequest();
// DEBUG
STDAIR_LOG_DEBUG ("Booking request: " << lBookingRequest.display());
// Build the sample BOM tree
stdair::TravelSolutionList_T lTSList;
travelccmService.buildSampleTravelSolutions (lTSList);
// DEBUG: Display the list of travel solutions
const std::string& lCSVDump = travelccmService.csvDisplay (lTSList);
STDAIR_LOG_DEBUG (lCSVDump);
// Choose a travel solution
const stdair::TravelSolutionStruct* lTS_ptr =
travelccmService.chooseTravelSolution (lTSList, lBookingRequest);
if (lTS_ptr != NULL) {
// DEBUG
STDAIR_LOG_DEBUG ("Chosen travel solution: " << lTS_ptr->display());
} else {
// DEBUG
STDAIR_LOG_DEBUG ("No travel solution can be found for "
<< lBookingRequest.display()
<< " within the following list of travel solutions");
STDAIR_LOG_DEBUG (lCSVDump);
}
// Close the Log outputFile
logOutputFile.close();
/**
* Note: as that program is not intended to be run on a server in
* production, it is better not to catch the exceptions. When it
* happens (that an exception is throwned), that way we get the
* call stack.
*/
return 0;
}
<|endoftext|> |
<commit_before>/*
Bacula® - The Network Backup Solution
Copyright (C) 2000-2007 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from
many others, a complete list can be found in the file AUTHORS.
This program is Free Software; you can redistribute it and/or
modify it under the terms of version two of the GNU General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
Bacula® is a registered trademark of John Walker.
The licensor of Bacula is the Free Software Foundation Europe
(FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
Switzerland, email:ftf@fsfeurope.org.
*/
/*
* Version $Id$
*
* MediaList Class
*
* Dirk Bartley, March 2007
*
*/
#include <QAbstractEventDispatcher>
#include <QMenu>
#include "bat.h"
#include "medialist.h"
#include "mediaedit/mediaedit.h"
#include "joblist/joblist.h"
#include "relabel/relabel.h"
#include "run/run.h"
MediaList::MediaList()
{
setupUi(this);
m_name = "Media";
pgInitialize();
QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png")));
/* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */
m_populated = false;
m_checkcurwidget = true;
m_closeable = false;
/* add context sensitive menu items specific to this classto the page
* selector tree. m_contextActions is QList of QActions */
m_contextActions.append(actionRefreshMediaList);
dockPage();
}
MediaList::~MediaList()
{
}
/*
* The main meat of the class!! The function that querries the director and
* creates the widgets with appropriate values.
*/
void MediaList::populateTree()
{
QTreeWidgetItem *mediatreeitem, *pooltreeitem, *topItem;
if (!m_console->preventInUseConnect())
return;
QStringList headerlist = (QStringList()
<< "Volume Name" << "Id" << "Status" << "Enabled" << "Bytes" << "Files"
<< "Jobs" << "Retention" << "Media Type" << "Slot" << "Use Duration"
<< "Max Jobs" << "Max Files" << "Max Bytes" << "Recycle" << "Enabled"
<< "RecyclePool" << "Last Written");
int statusIndex = headerlist.indexOf("Status");
m_checkcurwidget = false;
mp_treeWidget->clear();
m_checkcurwidget = true;
mp_treeWidget->setColumnCount(headerlist.count());
topItem = new QTreeWidgetItem(mp_treeWidget);
topItem->setText(0, "Pools");
topItem->setData(0, Qt::UserRole, 0);
topItem->setExpanded(true);
mp_treeWidget->setHeaderLabels(headerlist);
QString query;
foreach (QString pool_listItem, m_console->pool_list) {
pooltreeitem = new QTreeWidgetItem(topItem);
pooltreeitem->setText(0, pool_listItem);
pooltreeitem->setData(0, Qt::UserRole, 1);
pooltreeitem->setExpanded(true);
query = "SELECT Media.VolumeName AS Media, "
" Media.MediaId AS Id, Media.VolStatus AS VolStatus,"
" Media.Enabled AS Enabled, Media.VolBytes AS Bytes,"
" Media.VolFiles AS FileCount, Media.VolJobs AS JobCount,"
" Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType,"
" Media.Slot AS Slot, Media.VolUseDuration AS UseDuration,"
" Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles,"
" Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle,"
" Media.Enabled AS enabled, Pol.Name AS RecyclePool,"
" Media.LastWritten AS LastWritten"
" FROM Media"
" LEFT OUTER JOIN Pool ON (Media.PoolId=Pool.PoolId)"
" LEFT OUTER JOIN Pool AS Pol ON (Media.recyclepoolid=Pol.PoolId)"
" WHERE";
query += " Pool.Name='" + pool_listItem + "'";
query += " ORDER BY Media";
if (mainWin->m_sqlDebug) {
Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data());
}
QStringList results;
if (m_console->sql_cmd(query, results)) {
QString field;
QStringList fieldlist;
/* Iterate through the lines of results. */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
int index = 0;
mediatreeitem = new QTreeWidgetItem(pooltreeitem);
/* Iterate through fields in the record */
foreach (field, fieldlist) {
field = field.trimmed(); /* strip leading & trailing spaces */
if (field != "") {
mediatreeitem->setData(index, Qt::UserRole, 2);
mediatreeitem->setData(index, Qt::UserRole, 2);
mediatreeitem->setText(index, field);
if (index == statusIndex) {
setStatusColor(mediatreeitem, field, index);
}
}
index++;
} /* foreach field */
} /* foreach resultline */
} /* if results from query */
} /* foreach pool_listItem */
/* Resize the columns */
for(int cnter=0; cnter<headerlist.count(); cnter++) {
mp_treeWidget->resizeColumnToContents(cnter);
}
}
void MediaList::setStatusColor(QTreeWidgetItem *item, QString &field, int &index)
{
if (field == "Append" ) {
item->setBackground(index, Qt::green);
} else if (field == "Error") {
item->setBackground(index, Qt::red);
} else if ((field == "Used") || ("Full")){
item->setBackground(index, Qt::yellow);
}
}
/*
* Called from the signal of the context sensitive menu!
*/
void MediaList::editVolume()
{
MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId);
connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree()));
}
/*
* Called from the signal of the context sensitive menu!
*/
void MediaList::showJobs()
{
QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem);
}
/*
* When the treeWidgetItem in the page selector tree is singleclicked, Make sure
* The tree has been populated.
*/
void MediaList::PgSeltreeWidgetClicked()
{
if (!m_populated) {
populateTree();
createContextMenu();
m_populated=true;
}
}
/*
* Added to set the context menu policy based on currently active treeWidgetItem
* signaled by currentItemChanged
*/
void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem )
{
/* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
if (m_checkcurwidget) {
/* The Previous item */
if (previouswidgetitem) { /* avoid a segfault if first time */
foreach(QAction* mediaAction, mp_treeWidget->actions()) {
mp_treeWidget->removeAction(mediaAction);
}
}
int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt();
m_currentVolumeName=currentwidgetitem->text(0);
mp_treeWidget->addAction(actionRefreshMediaList);
if (treedepth == 2){
m_currentVolumeId=currentwidgetitem->text(1);
mp_treeWidget->addAction(actionEditVolume);
mp_treeWidget->addAction(actionListJobsOnVolume);
mp_treeWidget->addAction(actionDeleteVolume);
mp_treeWidget->addAction(actionPruneVolume);
mp_treeWidget->addAction(actionPurgeVolume);
mp_treeWidget->addAction(actionRelabelVolume);
mp_treeWidget->addAction(actionVolumeFromPool);
} else if (treedepth == 1) {
mp_treeWidget->addAction(actionAllVolumesFromPool);
}
}
}
/*
* Setup a context menu
* Made separate from populate so that it would not create context menu over and
* over as the tree is repopulated.
*/
void MediaList::createContextMenu()
{
mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume()));
connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs()));
connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume()));
connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume()));
connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume()));
connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume()));
connect(mp_treeWidget, SIGNAL(
currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
/* connect to the action specific to this pages class */
connect(actionRefreshMediaList, SIGNAL(triggered()), this,
SLOT(populateTree()));
connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool()));
connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool()));
}
/*
* Virtual function which is called when this page is visible on the stack
*/
void MediaList::currentStackItem()
{
if(!m_populated) {
populateTree();
/* Create the context menu for the medialist tree */
createContextMenu();
m_populated=true;
}
}
/*
* Called from the signal of the context sensitive menu to delete a volume!
*/
void MediaList::deleteVolume()
{
if (QMessageBox::warning(this, tr("Bat"),
tr("Are you sure you want to delete?? !!!.\n"
"This delete command is used to delete a Volume record and all associated catalog"
" records that were created. This command operates only on the Catalog"
" database and has no effect on the actual data written to a Volume. This"
" command can be dangerous and we strongly recommend that you do not use"
" it unless you know what you are doing. All Jobs and all associated"
" records (File and JobMedia) will be deleted from the catalog."
"Press OK to proceed with delete operation.?"),
QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Cancel) { return; }
QString cmd("delete volume=");
cmd += m_currentVolumeName;
consoleCommand(cmd);
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::purgeVolume()
{
if (QMessageBox::warning(this, tr("Bat"),
tr("Are you sure you want to purge ?? !!!.\n"
"The Purge command will delete associated Catalog database records from Jobs and"
" Volumes without considering the retention period. Purge works only on the"
" Catalog database and does not affect data written to Volumes. This command can"
" be dangerous because you can delete catalog records associated with current"
" backups of files, and we recommend that you do not use it unless you know what"
" you are doing.\n"
"Press OK to proceed with the purge operation?"),
QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Cancel) { return; }
QString cmd("purge volume=");
cmd += m_currentVolumeName;
consoleCommand(cmd);
populateTree();
}
/*
* Called from the signal of the context sensitive menu to prune!
*/
void MediaList::pruneVolume()
{
new prunePage(m_currentVolumeName, "");
}
/*
* Called from the signal of the context sensitive menu to relabel!
*/
void MediaList::relabelVolume()
{
setConsoleCurrent();
new relabelDialog(m_console, m_currentVolumeName);
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::allVolumesFromPool()
{
QString cmd = "update volume AllFromPool=" + m_currentVolumeName;
consoleCommand(cmd);
populateTree();
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::volumeFromPool()
{
QTreeWidgetItem *currentItem = mp_treeWidget->currentItem();
QTreeWidgetItem *parent = currentItem->parent();
QString pool = parent->text(0);
QString cmd;
cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool;
consoleCommand(cmd);
populateTree();
}
<commit_msg>ebl small SQL fix for mysql (recyclepoolid => RecyclePoolId)<commit_after>/*
Bacula® - The Network Backup Solution
Copyright (C) 2000-2007 Free Software Foundation Europe e.V.
The main author of Bacula is Kern Sibbald, with contributions from
many others, a complete list can be found in the file AUTHORS.
This program is Free Software; you can redistribute it and/or
modify it under the terms of version two of the GNU General Public
License as published by the Free Software Foundation and included
in the file LICENSE.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
Bacula® is a registered trademark of John Walker.
The licensor of Bacula is the Free Software Foundation Europe
(FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
Switzerland, email:ftf@fsfeurope.org.
*/
/*
* Version $Id$
*
* MediaList Class
*
* Dirk Bartley, March 2007
*
*/
#include <QAbstractEventDispatcher>
#include <QMenu>
#include "bat.h"
#include "medialist.h"
#include "mediaedit/mediaedit.h"
#include "joblist/joblist.h"
#include "relabel/relabel.h"
#include "run/run.h"
MediaList::MediaList()
{
setupUi(this);
m_name = "Media";
pgInitialize();
QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png")));
/* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */
m_populated = false;
m_checkcurwidget = true;
m_closeable = false;
/* add context sensitive menu items specific to this classto the page
* selector tree. m_contextActions is QList of QActions */
m_contextActions.append(actionRefreshMediaList);
dockPage();
}
MediaList::~MediaList()
{
}
/*
* The main meat of the class!! The function that querries the director and
* creates the widgets with appropriate values.
*/
void MediaList::populateTree()
{
QTreeWidgetItem *mediatreeitem, *pooltreeitem, *topItem;
if (!m_console->preventInUseConnect())
return;
QStringList headerlist = (QStringList()
<< "Volume Name" << "Id" << "Status" << "Enabled" << "Bytes" << "Files"
<< "Jobs" << "Retention" << "Media Type" << "Slot" << "Use Duration"
<< "Max Jobs" << "Max Files" << "Max Bytes" << "Recycle" << "Enabled"
<< "RecyclePool" << "Last Written");
int statusIndex = headerlist.indexOf("Status");
m_checkcurwidget = false;
mp_treeWidget->clear();
m_checkcurwidget = true;
mp_treeWidget->setColumnCount(headerlist.count());
topItem = new QTreeWidgetItem(mp_treeWidget);
topItem->setText(0, "Pools");
topItem->setData(0, Qt::UserRole, 0);
topItem->setExpanded(true);
mp_treeWidget->setHeaderLabels(headerlist);
QString query;
foreach (QString pool_listItem, m_console->pool_list) {
pooltreeitem = new QTreeWidgetItem(topItem);
pooltreeitem->setText(0, pool_listItem);
pooltreeitem->setData(0, Qt::UserRole, 1);
pooltreeitem->setExpanded(true);
query = "SELECT Media.VolumeName AS Media, "
" Media.MediaId AS Id, Media.VolStatus AS VolStatus,"
" Media.Enabled AS Enabled, Media.VolBytes AS Bytes,"
" Media.VolFiles AS FileCount, Media.VolJobs AS JobCount,"
" Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType,"
" Media.Slot AS Slot, Media.VolUseDuration AS UseDuration,"
" Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles,"
" Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle,"
" Media.Enabled AS enabled, Pol.Name AS RecyclePool,"
" Media.LastWritten AS LastWritten"
" FROM Media"
" LEFT OUTER JOIN Pool ON (Media.PoolId=Pool.PoolId)"
" LEFT OUTER JOIN Pool AS Pol ON (Media.RecyclePoolId=Pol.PoolId)"
" WHERE";
query += " Pool.Name='" + pool_listItem + "'";
query += " ORDER BY Media";
if (mainWin->m_sqlDebug) {
Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data());
}
QStringList results;
if (m_console->sql_cmd(query, results)) {
QString field;
QStringList fieldlist;
/* Iterate through the lines of results. */
foreach (QString resultline, results) {
fieldlist = resultline.split("\t");
int index = 0;
mediatreeitem = new QTreeWidgetItem(pooltreeitem);
/* Iterate through fields in the record */
foreach (field, fieldlist) {
field = field.trimmed(); /* strip leading & trailing spaces */
if (field != "") {
mediatreeitem->setData(index, Qt::UserRole, 2);
mediatreeitem->setData(index, Qt::UserRole, 2);
mediatreeitem->setText(index, field);
if (index == statusIndex) {
setStatusColor(mediatreeitem, field, index);
}
}
index++;
} /* foreach field */
} /* foreach resultline */
} /* if results from query */
} /* foreach pool_listItem */
/* Resize the columns */
for(int cnter=0; cnter<headerlist.count(); cnter++) {
mp_treeWidget->resizeColumnToContents(cnter);
}
}
void MediaList::setStatusColor(QTreeWidgetItem *item, QString &field, int &index)
{
if (field == "Append" ) {
item->setBackground(index, Qt::green);
} else if (field == "Error") {
item->setBackground(index, Qt::red);
} else if ((field == "Used") || ("Full")){
item->setBackground(index, Qt::yellow);
}
}
/*
* Called from the signal of the context sensitive menu!
*/
void MediaList::editVolume()
{
MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId);
connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree()));
}
/*
* Called from the signal of the context sensitive menu!
*/
void MediaList::showJobs()
{
QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem);
}
/*
* When the treeWidgetItem in the page selector tree is singleclicked, Make sure
* The tree has been populated.
*/
void MediaList::PgSeltreeWidgetClicked()
{
if (!m_populated) {
populateTree();
createContextMenu();
m_populated=true;
}
}
/*
* Added to set the context menu policy based on currently active treeWidgetItem
* signaled by currentItemChanged
*/
void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem )
{
/* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
if (m_checkcurwidget) {
/* The Previous item */
if (previouswidgetitem) { /* avoid a segfault if first time */
foreach(QAction* mediaAction, mp_treeWidget->actions()) {
mp_treeWidget->removeAction(mediaAction);
}
}
int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt();
m_currentVolumeName=currentwidgetitem->text(0);
mp_treeWidget->addAction(actionRefreshMediaList);
if (treedepth == 2){
m_currentVolumeId=currentwidgetitem->text(1);
mp_treeWidget->addAction(actionEditVolume);
mp_treeWidget->addAction(actionListJobsOnVolume);
mp_treeWidget->addAction(actionDeleteVolume);
mp_treeWidget->addAction(actionPruneVolume);
mp_treeWidget->addAction(actionPurgeVolume);
mp_treeWidget->addAction(actionRelabelVolume);
mp_treeWidget->addAction(actionVolumeFromPool);
} else if (treedepth == 1) {
mp_treeWidget->addAction(actionAllVolumesFromPool);
}
}
}
/*
* Setup a context menu
* Made separate from populate so that it would not create context menu over and
* over as the tree is repopulated.
*/
void MediaList::createContextMenu()
{
mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume()));
connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs()));
connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume()));
connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume()));
connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume()));
connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume()));
connect(mp_treeWidget, SIGNAL(
currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
/* connect to the action specific to this pages class */
connect(actionRefreshMediaList, SIGNAL(triggered()), this,
SLOT(populateTree()));
connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool()));
connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool()));
}
/*
* Virtual function which is called when this page is visible on the stack
*/
void MediaList::currentStackItem()
{
if(!m_populated) {
populateTree();
/* Create the context menu for the medialist tree */
createContextMenu();
m_populated=true;
}
}
/*
* Called from the signal of the context sensitive menu to delete a volume!
*/
void MediaList::deleteVolume()
{
if (QMessageBox::warning(this, tr("Bat"),
tr("Are you sure you want to delete?? !!!.\n"
"This delete command is used to delete a Volume record and all associated catalog"
" records that were created. This command operates only on the Catalog"
" database and has no effect on the actual data written to a Volume. This"
" command can be dangerous and we strongly recommend that you do not use"
" it unless you know what you are doing. All Jobs and all associated"
" records (File and JobMedia) will be deleted from the catalog."
"Press OK to proceed with delete operation.?"),
QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Cancel) { return; }
QString cmd("delete volume=");
cmd += m_currentVolumeName;
consoleCommand(cmd);
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::purgeVolume()
{
if (QMessageBox::warning(this, tr("Bat"),
tr("Are you sure you want to purge ?? !!!.\n"
"The Purge command will delete associated Catalog database records from Jobs and"
" Volumes without considering the retention period. Purge works only on the"
" Catalog database and does not affect data written to Volumes. This command can"
" be dangerous because you can delete catalog records associated with current"
" backups of files, and we recommend that you do not use it unless you know what"
" you are doing.\n"
"Press OK to proceed with the purge operation?"),
QMessageBox::Ok | QMessageBox::Cancel)
== QMessageBox::Cancel) { return; }
QString cmd("purge volume=");
cmd += m_currentVolumeName;
consoleCommand(cmd);
populateTree();
}
/*
* Called from the signal of the context sensitive menu to prune!
*/
void MediaList::pruneVolume()
{
new prunePage(m_currentVolumeName, "");
}
/*
* Called from the signal of the context sensitive menu to relabel!
*/
void MediaList::relabelVolume()
{
setConsoleCurrent();
new relabelDialog(m_console, m_currentVolumeName);
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::allVolumesFromPool()
{
QString cmd = "update volume AllFromPool=" + m_currentVolumeName;
consoleCommand(cmd);
populateTree();
}
/*
* Called from the signal of the context sensitive menu to purge!
*/
void MediaList::volumeFromPool()
{
QTreeWidgetItem *currentItem = mp_treeWidget->currentItem();
QTreeWidgetItem *parent = currentItem->parent();
QString pool = parent->text(0);
QString cmd;
cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool;
consoleCommand(cmd);
populateTree();
}
<|endoftext|> |
<commit_before>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* The BoostRingBuffer class template.
* @see ringbuffer/ringbuffer.hpp
* @see ringbuffer/ringbuffer_pa.hpp
*/
#ifndef PS_RINGBUFFER_BOOST_HPP
#define PS_RINGBUFFER_BOOST_HPP
#include <boost/circular_buffer.hpp>
#include "ringbuffer.hpp"
/**
* Implementation of RingBuffer using the Boost circular buffer.
*
* This is currently experimental and has known audio glitches when used.
* Here be undiscovered bugs.
*/
template <typename T1, typename T2, int P>
class BoostRingBuffer : public RingBuffer<T1, T2> {
public:
/**
* Constructs a BoostRingBuffer.
* @param size The size of one element in the ring buffer.
*/
BoostRingBuffer(int size)
{
this->rb = new boost::circular_buffer<char>((1 << P) * size);
this->size = size;
}
/**
* Destructs a BoostRingBuffer.
*/
~BoostRingBuffer()
{
assert(this->rb != nullptr);
delete this->rb;
}
T2 WriteCapacity() const override
{
return static_cast<T2>(this->rb->reserve() / this->size);
}
T2 ReadCapacity() const override
{
return static_cast<T2>(this->rb->size() / this->size);
}
T2 Write(T1 *start, T2 count) override
{
return OnBuffer(start, count,
[this](T1 *e) { this->rb->push_back(e); });
}
T2 Read(T1 *start, T2 count) override
{
return OnBuffer(start, count, [this](T1 *e) {
*e = this->rb->front();
this->rb->pop_front();
});
}
void Flush() override
{
this->rb->clear();
}
private:
boost::circular_buffer<T1> *rb; ///< The internal Boost ring buffer.
int size; ///< The size of one sample, in bytes.
/**
* Transfers between this ring buffer and an external array buffer.
* @param start The start of the array buffer.
* @param count The number of samples in the array buffer.
* @param f A function to perform on each position in the array
* buffer.
* @return The number of samples affected in the array buffer.
*/
T2 OnBuffer(T1 *start, T2 count, std::function<void(T1 *)> f)
{
T2 i;
for (i = 0; i < count * this->size; i++) {
f(start + i);
}
return (i + 1) / this->size;
}
};
#endif // PS_RINGBUFFER_BOOST
<commit_msg>Fix and tidy up BoostRingBuffer.<commit_after>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* The BoostRingBuffer class template.
* @see ringbuffer/ringbuffer.hpp
* @see ringbuffer/ringbuffer_pa.hpp
*/
#ifndef PS_RINGBUFFER_BOOST_HPP
#define PS_RINGBUFFER_BOOST_HPP
#include <boost/circular_buffer.hpp>
#include "ringbuffer.hpp"
/**
* Implementation of RingBuffer using the Boost circular buffer.
*
* This is currently experimental and has known audio glitches when used.
* Here be undiscovered bugs.
*/
template <typename T1, typename T2, int P>
class BoostRingBuffer : public RingBuffer<T1, T2> {
public:
using InternalBuffer = boost::circular_buffer<T1>;
using InternalBufferPtr = std::unique_ptr<InternalBuffer>;
/**
* Constructs a BoostRingBuffer.
* @param size The size of one element in the ring buffer.
*/
BoostRingBuffer(int size)
{
this->rb = InternalBufferPtr(new InternalBuffer((1 << P) * size));
this->size = size;
}
T2 WriteCapacity() const override
{
return static_cast<T2>(this->rb->reserve() / this->size);
}
T2 ReadCapacity() const override
{
return static_cast<T2>(this->rb->size() / this->size);
}
T2 Write(T1 *start, T2 count) override
{
return OnBuffer(start, count,
[this](T1 *e) { this->rb->push_back(*e); });
}
T2 Read(T1 *start, T2 count) override
{
return OnBuffer(start, count, [this](T1 *e) {
*e = this->rb->front();
this->rb->pop_front();
});
}
void Flush() override
{
this->rb->clear();
}
private:
InternalBufferPtr rb; ///< The internal Boost ring buffer.
int size; ///< The size of one sample, in bytes.
/**
* Transfers between this ring buffer and an external array buffer.
* @param start The start of the array buffer.
* @param count The number of samples in the array buffer.
* @param f A function to perform on each position in the array
* buffer.
* @return The number of samples affected in the array buffer.
*/
T2 OnBuffer(T1 *start, T2 count, std::function<void(T1 *)> f)
{
T1 *end = start + (count * this->size);
for (T1 *ptr = start; ptr < end; ptr++) {
f(ptr);
}
return count;
}
};
#endif // PS_RINGBUFFER_BOOST
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*/
#include "sim/faults.hh"
#include "cpu/exec_context.hh"
#include "cpu/base.hh"
#if !FULL_SYSTEM
void FaultBase::invoke(ExecContext * xc)
{
fatal("fault (%s) detected @ PC 0x%08p", name(), xc->readPC());
}
#else
void FaultBase::invoke(ExecContext * xc)
{
DPRINTF(Fault, "Fault %s at PC: %#x\n", name(), xc->regs.pc);
xc->cpu->recordEvent(csprintf("Fault %s", name()));
assert(!xc->misspeculating());
}
#endif
<commit_msg>Avoid accessing objects directly within the XC.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*/
#include "sim/faults.hh"
#include "cpu/exec_context.hh"
#include "cpu/base.hh"
#if !FULL_SYSTEM
void FaultBase::invoke(ExecContext * xc)
{
fatal("fault (%s) detected @ PC 0x%08p", name(), xc->readPC());
}
#else
void FaultBase::invoke(ExecContext * xc)
{
DPRINTF(Fault, "Fault %s at PC: %#x\n", name(), xc->readPC());
xc->getCpuPtr()->recordEvent(csprintf("Fault %s", name()));
assert(!xc->misspeculating());
}
#endif
<|endoftext|> |
<commit_before>/* Copyright 2016 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// portability wrapper over NUMA system interfaces
// NOTE: this is nowhere near a full libnuma-style interface - it's just the
// calls that Realm's NUMA module needs
#include "numasysif.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <map>
#ifdef __linux__
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/mempolicy.h>
#include <dirent.h>
#include <sched.h>
#include <ctype.h>
#include <sys/mman.h>
namespace {
long get_mempolicy(int *policy, const unsigned long *nmask,
unsigned long maxnode, void *addr, int flags)
{
return syscall(__NR_get_mempolicy, policy, nmask,
maxnode, addr, flags);
}
long mbind(void *start, unsigned long len, int mode,
const unsigned long *nmask, unsigned long maxnode, unsigned flags)
{
return syscall(__NR_mbind, (long)start, len, mode, (long)nmask,
maxnode, flags);
}
long set_mempolicy(int mode, const unsigned long *nmask,
unsigned long maxnode)
{
return syscall(__NR_set_mempolicy, mode, nmask, maxnode);
}
};
#endif
namespace Realm {
// as soon as we get more than one real version of these, split them out into
// separate files
// is NUMA support available in the system?
bool numasysif_numa_available(void)
{
#ifdef __linux__
int policy;
unsigned long nmask;
int ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED);
if((ret != 0) || (nmask == 0)) {
fprintf(stderr, "get_mempolicy() returned: ret=%d nmask=%08lx\n", ret, nmask);
return false;
}
//printf("policy=%d nmask=%08lx\n", policy, nmask);
//ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0);
//printf("ret=%d policy=%d nmask=%08lx\n", ret, policy, nmask);
return true;
#else
return false;
#endif
}
// return info on the memory and cpu in each NUMA node
// default is to restrict to only those nodes enabled in the current affinity mask
bool numasysif_get_mem_info(std::vector<NumaNodeMemInfo>& info,
bool only_available /*= true*/)
{
#ifdef __linux__
int policy = -1;
unsigned long nmask = 0;
int ret = -1;
if(only_available) {
// first, ask for the default policy for the thread to detect binding via
// numactl, mpirun, etc.
ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0);
}
if((ret != 0) || (policy != MPOL_BIND) || (nmask == 0)) {
// not a reasonable-looking bound state, so ask for all nodes
ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED);
if((ret != 0) || (nmask == 0)) {
// still no good
return false;
}
}
// for each bit set in the mask, try to query the free memory
for(int i = 0; i < 8*(int)sizeof(nmask); i++)
if(((nmask >> i) & 1) != 0) {
// free information comes from /sys...
char fname[80];
sprintf(fname, "/sys/devices/system/node/node%d/meminfo", i);
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno));
continue;
}
char line[256];
while(fgets(line, 256, f)) {
const char *s = strstr(line, "MemFree");
if(!s) continue;
const char *endptr;
errno = 0;
long long sz = strtoll(s+9, (char **)&endptr, 10);
if((errno != 0) || strcmp(endptr, " kB\n")) {
fprintf(stderr, "ill-formed line: '%s' '%s'\n", s, endptr);
continue;
}
// success - add this to the list and stop reading
NumaNodeMemInfo mi;
mi.node_id = i;
mi.bytes_available = (sz << 10);
info.push_back(mi);
break;
}
// if we get all the way through the file without finding the size,
// we just don't add anything to the info
fclose(f);
}
// as long as we got at least one valid node, assume we're successful
return !info.empty();
#else
return false;
#endif
}
bool numasysif_get_cpu_info(std::vector<NumaNodeCpuInfo>& info,
bool only_available /*= true*/)
{
#ifdef __linux__
// if we're restricting to what's been made available, find what's been
// made available
cpu_set_t avail_cpus;
if(only_available) {
int ret = sched_getaffinity(0, sizeof(avail_cpus), &avail_cpus);
if(ret != 0) {
fprintf(stderr, "sched_getaffinity failed: %s\n", strerror(errno));
return false;
}
} else
CPU_ZERO(&avail_cpus);
// now enumerate cpus via /sys and determine which nodes they belong to
std::map<int, int> cpu_counts;
DIR *cpudir = opendir("/sys/devices/system/cpu");
if(!cpudir) {
fprintf(stderr, "couldn't read /sys/devices/system/cpu: %s\n", strerror(errno));
return false;
}
struct dirent *de;
while((de = readdir(cpudir)) != 0)
if(!strncmp(de->d_name, "cpu", 3)) {
int cpu_index = atoi(de->d_name + 3);
if(only_available && !CPU_ISSET(cpu_index, &avail_cpus))
continue;
// find the node symlink to determine the node
char path2[256];
sprintf(path2, "/sys/devices/system/cpu/%s", de->d_name);
DIR *d2 = opendir(path2);
if(!d2) {
fprintf(stderr, "couldn't read '%s': %s\n", path2, strerror(errno));
continue;
}
struct dirent *de2;
while((de2 = readdir(d2)) != 0)
if(!strncmp(de2->d_name, "node", 4)) {
int node_index = atoi(de2->d_name + 4);
cpu_counts[node_index]++;
break;
}
closedir(d2);
}
// any matches is "success"
if(!cpu_counts.empty()) {
for(std::map<int,int>::const_iterator it = cpu_counts.begin();
it != cpu_counts.end();
++it) {
NumaNodeCpuInfo ci;
ci.node_id = it->first;
ci.cores_available = it->second;
info.push_back(ci);
}
return true;
} else
return false;
#else
return false;
#endif
}
// return the "distance" between two nodes - try to normalize to Linux's model of
// 10 being the same node and the cost for other nodes increasing by roughly 10
// per hop
int numasysif_get_distance(int node1, int node2)
{
#ifdef __linux__
static std::map<int, std::vector<int> > saved_distances;
std::map<int, std::vector<int> >::iterator it = saved_distances.find(node1);
if(it == saved_distances.end()) {
// not one we've already looked up, so do it now
// if we break out early, we'll end up with an empty vector, which means
// we'll return -1 for all future queries
std::vector<int>& v = saved_distances[node1];
char fname[256];
sprintf(fname, "/sys/devices/system/node/node%d/distance", node1);
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno));
saved_distances[node1].clear();
return -1;
}
char line[256];
if(fgets(line, 256, f)) {
char *p = line;
while(isdigit(*p)) {
errno = 0;
int d = strtol(p, &p, 10);
if(errno != 0) break;
v.push_back(d);
while(isspace(*p)) p++;
}
}
fclose(f);
if((node2 >= 0) && (node2 < (int)v.size()))
return v[node2];
else
return -1;
} else {
const std::vector<int>& v = it->second;
if((node2 >= 0) && (node2 < (int)v.size()))
return v[node2];
else
return -1;
}
#else
return -1;
#endif
}
// allocate memory on a given NUMA node - pin if requested
void *numasysif_alloc_mem(int node, size_t bytes, bool pin)
{
#ifdef __linux__
// get memory from mmap
// TODO: hugetlbfs, if possible
void *base = mmap(0,
bytes,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if(!base) return 0;
// use the bind call for the rest
if(numasysif_bind_mem(node, base, bytes, pin))
return base;
// if not, clean up and return failure
numasysif_free_mem(node, base, bytes);
return 0;
#else
return 0;
#endif
}
// free memory allocated on a given NUMA node
bool numasysif_free_mem(int node, void *base, size_t bytes)
{
#ifdef __linux__
int ret = munmap(base, bytes);
return(ret == 0);
#else
return false;
#endif
}
// bind already-allocated memory to a given node - pin if requested
// may fail if the memory has already been touched
bool numasysif_bind_mem(int node, void *base, size_t bytes, bool pin)
{
#ifdef __linux__
int policy = MPOL_BIND;
unsigned long nmask = (1UL << node);
int ret = mbind(base, bytes,
policy, &nmask, 8*sizeof(nmask),
MPOL_MF_STRICT | MPOL_MF_MOVE);
if(ret != 0) {
fprintf(stderr, "failed to bind memory for node %d: %s\n", node, strerror(errno));
return false;
}
// attempt to pin the memory if requested
if(pin) {
int ret = mlock(base, bytes);
if(ret != 0) {
fprintf(stderr, "mlock failed for memory on node %d: %s\n", node, strerror(errno));
return false;
}
}
return true;
#else
return false;
#endif
}
};
<commit_msg>realm: commenting out an unused function for now<commit_after>/* Copyright 2016 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// portability wrapper over NUMA system interfaces
// NOTE: this is nowhere near a full libnuma-style interface - it's just the
// calls that Realm's NUMA module needs
#include "numasysif.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <map>
#ifdef __linux__
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/mempolicy.h>
#include <dirent.h>
#include <sched.h>
#include <ctype.h>
#include <sys/mman.h>
namespace {
long get_mempolicy(int *policy, const unsigned long *nmask,
unsigned long maxnode, void *addr, int flags)
{
return syscall(__NR_get_mempolicy, policy, nmask,
maxnode, addr, flags);
}
long mbind(void *start, unsigned long len, int mode,
const unsigned long *nmask, unsigned long maxnode, unsigned flags)
{
return syscall(__NR_mbind, (long)start, len, mode, (long)nmask,
maxnode, flags);
}
#if 0
long set_mempolicy(int mode, const unsigned long *nmask,
unsigned long maxnode)
{
return syscall(__NR_set_mempolicy, mode, nmask, maxnode);
}
#endif
};
#endif
namespace Realm {
// as soon as we get more than one real version of these, split them out into
// separate files
// is NUMA support available in the system?
bool numasysif_numa_available(void)
{
#ifdef __linux__
int policy;
unsigned long nmask;
int ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED);
if((ret != 0) || (nmask == 0)) {
fprintf(stderr, "get_mempolicy() returned: ret=%d nmask=%08lx\n", ret, nmask);
return false;
}
//printf("policy=%d nmask=%08lx\n", policy, nmask);
//ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0);
//printf("ret=%d policy=%d nmask=%08lx\n", ret, policy, nmask);
return true;
#else
return false;
#endif
}
// return info on the memory and cpu in each NUMA node
// default is to restrict to only those nodes enabled in the current affinity mask
bool numasysif_get_mem_info(std::vector<NumaNodeMemInfo>& info,
bool only_available /*= true*/)
{
#ifdef __linux__
int policy = -1;
unsigned long nmask = 0;
int ret = -1;
if(only_available) {
// first, ask for the default policy for the thread to detect binding via
// numactl, mpirun, etc.
ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, 0);
}
if((ret != 0) || (policy != MPOL_BIND) || (nmask == 0)) {
// not a reasonable-looking bound state, so ask for all nodes
ret = get_mempolicy(&policy, &nmask, 8*sizeof(nmask), 0, MPOL_F_MEMS_ALLOWED);
if((ret != 0) || (nmask == 0)) {
// still no good
return false;
}
}
// for each bit set in the mask, try to query the free memory
for(int i = 0; i < 8*(int)sizeof(nmask); i++)
if(((nmask >> i) & 1) != 0) {
// free information comes from /sys...
char fname[80];
sprintf(fname, "/sys/devices/system/node/node%d/meminfo", i);
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno));
continue;
}
char line[256];
while(fgets(line, 256, f)) {
const char *s = strstr(line, "MemFree");
if(!s) continue;
const char *endptr;
errno = 0;
long long sz = strtoll(s+9, (char **)&endptr, 10);
if((errno != 0) || strcmp(endptr, " kB\n")) {
fprintf(stderr, "ill-formed line: '%s' '%s'\n", s, endptr);
continue;
}
// success - add this to the list and stop reading
NumaNodeMemInfo mi;
mi.node_id = i;
mi.bytes_available = (sz << 10);
info.push_back(mi);
break;
}
// if we get all the way through the file without finding the size,
// we just don't add anything to the info
fclose(f);
}
// as long as we got at least one valid node, assume we're successful
return !info.empty();
#else
return false;
#endif
}
bool numasysif_get_cpu_info(std::vector<NumaNodeCpuInfo>& info,
bool only_available /*= true*/)
{
#ifdef __linux__
// if we're restricting to what's been made available, find what's been
// made available
cpu_set_t avail_cpus;
if(only_available) {
int ret = sched_getaffinity(0, sizeof(avail_cpus), &avail_cpus);
if(ret != 0) {
fprintf(stderr, "sched_getaffinity failed: %s\n", strerror(errno));
return false;
}
} else
CPU_ZERO(&avail_cpus);
// now enumerate cpus via /sys and determine which nodes they belong to
std::map<int, int> cpu_counts;
DIR *cpudir = opendir("/sys/devices/system/cpu");
if(!cpudir) {
fprintf(stderr, "couldn't read /sys/devices/system/cpu: %s\n", strerror(errno));
return false;
}
struct dirent *de;
while((de = readdir(cpudir)) != 0)
if(!strncmp(de->d_name, "cpu", 3)) {
int cpu_index = atoi(de->d_name + 3);
if(only_available && !CPU_ISSET(cpu_index, &avail_cpus))
continue;
// find the node symlink to determine the node
char path2[256];
sprintf(path2, "/sys/devices/system/cpu/%s", de->d_name);
DIR *d2 = opendir(path2);
if(!d2) {
fprintf(stderr, "couldn't read '%s': %s\n", path2, strerror(errno));
continue;
}
struct dirent *de2;
while((de2 = readdir(d2)) != 0)
if(!strncmp(de2->d_name, "node", 4)) {
int node_index = atoi(de2->d_name + 4);
cpu_counts[node_index]++;
break;
}
closedir(d2);
}
// any matches is "success"
if(!cpu_counts.empty()) {
for(std::map<int,int>::const_iterator it = cpu_counts.begin();
it != cpu_counts.end();
++it) {
NumaNodeCpuInfo ci;
ci.node_id = it->first;
ci.cores_available = it->second;
info.push_back(ci);
}
return true;
} else
return false;
#else
return false;
#endif
}
// return the "distance" between two nodes - try to normalize to Linux's model of
// 10 being the same node and the cost for other nodes increasing by roughly 10
// per hop
int numasysif_get_distance(int node1, int node2)
{
#ifdef __linux__
static std::map<int, std::vector<int> > saved_distances;
std::map<int, std::vector<int> >::iterator it = saved_distances.find(node1);
if(it == saved_distances.end()) {
// not one we've already looked up, so do it now
// if we break out early, we'll end up with an empty vector, which means
// we'll return -1 for all future queries
std::vector<int>& v = saved_distances[node1];
char fname[256];
sprintf(fname, "/sys/devices/system/node/node%d/distance", node1);
FILE *f = fopen(fname, "r");
if(!f) {
fprintf(stderr, "can't read '%s': %s\n", fname, strerror(errno));
saved_distances[node1].clear();
return -1;
}
char line[256];
if(fgets(line, 256, f)) {
char *p = line;
while(isdigit(*p)) {
errno = 0;
int d = strtol(p, &p, 10);
if(errno != 0) break;
v.push_back(d);
while(isspace(*p)) p++;
}
}
fclose(f);
if((node2 >= 0) && (node2 < (int)v.size()))
return v[node2];
else
return -1;
} else {
const std::vector<int>& v = it->second;
if((node2 >= 0) && (node2 < (int)v.size()))
return v[node2];
else
return -1;
}
#else
return -1;
#endif
}
// allocate memory on a given NUMA node - pin if requested
void *numasysif_alloc_mem(int node, size_t bytes, bool pin)
{
#ifdef __linux__
// get memory from mmap
// TODO: hugetlbfs, if possible
void *base = mmap(0,
bytes,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if(!base) return 0;
// use the bind call for the rest
if(numasysif_bind_mem(node, base, bytes, pin))
return base;
// if not, clean up and return failure
numasysif_free_mem(node, base, bytes);
return 0;
#else
return 0;
#endif
}
// free memory allocated on a given NUMA node
bool numasysif_free_mem(int node, void *base, size_t bytes)
{
#ifdef __linux__
int ret = munmap(base, bytes);
return(ret == 0);
#else
return false;
#endif
}
// bind already-allocated memory to a given node - pin if requested
// may fail if the memory has already been touched
bool numasysif_bind_mem(int node, void *base, size_t bytes, bool pin)
{
#ifdef __linux__
int policy = MPOL_BIND;
unsigned long nmask = (1UL << node);
int ret = mbind(base, bytes,
policy, &nmask, 8*sizeof(nmask),
MPOL_MF_STRICT | MPOL_MF_MOVE);
if(ret != 0) {
fprintf(stderr, "failed to bind memory for node %d: %s\n", node, strerror(errno));
return false;
}
// attempt to pin the memory if requested
if(pin) {
int ret = mlock(base, bytes);
if(ret != 0) {
fprintf(stderr, "mlock failed for memory on node %d: %s\n", node, strerror(errno));
return false;
}
}
return true;
#else
return false;
#endif
}
};
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "adjustment.hh"
#include "factory.hh"
namespace Rapicorn {
Adjustment::Adjustment() :
sig_value_changed (Aida::slot (*this, &Adjustment::value_changed)),
sig_range_changed (Aida::slot (*this, &Adjustment::range_changed))
{}
Adjustment::~Adjustment()
{}
double
Adjustment::flipped_value()
{
double v = value() - lower();
return upper() - page() - v;
}
void
Adjustment::flipped_value (double newval)
{
double l = lower();
double u = upper() - page();
newval = CLAMP (newval, l, u);
double v = newval - l;
value (u - v);
}
double
Adjustment::nvalue ()
{
double l = lower(), u = upper() - page(), ar = u - l;
return ar > 0 ? (value() - l) / ar : 0.0;
}
void
Adjustment::nvalue (double newval)
{
double l = lower(), u = upper() - page(), ar = u - l;
value (l + newval * ar);
}
double
Adjustment::flipped_nvalue ()
{
return 1.0 - nvalue();
}
void
Adjustment::flipped_nvalue (double newval)
{
nvalue (1.0 - newval);
}
void
Adjustment::value_changed()
{}
void
Adjustment::range_changed()
{}
double
Adjustment::abs_range ()
{
return fabs (upper() - page() - lower());
}
double
Adjustment::abs_length ()
{
double p = page();
double ar = fabs (upper() - lower());
return ar > 0 ? p / ar : 0.0;
}
bool
Adjustment::move_flipped (MoveType movet)
{
switch (movet)
{
case MOVE_PAGE_FORWARD: return move (MOVE_PAGE_BACKWARD);
case MOVE_STEP_FORWARD: return move (MOVE_STEP_BACKWARD);
case MOVE_STEP_BACKWARD: return move (MOVE_STEP_FORWARD);
case MOVE_PAGE_BACKWARD: return move (MOVE_PAGE_FORWARD);
case MOVE_NONE: ;
}
return false;
}
bool
Adjustment::move (MoveType move)
{
switch (move)
{
case MOVE_PAGE_FORWARD:
value (value() + page_increment());
return true;
case MOVE_STEP_FORWARD:
value (value() + step_increment());
return true;
case MOVE_STEP_BACKWARD:
value (value() - step_increment());
return true;
case MOVE_PAGE_BACKWARD:
value (value() - page_increment());
return true;
case MOVE_NONE: ;
}
return false;
}
String
Adjustment::string ()
{
String s = string_printf ("Adjustment(%g,[%f,%f],istep=%+f,pstep=%+f,page=%f%s)",
value(), lower(), upper(),
step_increment(), page_increment(), page(),
frozen() ? ",frozen" : "");
return s;
}
struct AdjustmentMemorizedState {
double value, lower, upper, step_increment, page_increment, page;
};
static DataKey<AdjustmentMemorizedState> memorized_state_key;
class AdjustmentSimpleImpl : public virtual Adjustment, public virtual DataListContainer {
double m_value, m_lower, m_upper, m_step_increment, m_page_increment, m_page;
uint m_freeze_count;
public:
AdjustmentSimpleImpl() :
m_value (0), m_lower (0), m_upper (100),
m_step_increment (1), m_page_increment (10), m_page (0),
m_freeze_count (0)
{}
/* value */
virtual double value () { return m_value; }
virtual void
value (double newval)
{
double old_value = m_value;
if (isnan (newval))
{
critical ("Adjustment::value(): invalid value: %g", newval);
newval = 0;
}
m_value = CLAMP (newval, m_lower, m_upper - m_page);
if (old_value != m_value && !m_freeze_count)
sig_value_changed.emit ();
}
/* range */
virtual bool frozen () const { return m_freeze_count > 0; }
virtual double lower () const { return m_lower; }
virtual void lower (double newval) { assert_return (m_freeze_count); m_lower = newval; }
virtual double upper () const { return m_upper; }
virtual void upper (double newval) { assert_return (m_freeze_count); m_upper = newval; }
virtual double step_increment () const { return m_step_increment; }
virtual void step_increment (double newval) { assert_return (m_freeze_count); m_step_increment = newval; }
virtual double page_increment () const { return m_page_increment; }
virtual void page_increment (double newval) { assert_return (m_freeze_count); m_page_increment = newval; }
virtual double page () const { return m_page; }
virtual void page (double newval) { assert_return (m_freeze_count); m_page = newval; }
virtual void
freeze ()
{
if (!m_freeze_count)
{
AdjustmentMemorizedState m;
m.value = m_value;
m.lower = m_lower;
m.upper = m_upper;
m.step_increment = m_step_increment;
m.page_increment = m_page_increment;
m.page = m_page;
set_data (&memorized_state_key, m);
}
m_freeze_count++;
}
virtual void
constrain ()
{
assert_return (m_freeze_count);
if (m_lower > m_upper)
m_lower = m_upper = (m_lower + m_upper) / 2;
m_page = CLAMP (m_page, 0, m_upper - m_lower);
m_page_increment = MAX (m_page_increment, 0);
if (m_page > 0)
m_page_increment = MIN (m_page_increment, m_page);
m_step_increment = MAX (0, m_step_increment);
if (m_page_increment > 0)
m_step_increment = MIN (m_step_increment, m_page_increment);
else if (m_page > 0)
m_step_increment = MIN (m_step_increment, m_page);
m_value = CLAMP (m_value, m_lower, m_upper - m_page);
}
virtual void
thaw ()
{
assert_return (m_freeze_count);
if (m_freeze_count == 1)
constrain();
m_freeze_count--;
if (!m_freeze_count)
{
AdjustmentMemorizedState m = swap_data (&memorized_state_key);
if (m.lower != m_lower || m.upper != m_upper || m.page != m_page ||
m.step_increment != m_step_increment || m.page_increment != m_page_increment)
sig_range_changed.emit();
if (m.value != m_value)
sig_value_changed.emit ();
}
}
};
Adjustment*
Adjustment::create (double value,
double lower,
double upper,
double step_increment,
double page_increment,
double page_size)
{
AdjustmentSimpleImpl *adj = new AdjustmentSimpleImpl();
adj->freeze();
adj->lower (lower);
adj->upper (upper);
adj->step_increment (step_increment);
adj->page_increment (page_increment);
adj->page (page_size);
adj->thaw();
return adj;
}
} // Rapicorn
<commit_msg>UI: adjustment member renames<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "adjustment.hh"
#include "factory.hh"
namespace Rapicorn {
Adjustment::Adjustment() :
sig_value_changed (Aida::slot (*this, &Adjustment::value_changed)),
sig_range_changed (Aida::slot (*this, &Adjustment::range_changed))
{}
Adjustment::~Adjustment()
{}
double
Adjustment::flipped_value()
{
double v = value() - lower();
return upper() - page() - v;
}
void
Adjustment::flipped_value (double newval)
{
double l = lower();
double u = upper() - page();
newval = CLAMP (newval, l, u);
double v = newval - l;
value (u - v);
}
double
Adjustment::nvalue ()
{
double l = lower(), u = upper() - page(), ar = u - l;
return ar > 0 ? (value() - l) / ar : 0.0;
}
void
Adjustment::nvalue (double newval)
{
double l = lower(), u = upper() - page(), ar = u - l;
value (l + newval * ar);
}
double
Adjustment::flipped_nvalue ()
{
return 1.0 - nvalue();
}
void
Adjustment::flipped_nvalue (double newval)
{
nvalue (1.0 - newval);
}
void
Adjustment::value_changed()
{}
void
Adjustment::range_changed()
{}
double
Adjustment::abs_range ()
{
return fabs (upper() - page() - lower());
}
double
Adjustment::abs_length ()
{
double p = page();
double ar = fabs (upper() - lower());
return ar > 0 ? p / ar : 0.0;
}
bool
Adjustment::move_flipped (MoveType movet)
{
switch (movet)
{
case MOVE_PAGE_FORWARD: return move (MOVE_PAGE_BACKWARD);
case MOVE_STEP_FORWARD: return move (MOVE_STEP_BACKWARD);
case MOVE_STEP_BACKWARD: return move (MOVE_STEP_FORWARD);
case MOVE_PAGE_BACKWARD: return move (MOVE_PAGE_FORWARD);
case MOVE_NONE: ;
}
return false;
}
bool
Adjustment::move (MoveType move)
{
switch (move)
{
case MOVE_PAGE_FORWARD:
value (value() + page_increment());
return true;
case MOVE_STEP_FORWARD:
value (value() + step_increment());
return true;
case MOVE_STEP_BACKWARD:
value (value() - step_increment());
return true;
case MOVE_PAGE_BACKWARD:
value (value() - page_increment());
return true;
case MOVE_NONE: ;
}
return false;
}
String
Adjustment::string ()
{
String s = string_printf ("Adjustment(%g,[%f,%f],istep=%+f,pstep=%+f,page=%f%s)",
value(), lower(), upper(),
step_increment(), page_increment(), page(),
frozen() ? ",frozen" : "");
return s;
}
struct AdjustmentMemorizedState {
double value, lower, upper, step_increment, page_increment, page;
};
static DataKey<AdjustmentMemorizedState> memorized_state_key;
class AdjustmentSimpleImpl : public virtual Adjustment, public virtual DataListContainer {
double value_, lower_, upper_, step_increment_, page_increment_, page_;
uint freeze_count_;
public:
AdjustmentSimpleImpl() :
value_ (0), lower_ (0), upper_ (100),
step_increment_ (1), page_increment_ (10), page_ (0),
freeze_count_ (0)
{}
/* value */
virtual double value () { return value_; }
virtual void
value (double newval)
{
double old_value = value_;
if (isnan (newval))
{
critical ("Adjustment::value(): invalid value: %g", newval);
newval = 0;
}
value_ = CLAMP (newval, lower_, upper_ - page_);
if (old_value != value_ && !freeze_count_)
sig_value_changed.emit ();
}
/* range */
virtual bool frozen () const { return freeze_count_ > 0; }
virtual double lower () const { return lower_; }
virtual void lower (double newval) { assert_return (freeze_count_); lower_ = newval; }
virtual double upper () const { return upper_; }
virtual void upper (double newval) { assert_return (freeze_count_); upper_ = newval; }
virtual double step_increment () const { return step_increment_; }
virtual void step_increment (double newval) { assert_return (freeze_count_); step_increment_ = newval; }
virtual double page_increment () const { return page_increment_; }
virtual void page_increment (double newval) { assert_return (freeze_count_); page_increment_ = newval; }
virtual double page () const { return page_; }
virtual void page (double newval) { assert_return (freeze_count_); page_ = newval; }
virtual void
freeze ()
{
if (!freeze_count_)
{
AdjustmentMemorizedState m;
m.value = value_;
m.lower = lower_;
m.upper = upper_;
m.step_increment = step_increment_;
m.page_increment = page_increment_;
m.page = page_;
set_data (&memorized_state_key, m);
}
freeze_count_++;
}
virtual void
constrain ()
{
assert_return (freeze_count_);
if (lower_ > upper_)
lower_ = upper_ = (lower_ + upper_) / 2;
page_ = CLAMP (page_, 0, upper_ - lower_);
page_increment_ = MAX (page_increment_, 0);
if (page_ > 0)
page_increment_ = MIN (page_increment_, page_);
step_increment_ = MAX (0, step_increment_);
if (page_increment_ > 0)
step_increment_ = MIN (step_increment_, page_increment_);
else if (page_ > 0)
step_increment_ = MIN (step_increment_, page_);
value_ = CLAMP (value_, lower_, upper_ - page_);
}
virtual void
thaw ()
{
assert_return (freeze_count_);
if (freeze_count_ == 1)
constrain();
freeze_count_--;
if (!freeze_count_)
{
AdjustmentMemorizedState m = swap_data (&memorized_state_key);
if (m.lower != lower_ || m.upper != upper_ || m.page != page_ ||
m.step_increment != step_increment_ || m.page_increment != page_increment_)
sig_range_changed.emit();
if (m.value != value_)
sig_value_changed.emit ();
}
}
};
Adjustment*
Adjustment::create (double value,
double lower,
double upper,
double step_increment,
double page_increment,
double page_size)
{
AdjustmentSimpleImpl *adj = new AdjustmentSimpleImpl();
adj->freeze();
adj->lower (lower);
adj->upper (upper);
adj->step_increment (step_increment);
adj->page_increment (page_increment);
adj->page (page_size);
adj->thaw();
return adj;
}
} // Rapicorn
<|endoftext|> |
<commit_before>#ifndef MIDDLEWARE_PARSLEY_HPP
#define MIDDLEWARE_PARSLEY_HPP
#include "json.hpp"
#include "middleware.hpp"
/**
* @brief A vegan way to parse JSON Content in a response
* @details TBC..
*
*/
class Parsley : public server::Middleware {
public:
virtual void process(
server::Request_ptr req,
server::Response_ptr res,
server::Next next
) override
{
if(!has_json(req)) {
printf("<Parsley> No JSON in header field.\n");
(*next)();
return;
}
// Request doesn't have JSON attribute
if(!req->has_attribute<Json>()) {
// create attribute
auto json = std::make_shared<Json>();
// access the document and parse the body
json->doc().Parse(req->get_body().c_str());
printf("<Parsley> Parsed JSON data.\n");
// add the json to the request
req->set_attribute(json);
}
(*next)();
}
private:
bool has_json(server::Request_ptr req) const {
auto c_type = http::header_fields::Entity::Content_Type;
return req->has_header(c_type)
&& (req->header_value(c_type) == "application/json");
}
};
#endif
<commit_msg>Moved rapidjson dependency to json.hpp<commit_after>#ifndef MIDDLEWARE_PARSLEY_HPP
#define MIDDLEWARE_PARSLEY_HPP
#include "json.hpp"
#include "middleware.hpp"
/**
* @brief A vegan way to parse JSON Content in a response
* @details TBC..
*
*/
class Parsley : public server::Middleware {
public:
virtual void process(
server::Request_ptr req,
server::Response_ptr res,
server::Next next
) override
{
using namespace json;
if(!has_json(req)) {
//printf("<Parsley> No JSON in header field.\n");
(*next)();
return;
}
// Request doesn't have JSON attribute
if(!req->has_attribute<JsonDoc>()) {
// create attribute
auto json = std::make_shared<JsonDoc>();
// access the document and parse the body
json->doc().Parse(req->get_body().c_str());
printf("<Parsley> Parsed JSON data.\n");
// add the json to the request
req->set_attribute(json);
}
(*next)();
}
private:
bool has_json(server::Request_ptr req) const {
auto c_type = http::header_fields::Entity::Content_Type;
return req->has_header(c_type)
&& (req->header_value(c_type) == "application/json");
}
};
#endif
<|endoftext|> |
<commit_before>#ifndef ITER_POWERSET_HPP_
#define ITER_POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include <cassert>
#include <memory>
#include <initializer_list>
#include <utility>
#include <iterator>
#include <type_traits>
namespace iter {
template <typename Container>
class Powersetter {
private:
Container container;
using CombinatorType =
decltype(combinations(std::declval<Container&>(), 0));
public:
Powersetter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<
std::input_iterator_tag, CombinatorType>
{
private:
std::remove_reference_t<Container> *container_p;
std::size_t set_size;
std::shared_ptr<CombinatorType> comb;
iterator_type<CombinatorType> comb_iter;
iterator_type<CombinatorType> comb_end;
public:
Iterator(Container& in_container, std::size_t sz)
: container_p{&in_container},
set_size{sz},
comb{new CombinatorType(combinations(in_container, sz))},
comb_iter{std::begin(*comb)},
comb_end{std::end(*comb)}
{ }
Iterator& operator++() {
++this->comb_iter;
if (this->comb_iter == this->comb_end) {
++this->set_size;
this->comb.reset(new CombinatorType(combinations(
*this->container_p, this->set_size)));
this->comb_iter = std::begin(*this->comb);
this->comb_end = std::end(*this->comb);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<CombinatorType> operator*() {
return *this->comb_iter;
}
bool operator != (const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->set_size == other.set_size
&& this->comb_iter == other.comb_iter;
}
};
Iterator begin() {
return {this->container, 0};
}
Iterator end() {
return {this->container, dumb_size(this->container) + 1};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<commit_msg>removes "naked new"s in powerset using make_shared<commit_after>#ifndef ITER_POWERSET_HPP_
#define ITER_POWERSET_HPP_
#include "iterbase.hpp"
#include "combinations.hpp"
#include <cassert>
#include <memory>
#include <initializer_list>
#include <utility>
#include <iterator>
#include <type_traits>
namespace iter {
template <typename Container>
class Powersetter {
private:
Container container;
using CombinatorType =
decltype(combinations(std::declval<Container&>(), 0));
public:
Powersetter(Container&& in_container)
: container(std::forward<Container>(in_container))
{ }
class Iterator
: public std::iterator<
std::input_iterator_tag, CombinatorType>
{
private:
std::remove_reference_t<Container> *container_p;
std::size_t set_size;
std::shared_ptr<CombinatorType> comb;
iterator_type<CombinatorType> comb_iter;
iterator_type<CombinatorType> comb_end;
public:
Iterator(Container& in_container, std::size_t sz)
: container_p{&in_container},
set_size{sz},
comb{std::make_shared<CombinatorType>(
combinations(in_container, sz))},
comb_iter{std::begin(*comb)},
comb_end{std::end(*comb)}
{ }
Iterator& operator++() {
++this->comb_iter;
if (this->comb_iter == this->comb_end) {
++this->set_size;
this->comb = std::make_shared<CombinatorType>(
combinations(
*this->container_p, this->set_size));
this->comb_iter = std::begin(*this->comb);
this->comb_end = std::end(*this->comb);
}
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<CombinatorType> operator*() {
return *this->comb_iter;
}
bool operator != (const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->set_size == other.set_size
&& this->comb_iter == other.comb_iter;
}
};
Iterator begin() {
return {this->container, 0};
}
Iterator end() {
return {this->container, dumb_size(this->container) + 1};
}
};
template <typename Container>
Powersetter<Container> powerset(Container&& container) {
return {std::forward<Container>(container)};
}
template <typename T>
Powersetter<std::initializer_list<T>> powerset(
std::initializer_list<T> il) {
return {std::move(il)};
}
}
#endif
<|endoftext|> |
<commit_before><commit_msg>添加性能测试用例<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2009-2013 Juli Mallett. 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.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <common/endian.h>
#include <event/event_callback.h>
#include <io/socket/socket.h>
#include "proxy_connector.h"
#include "proxy_socks_connection.h"
ProxySocksConnection::ProxySocksConnection(const std::string& name, Socket *client)
: log_("/wanproxy/proxy/" + name + "/socks/connection"),
name_(name),
client_(client),
action_(NULL),
state_(GetSOCKSVersion),
network_port_(0),
network_address_(),
socks5_authenticated_(false),
socks5_remote_name_()
{
schedule_read(1);
}
ProxySocksConnection::~ProxySocksConnection()
{
ASSERT(log_, action_ == NULL);
}
void
ProxySocksConnection::read_complete(Event e)
{
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
case Event::EOS:
INFO(log_) << "Client closed before connection established.";
schedule_close();
return;
default:
ERROR(log_) << "Unexpected event: " << e;
schedule_close();
return;
}
switch (state_) {
case GetSOCKSVersion:
switch (e.buffer_.peek()) {
case 0x04:
state_ = GetSOCKS4Command;
schedule_read(1);
break;
case 0x05:
if (socks5_authenticated_) {
state_ = GetSOCKS5Command;
schedule_read(1);
} else {
state_ = GetSOCKS5AuthLength;
schedule_read(1);
}
break;
default:
schedule_close();
break;
}
break;
/* SOCKS4 */
case GetSOCKS4Command:
if (e.buffer_.peek() != 0x01) {
schedule_close();
break;
}
state_ = GetSOCKS4Port;
schedule_read(2);
break;
case GetSOCKS4Port:
e.buffer_.extract(&network_port_);
network_port_ = BigEndian::decode(network_port_);
state_ = GetSOCKS4Address;
schedule_read(4);
break;
case GetSOCKS4Address:
ASSERT(log_, e.buffer_.length() == 4);
network_address_ = e.buffer_;
state_ = GetSOCKS4User;
schedule_read(1);
break;
case GetSOCKS4User:
if (e.buffer_.peek() == 0x00) {
schedule_write();
break;
}
schedule_read(1);
break;
/* SOCKS5 */
case GetSOCKS5AuthLength:
state_ = GetSOCKS5Auth;
schedule_read(e.buffer_.peek());
break;
case GetSOCKS5Auth:
while (!e.buffer_.empty()) {
if (e.buffer_.peek() == 0x00) {
schedule_write();
break;
}
e.buffer_.skip(1);
}
if (e.buffer_.empty()) {
schedule_close();
break;
}
break;
case GetSOCKS5Command:
if (e.buffer_.peek() != 0x01) {
schedule_close();
break;
}
state_ = GetSOCKS5Reserved;
schedule_read(1);
break;
case GetSOCKS5Reserved:
if (e.buffer_.peek() != 0x00) {
schedule_close();
break;
}
state_ = GetSOCKS5AddressType;
schedule_read(1);
break;
case GetSOCKS5AddressType:
switch (e.buffer_.peek()) {
case 0x01:
state_ = GetSOCKS5Address;
schedule_read(4);
break;
case 0x03:
state_ = GetSOCKS5NameLength;
schedule_read(1);
break;
case 0x04:
state_ = GetSOCKS5Address6;
schedule_read(16);
break;
default:
schedule_close();
break;
}
break;
case GetSOCKS5Address:
ASSERT(log_, e.buffer_.length() == 4);
network_address_ = e.buffer_;
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5Address6:
ASSERT(log_, e.buffer_.length() == 16);
network_address_ = e.buffer_;
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5NameLength:
state_ = GetSOCKS5Name;
schedule_read(e.buffer_.peek());
break;
case GetSOCKS5Name:
while (!e.buffer_.empty()) {
socks5_remote_name_ += (char)e.buffer_.peek();
e.buffer_.skip(1);
}
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5Port:
e.buffer_.extract(&network_port_);
network_port_ = BigEndian::decode(network_port_);
schedule_write();
break;
}
}
void
ProxySocksConnection::write_complete(Event e)
{
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Unexpected event: " << e;
schedule_close();
return;
}
if (state_ == GetSOCKS5Auth) {
ASSERT(log_, !socks5_authenticated_);
ASSERT(log_, socks5_remote_name_ == "");
ASSERT(log_, network_address_.empty());
ASSERT(log_, network_port_ == 0);
socks5_authenticated_ = true;
state_ = GetSOCKSVersion;
schedule_read(1);
return;
}
std::ostringstream remote_name;
SocketAddressFamily family;
if (state_ == GetSOCKS5Port && socks5_remote_name_ != "") {
ASSERT(log_, socks5_authenticated_);
ASSERT(log_, network_address_.empty());
remote_name << '[' << socks5_remote_name_ << ']' << ':' << network_port_;
family = SocketAddressFamilyIP;
} else {
remote_name << '[';
switch (network_address_.length()) {
case 4:
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek();
network_address_.skip(1);
family = SocketAddressFamilyIPv4;
break;
case 16:
for (;;) {
uint8_t bytes[2];
char hex[5];
network_address_.moveout(bytes, sizeof bytes);
if (bytes[0] == 0 && bytes[1] == 0)
strlcpy(hex, "0", sizeof hex);
else
snprintf(hex, sizeof hex, "%0x%02x", bytes[0], bytes[1]);
remote_name << hex;
if (network_address_.empty())
break;
remote_name << ":";
}
family = SocketAddressFamilyIPv6;
break;
default:
NOTREACHED(log_);
}
remote_name << ']';
remote_name << ':' << network_port_;
}
new ProxyConnector(name_, NULL, client_, SocketImplOS, family, remote_name.str());
client_ = NULL;
delete this;
}
void
ProxySocksConnection::close_complete(void)
{
action_->cancel();
action_ = NULL;
ASSERT(log_, client_ != NULL);
delete client_;
client_ = NULL;
delete this;
return;
}
void
ProxySocksConnection::schedule_read(size_t amount)
{
ASSERT(log_, action_ == NULL);
ASSERT(log_, client_ != NULL);
EventCallback *cb = callback(this, &ProxySocksConnection::read_complete);
action_ = client_->read(amount, cb);
}
void
ProxySocksConnection::schedule_write(void)
{
ASSERT(log_, action_ == NULL);
static const uint8_t socks4_connected[] = {
0x00,
0x5a,
0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
static const uint8_t socks5_authenticated[] = {
0x05,
0x00,
};
static const uint8_t socks5_connected[] = {
0x05,
0x00,
0x00,
};
Buffer response;
switch (state_) {
case GetSOCKS4User:
response.append(socks4_connected, sizeof socks4_connected);
break;
case GetSOCKS5Auth:
response.append(socks5_authenticated, sizeof socks5_authenticated);
break;
case GetSOCKS5Port: {
response.append(socks5_connected, sizeof socks5_connected);
/* XXX It's fun to lie about what kind of name we were given. */
if (socks5_remote_name_ != "" || network_address_.empty()) {
response.append((uint8_t)0x03);
response.append((uint8_t)socks5_remote_name_.length());
response.append(socks5_remote_name_);
} else {
uint32_t address;
network_address_.extract(&address);
address = BigEndian::encode(address);
response.append((uint8_t)0x01);
response.append(&address);
}
uint16_t port = BigEndian::encode(network_port_);
response.append(&port);
break;
}
default:
NOTREACHED(log_);
}
ASSERT(log_, client_ != NULL);
EventCallback *cb = callback(this, &ProxySocksConnection::write_complete);
action_ = client_->write(&response, cb);
}
void
ProxySocksConnection::schedule_close(void)
{
ASSERT(log_, action_ == NULL);
ASSERT(log_, client_ != NULL);
SimpleCallback *cb = callback(this, &ProxySocksConnection::close_complete);
action_ = client_->close(cb);
}
<commit_msg>Just copy back the original network address.<commit_after>/*
* Copyright (c) 2009-2013 Juli Mallett. 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.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <common/endian.h>
#include <event/event_callback.h>
#include <io/socket/socket.h>
#include "proxy_connector.h"
#include "proxy_socks_connection.h"
ProxySocksConnection::ProxySocksConnection(const std::string& name, Socket *client)
: log_("/wanproxy/proxy/" + name + "/socks/connection"),
name_(name),
client_(client),
action_(NULL),
state_(GetSOCKSVersion),
network_port_(0),
network_address_(),
socks5_authenticated_(false),
socks5_remote_name_()
{
schedule_read(1);
}
ProxySocksConnection::~ProxySocksConnection()
{
ASSERT(log_, action_ == NULL);
}
void
ProxySocksConnection::read_complete(Event e)
{
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
case Event::EOS:
INFO(log_) << "Client closed before connection established.";
schedule_close();
return;
default:
ERROR(log_) << "Unexpected event: " << e;
schedule_close();
return;
}
switch (state_) {
case GetSOCKSVersion:
switch (e.buffer_.peek()) {
case 0x04:
state_ = GetSOCKS4Command;
schedule_read(1);
break;
case 0x05:
if (socks5_authenticated_) {
state_ = GetSOCKS5Command;
schedule_read(1);
} else {
state_ = GetSOCKS5AuthLength;
schedule_read(1);
}
break;
default:
schedule_close();
break;
}
break;
/* SOCKS4 */
case GetSOCKS4Command:
if (e.buffer_.peek() != 0x01) {
schedule_close();
break;
}
state_ = GetSOCKS4Port;
schedule_read(2);
break;
case GetSOCKS4Port:
e.buffer_.extract(&network_port_);
network_port_ = BigEndian::decode(network_port_);
state_ = GetSOCKS4Address;
schedule_read(4);
break;
case GetSOCKS4Address:
ASSERT(log_, e.buffer_.length() == 4);
network_address_ = e.buffer_;
state_ = GetSOCKS4User;
schedule_read(1);
break;
case GetSOCKS4User:
if (e.buffer_.peek() == 0x00) {
schedule_write();
break;
}
schedule_read(1);
break;
/* SOCKS5 */
case GetSOCKS5AuthLength:
state_ = GetSOCKS5Auth;
schedule_read(e.buffer_.peek());
break;
case GetSOCKS5Auth:
while (!e.buffer_.empty()) {
if (e.buffer_.peek() == 0x00) {
schedule_write();
break;
}
e.buffer_.skip(1);
}
if (e.buffer_.empty()) {
schedule_close();
break;
}
break;
case GetSOCKS5Command:
if (e.buffer_.peek() != 0x01) {
schedule_close();
break;
}
state_ = GetSOCKS5Reserved;
schedule_read(1);
break;
case GetSOCKS5Reserved:
if (e.buffer_.peek() != 0x00) {
schedule_close();
break;
}
state_ = GetSOCKS5AddressType;
schedule_read(1);
break;
case GetSOCKS5AddressType:
switch (e.buffer_.peek()) {
case 0x01:
state_ = GetSOCKS5Address;
schedule_read(4);
break;
case 0x03:
state_ = GetSOCKS5NameLength;
schedule_read(1);
break;
case 0x04:
state_ = GetSOCKS5Address6;
schedule_read(16);
break;
default:
schedule_close();
break;
}
break;
case GetSOCKS5Address:
ASSERT(log_, e.buffer_.length() == 4);
network_address_ = e.buffer_;
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5Address6:
ASSERT(log_, e.buffer_.length() == 16);
network_address_ = e.buffer_;
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5NameLength:
state_ = GetSOCKS5Name;
schedule_read(e.buffer_.peek());
break;
case GetSOCKS5Name:
while (!e.buffer_.empty()) {
socks5_remote_name_ += (char)e.buffer_.peek();
e.buffer_.skip(1);
}
state_ = GetSOCKS5Port;
schedule_read(2);
break;
case GetSOCKS5Port:
e.buffer_.extract(&network_port_);
network_port_ = BigEndian::decode(network_port_);
schedule_write();
break;
}
}
void
ProxySocksConnection::write_complete(Event e)
{
action_->cancel();
action_ = NULL;
switch (e.type_) {
case Event::Done:
break;
default:
ERROR(log_) << "Unexpected event: " << e;
schedule_close();
return;
}
if (state_ == GetSOCKS5Auth) {
ASSERT(log_, !socks5_authenticated_);
ASSERT(log_, socks5_remote_name_ == "");
ASSERT(log_, network_address_.empty());
ASSERT(log_, network_port_ == 0);
socks5_authenticated_ = true;
state_ = GetSOCKSVersion;
schedule_read(1);
return;
}
std::ostringstream remote_name;
SocketAddressFamily family;
if (state_ == GetSOCKS5Port && socks5_remote_name_ != "") {
ASSERT(log_, socks5_authenticated_);
ASSERT(log_, network_address_.empty());
remote_name << '[' << socks5_remote_name_ << ']' << ':' << network_port_;
family = SocketAddressFamilyIP;
} else {
remote_name << '[';
switch (network_address_.length()) {
case 4:
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek() << '.';
network_address_.skip(1);
remote_name << (unsigned)network_address_.peek();
network_address_.skip(1);
family = SocketAddressFamilyIPv4;
break;
case 16:
for (;;) {
uint8_t bytes[2];
char hex[5];
network_address_.moveout(bytes, sizeof bytes);
if (bytes[0] == 0 && bytes[1] == 0)
strlcpy(hex, "0", sizeof hex);
else
snprintf(hex, sizeof hex, "%0x%02x", bytes[0], bytes[1]);
remote_name << hex;
if (network_address_.empty())
break;
remote_name << ":";
}
family = SocketAddressFamilyIPv6;
break;
default:
NOTREACHED(log_);
}
remote_name << ']';
remote_name << ':' << network_port_;
}
new ProxyConnector(name_, NULL, client_, SocketImplOS, family, remote_name.str());
client_ = NULL;
delete this;
}
void
ProxySocksConnection::close_complete(void)
{
action_->cancel();
action_ = NULL;
ASSERT(log_, client_ != NULL);
delete client_;
client_ = NULL;
delete this;
return;
}
void
ProxySocksConnection::schedule_read(size_t amount)
{
ASSERT(log_, action_ == NULL);
ASSERT(log_, client_ != NULL);
EventCallback *cb = callback(this, &ProxySocksConnection::read_complete);
action_ = client_->read(amount, cb);
}
void
ProxySocksConnection::schedule_write(void)
{
ASSERT(log_, action_ == NULL);
static const uint8_t socks4_connected[] = {
0x00,
0x5a,
0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
static const uint8_t socks5_authenticated[] = {
0x05,
0x00,
};
static const uint8_t socks5_connected[] = {
0x05,
0x00,
0x00,
};
Buffer response;
switch (state_) {
case GetSOCKS4User:
response.append(socks4_connected, sizeof socks4_connected);
break;
case GetSOCKS5Auth:
response.append(socks5_authenticated, sizeof socks5_authenticated);
break;
case GetSOCKS5Port: {
response.append(socks5_connected, sizeof socks5_connected);
/* XXX It's fun to lie about what kind of name we were given. */
if (socks5_remote_name_ != "" || network_address_.empty()) {
response.append((uint8_t)0x03);
response.append((uint8_t)socks5_remote_name_.length());
response.append(socks5_remote_name_);
} else {
response.append((uint8_t)0x01);
response.append(&network_address_);
}
uint16_t port = BigEndian::encode(network_port_);
response.append(&port);
break;
}
default:
NOTREACHED(log_);
}
ASSERT(log_, client_ != NULL);
EventCallback *cb = callback(this, &ProxySocksConnection::write_complete);
action_ = client_->write(&response, cb);
}
void
ProxySocksConnection::schedule_close(void)
{
ASSERT(log_, action_ == NULL);
ASSERT(log_, client_ != NULL);
SimpleCallback *cb = callback(this, &ProxySocksConnection::close_complete);
action_ = client_->close(cb);
}
<|endoftext|> |
<commit_before>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QDomDocument>
#include <QDomElement>
#include <QSharedPointer>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
// Load count.
static unsigned int instances(0);
// Correlation object.
static QSharedPointer<multiplexing::hooker> obj;
extern "C" {
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
// Decrement instance number.
if (!--instances) {
// Unregister correlation object.
multiplexing::engine::instance().unhook(*obj);
obj.clear();
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
// Increment instance number.
if (!instances++) {
// Check that correlation is enabled.
config::state const& cfg(*static_cast<config::state const*>(arg));
bool loaded(false);
QMap<QString, QString>::const_iterator
it(cfg.params().find("correlation"));
if (it != cfg.params().end()) {
// Parameters.
QString correlation_file;
QString retention_file;
// Parse XML.
QDomDocument d;
if (d.setContent(it.value())) {
// Browse first-level elements.
QDomElement root(d.documentElement());
QDomNodeList level1(root.childNodes());
for (int i = 0, len = level1.size(); i < len; ++i) {
QDomElement elem(level1.item(i).toElement());
if (!elem.isNull()) {
QString name(elem.tagName());
if (name == "file")
correlation_file = elem.text();
else if (name == "retention")
retention_file = elem.text();
}
}
}
if (!correlation_file.isEmpty()) {
// Create and register correlation object.
QSharedPointer<correlation::correlator>
crltr(new correlation::correlator);
try {
crltr->load(correlation_file, retention_file);
obj = crltr.staticCast<multiplexing::hooker>();
multiplexing::engine::instance().hook(*obj);
loaded = true;
}
catch (std::exception const& e) {
logging::config << logging::HIGH << "correlation: " \
"configuration loading error: " << e.what();
}
catch (...) {
logging::config << logging::HIGH << "correlation: " \
"configuration loading error";
}
}
}
if (!loaded)
logging::config << logging::HIGH << "correlation: invalid " \
"correlation configuration, correlation engine is NOT loaded";
}
return ;
}
}
<commit_msg>Minor improvements in correlation module.<commit_after>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <QDomDocument>
#include <QDomElement>
#include <QSharedPointer>
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/correlation/correlator.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/multiplexing/engine.hh"
using namespace com::centreon::broker;
// Load count.
static unsigned int instances(0);
// Correlation object.
static QSharedPointer<multiplexing::hooker> obj;
extern "C" {
/**
* Module deinitialization routine.
*/
void broker_module_deinit() {
// Decrement instance number.
if (!--instances) {
// Unregister correlation object.
multiplexing::engine::instance().unhook(*obj);
obj.clear();
}
return ;
}
/**
* Module initialization routine.
*
* @param[in] arg Configuration argument.
*/
void broker_module_init(void const* arg) {
// Increment instance number.
if (!instances++) {
// Check that correlation is enabled.
config::state const& cfg(*static_cast<config::state const*>(arg));
bool loaded(false);
QMap<QString, QString>::const_iterator
it(cfg.params().find("correlation"));
if (it != cfg.params().end()) {
// Parameters.
QString correlation_file;
QString retention_file;
// Parse XML.
QDomDocument d;
if (d.setContent(it.value())) {
// Browse first-level elements.
QDomElement root(d.documentElement());
QDomNodeList level1(root.childNodes());
for (int i = 0, len = level1.size(); i < len; ++i) {
QDomElement elem(level1.item(i).toElement());
if (!elem.isNull()) {
QString name(elem.tagName());
if (name == "file")
correlation_file = elem.text();
else if (name == "retention")
retention_file = elem.text();
}
}
}
// File exists, load it.
if (!correlation_file.isEmpty()) {
// Create and register correlation object.
QSharedPointer<correlation::correlator>
crltr(new correlation::correlator);
try {
crltr->load(correlation_file, retention_file);
obj = crltr.staticCast<multiplexing::hooker>();
multiplexing::engine::instance().hook(*obj);
loaded = true;
}
catch (std::exception const& e) {
logging::config(logging::high) << "correlation: " \
"configuration loading error: " << e.what();
}
catch (...) {
logging::config(logging::high) << "correlation: " \
"configuration loading error";
}
}
}
if (!loaded)
logging::config(logging::high) << "correlation: invalid " \
"correlation configuration, correlation engine is NOT loaded";
}
return ;
}
}
<|endoftext|> |
<commit_before>/*
* SessionExecuteChunkOperation.hpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP
#define SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <core/system/System.hpp>
#include "NotebookOutput.hpp"
#include "NotebookExec.hpp"
#include "SessionRmdNotebook.hpp"
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
class ExecuteChunkOperation : boost::noncopyable,
public boost::enable_shared_from_this<ExecuteChunkOperation>
{
typedef core::shell_utils::ShellCommand ShellCommand;
typedef core::system::ProcessCallbacks ProcessCallbacks;
typedef core::system::ProcessOperations ProcessOperations;
public:
static boost::shared_ptr<ExecuteChunkOperation> create(const std::string& docId,
const std::string& chunkId,
const ShellCommand& command)
{
return boost::shared_ptr<ExecuteChunkOperation>(new ExecuteChunkOperation(
docId,
chunkId,
command));
}
private:
ExecuteChunkOperation(const std::string& docId,
const std::string& chunkId,
const ShellCommand& command)
: isRunning_(false),
terminationRequested_(false),
docId_(docId),
chunkId_(chunkId),
command_(command)
{
}
public:
ProcessCallbacks processCallbacks()
{
ProcessCallbacks callbacks;
callbacks.onStarted = boost::bind(
&ExecuteChunkOperation::onStarted,
shared_from_this(),
_1);
callbacks.onContinue = boost::bind(
&ExecuteChunkOperation::onContinue,
shared_from_this(),
_1);
callbacks.onStdout = boost::bind(
&ExecuteChunkOperation::onStdout,
shared_from_this(),
_1,
_2);
callbacks.onStderr = boost::bind(
&ExecuteChunkOperation::onStderr,
shared_from_this(),
_1,
_2);
callbacks.onExit = boost::bind(
&ExecuteChunkOperation::onExit,
shared_from_this(),
_1);
return callbacks;
}
private:
void onStarted(ProcessOperations& operations)
{
using namespace core;
Error error = Success();
// ensure staging directory
FilePath stagingPath = notebook::chunkOutputPath(
docId_,
chunkId_ + kStagingSuffix,
notebook::ContextExact);
error = stagingPath.ensureDirectory();
if (error)
LOG_ERROR(error);
// ensure regular directory
FilePath outputPath = notebook::chunkOutputPath(
docId_,
chunkId_,
notebook::ContextExact);
error = outputPath.ensureDirectory();
if (error)
LOG_ERROR(error);
// clean old chunk output
error = notebook::cleanChunkOutput(docId_, chunkId_, true);
if (error)
LOG_ERROR(error);
isRunning_ = true;
}
bool onContinue(ProcessOperations& operations)
{
return !terminationRequested_;
}
void onExit(int exitStatus)
{
isRunning_ = false;
}
void onStdout(ProcessOperations& operations, const std::string& output)
{
core::FilePath target = notebook::chunkOutputFile(docId_, chunkId_, notebook::ContextExact);
notebook::enqueueChunkOutput(docId_, chunkId_, notebook::notebookCtxId(), kChunkOutputText, target);
}
void onStderr(ProcessOperations& operations, const std::string& output)
{
core::FilePath target = notebook::chunkOutputFile(docId_, chunkId_, notebook::ContextExact);
notebook::enqueueChunkOutput(docId_, chunkId_, notebook::notebookCtxId(), kChunkOutputError, target);
}
void terminate()
{
terminationRequested_ = true;
}
public:
bool isRunning() const { return isRunning_; }
bool terminationRequested() const { return terminationRequested_; }
const std::string& chunkId() const { return chunkId_; }
private:
bool isRunning_;
bool terminationRequested_;
std::string docId_;
std::string chunkId_;
std::vector<boost::signals::connection> connections_;
ShellCommand command_;
};
} // end namespace rmarkdown
} // end namespace modules
} // end namespace session
} // end namespace rstudio
#endif /* SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP */
<commit_msg>writing of CSV data as necessary<commit_after>/*
* SessionExecuteChunkOperation.hpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP
#define SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <core/FileSerializer.hpp>
#include <core/text/CsvParser.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <core/system/System.hpp>
#include "NotebookOutput.hpp"
#include "NotebookExec.hpp"
#include "SessionRmdNotebook.hpp"
namespace rstudio {
namespace session {
namespace modules {
namespace rmarkdown {
class ExecuteChunkOperation : boost::noncopyable,
public boost::enable_shared_from_this<ExecuteChunkOperation>
{
typedef core::shell_utils::ShellCommand ShellCommand;
typedef core::system::ProcessCallbacks ProcessCallbacks;
typedef core::system::ProcessOperations ProcessOperations;
public:
static boost::shared_ptr<ExecuteChunkOperation> create(const std::string& docId,
const std::string& chunkId,
const ShellCommand& command)
{
return boost::shared_ptr<ExecuteChunkOperation>(new ExecuteChunkOperation(
docId,
chunkId,
command));
}
private:
ExecuteChunkOperation(const std::string& docId,
const std::string& chunkId,
const ShellCommand& command)
: isRunning_(false),
terminationRequested_(false),
docId_(docId),
chunkId_(chunkId),
command_(command)
{
using namespace core;
Error error = Success();
// ensure staging directory
FilePath stagingPath = notebook::chunkOutputPath(
docId_,
chunkId_ + kStagingSuffix,
notebook::ContextExact);
error = stagingPath.removeIfExists();
if (error)
LOG_ERROR(error);
error = stagingPath.ensureDirectory();
if (error)
LOG_ERROR(error);
// ensure regular directory
FilePath outputPath = notebook::chunkOutputPath(
docId_,
chunkId_,
notebook::ContextExact);
error = outputPath.removeIfExists();
if (error)
LOG_ERROR(error);
error = outputPath.ensureDirectory();
if (error)
LOG_ERROR(error);
// clean old chunk output
error = notebook::cleanChunkOutput(docId_, chunkId_, true);
if (error)
LOG_ERROR(error);
}
public:
ProcessCallbacks processCallbacks()
{
ProcessCallbacks callbacks;
callbacks.onStarted = boost::bind(
&ExecuteChunkOperation::onStarted,
shared_from_this(),
_1);
callbacks.onContinue = boost::bind(
&ExecuteChunkOperation::onContinue,
shared_from_this(),
_1);
callbacks.onStdout = boost::bind(
&ExecuteChunkOperation::onStdout,
shared_from_this(),
_1,
_2);
callbacks.onStderr = boost::bind(
&ExecuteChunkOperation::onStderr,
shared_from_this(),
_1,
_2);
callbacks.onExit = boost::bind(
&ExecuteChunkOperation::onExit,
shared_from_this(),
_1);
return callbacks;
}
private:
enum OutputType { OUTPUT_STDOUT, OUTPUT_STDERR };
void onStarted(ProcessOperations& operations)
{
isRunning_ = true;
}
bool onContinue(ProcessOperations& operations)
{
return !terminationRequested_;
}
void onExit(int exitStatus)
{
notebook::events().onChunkExecCompleted(docId_, chunkId_, notebook::notebookCtxId());
isRunning_ = false;
}
void onStdout(ProcessOperations& operations, const std::string& output)
{
onText(output, OUTPUT_STDOUT);
}
void onStderr(ProcessOperations& operations, const std::string& output)
{
onText(output, OUTPUT_STDERR);
}
void onText(const std::string& output, OutputType outputType)
{
using namespace core;
// get path to cache file
FilePath target = notebook::chunkOutputFile(docId_, chunkId_, kChunkOutputText);
// generate CSV to write
std::vector<std::string> values;
values.push_back(outputType == OUTPUT_STDOUT ? "1" : "2");
values.push_back(output);
std::string encoded = text::encodeCsvLine(values) + "\n";
// write to cache
Error error = writeStringToFile(target, encoded);
if (error)
LOG_ERROR(error);
// emit client event
notebook::enqueueChunkOutput(
docId_,
chunkId_,
notebook::notebookCtxId(),
kChunkOutputText,
target);
}
void terminate()
{
terminationRequested_ = true;
}
public:
bool isRunning() const { return isRunning_; }
bool terminationRequested() const { return terminationRequested_; }
const std::string& chunkId() const { return chunkId_; }
private:
bool isRunning_;
bool terminationRequested_;
std::string docId_;
std::string chunkId_;
std::vector<boost::signals::connection> connections_;
ShellCommand command_;
};
} // end namespace rmarkdown
} // end namespace modules
} // end namespace session
} // end namespace rstudio
#endif /* SESSION_MODULES_RMARKDOWN_SESSION_EXECUTE_CHUNK_OPERATIONR_HPP */
<|endoftext|> |
<commit_before>/* Copyright 2015 CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "applicationInitHelper.h"
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtGui/QFont>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#include <QtGui/QApplication>
#include <QtGui/QWSServer>
#else
#include <QtWidgets/QApplication>
#endif
#include <QsLog.h>
#include "translationsHelper.h"
#include "version.h"
#include "fileUtils.h"
#include "coreDumping.h"
#include "loggingHelper.h"
#include "paths.h"
using namespace trikKernel;
ApplicationInitHelper::ApplicationInitHelper(QCoreApplication &app)
: mApp(app)
, mLoggingHelper(new LoggingHelper(Paths::logsPath()))
{
qsrand(QDateTime::currentMSecsSinceEpoch());
mApp.setApplicationVersion(trikKernel::version);
trikKernel::TranslationsHelper::initLocale(app.arguments().contains("--no-locale")
|| app.arguments().contains("-no-locale"));
QApplication *guiApp = dynamic_cast<QApplication *>(&app);
if (guiApp) {
QFont font(guiApp->font());
font.setPixelSize(18);
guiApp->setFont(font);
}
mCommandLineParser.addFlag("h", "help", QObject::tr("Print this help text."));
mCommandLineParser.addFlag("no-locale", "no-locale"
, QObject::tr("Ignore all locale options and use English language"));
mCommandLineParser.addOption("c", "config-path"
, QObject::tr("Path to a directory where all configs for TRIK runtime are stored. Config files are\n"
"\tsystem-config.xml (system-wide configuration of robot hardware for trikControl library) and\n"
"\tmodel-config.xml (configuration of current model).")
);
#ifdef Q_WS_QWS
if (!app.arguments().contains("--no-display") && !!app.arguments().contains("-no-display")) {
QWSServer * const server = QWSServer::instance();
if (server) {
server->setCursorVisible(false);
}
}
#endif
}
ApplicationInitHelper::~ApplicationInitHelper()
{
}
trikKernel::CommandLineParser &ApplicationInitHelper::commandLineParser()
{
return mCommandLineParser;
}
bool ApplicationInitHelper::parseCommandLine()
{
if (!mCommandLineParser.process(mApp) || mCommandLineParser.isSet("h")) {
mCommandLineParser.showHelp();
return false;
}
return true;
}
void ApplicationInitHelper::init()
{
trikKernel::coreDumping::initCoreDumping();
mConfigPath = Paths::configsPath();
if (mCommandLineParser.isSet("c")) {
mConfigPath = trikKernel::FileUtils::normalizePath(mCommandLineParser.value("c"));
}
QLOG_INFO() << "====================================================================";
}
QString ApplicationInitHelper::configPath() const
{
return mConfigPath;
}
<commit_msg>Fixed visible mouse cursor<commit_after>/* Copyright 2015 CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "applicationInitHelper.h"
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtGui/QFont>
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#include <QtGui/QApplication>
#include <QtGui/QWSServer>
#else
#include <QtWidgets/QApplication>
#endif
#include <QsLog.h>
#include "translationsHelper.h"
#include "version.h"
#include "fileUtils.h"
#include "coreDumping.h"
#include "loggingHelper.h"
#include "paths.h"
using namespace trikKernel;
ApplicationInitHelper::ApplicationInitHelper(QCoreApplication &app)
: mApp(app)
, mLoggingHelper(new LoggingHelper(Paths::logsPath()))
{
qsrand(QDateTime::currentMSecsSinceEpoch());
mApp.setApplicationVersion(trikKernel::version);
trikKernel::TranslationsHelper::initLocale(app.arguments().contains("--no-locale")
|| app.arguments().contains("-no-locale"));
QApplication *guiApp = dynamic_cast<QApplication *>(&app);
if (guiApp) {
QFont font(guiApp->font());
font.setPixelSize(18);
guiApp->setFont(font);
}
mCommandLineParser.addFlag("h", "help", QObject::tr("Print this help text."));
mCommandLineParser.addFlag("no-locale", "no-locale"
, QObject::tr("Ignore all locale options and use English language"));
mCommandLineParser.addOption("c", "config-path"
, QObject::tr("Path to a directory where all configs for TRIK runtime are stored. Config files are\n"
"\tsystem-config.xml (system-wide configuration of robot hardware for trikControl library) and\n"
"\tmodel-config.xml (configuration of current model).")
);
#ifdef Q_WS_QWS
if (!app.arguments().contains("--no-display") && !app.arguments().contains("-no-display")) {
QWSServer * const server = QWSServer::instance();
if (server) {
server->setCursorVisible(false);
}
}
#endif
}
ApplicationInitHelper::~ApplicationInitHelper()
{
}
trikKernel::CommandLineParser &ApplicationInitHelper::commandLineParser()
{
return mCommandLineParser;
}
bool ApplicationInitHelper::parseCommandLine()
{
if (!mCommandLineParser.process(mApp) || mCommandLineParser.isSet("h")) {
mCommandLineParser.showHelp();
return false;
}
return true;
}
void ApplicationInitHelper::init()
{
trikKernel::coreDumping::initCoreDumping();
mConfigPath = Paths::configsPath();
if (mCommandLineParser.isSet("c")) {
mConfigPath = trikKernel::FileUtils::normalizePath(mCommandLineParser.value("c"));
}
QLOG_INFO() << "====================================================================";
}
QString ApplicationInitHelper::configPath() const
{
return mConfigPath;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewShellImplementation.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:44:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX
#include "ViewShell.hxx"
#include "ViewShellManager.hxx"
#include "ToolBarManager.hxx"
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <memory>
namespace sd {
class DrawController;
/** This class contains (will contain) the implementation of methods that
have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
bool mbIsShowingUIControls;
bool mbIsMainViewShell;
/// Set to true when the ViewShell::Init() method has been called.
bool mbIsInitialized;
/** Set to true while ViewShell::ArrangeGUIElements() is being
executed. It is used as guard against recursive execution.
*/
bool mbArrangeActive;
/** Remember a link to the sub shell factory, so that it can be
unregistered at the ViewShellManager when a ViewShell is deleted.
*/
ViewShellManager::SharedShellFactory mpSubShellFactory;
/** This update lock for the ToolBarManager exists in order to avoid
problems with tool bars being displayed while the mouse button is
pressed. Whith docked tool bars this can lead to a size change of
the view. This would change the relative mouse coordinates and thus
interpret every mouse click as move command.
*/
class ToolBarManagerLock
{
public:
/** Create a new instance. This allows the mpSelf member to be set
automatically.
*/
static ::boost::shared_ptr<ToolBarManagerLock> Create (
const ::boost::shared_ptr<ToolBarManager>& rpManager);
/** Release the lock. When the UI is captured
(Application::IsUICaptured() returns <TRUE/>) then the lock is
released later asynchronously.
@param bForce
When this flag is <TRUE/> then the lock is released even
when IsUICaptured() returns <TRUE/>.
*/
void Release (bool bForce = false);
DECL_LINK(TimeoutCallback,Timer*);
private:
::std::auto_ptr<sd::ToolBarManager::UpdateLock> mpLock;
/** The timer is used both as a safe guard to unlock the update lock
when Release() is not called explicitly. It is also used to
defer the release of the lock to a time when the UI is not
captured.
*/
Timer maTimer;
/** The shared_ptr to this allows the ToolBarManagerLock to control
its own lifetime. This, of course, does work only when no one
holds another shared_ptr longer than only temporary.
*/
::boost::shared_ptr<ToolBarManagerLock> mpSelf;
ToolBarManagerLock (const ::boost::shared_ptr<ToolBarManager>& rpManager);
~ToolBarManagerLock (void);
class Deleter;
friend class Deleter;
};
// The member is not an auto_ptr because it takes over its own life time
// control.
::boost::weak_ptr<ToolBarManagerLock> mpUpdateLockForMouse;
Implementation (ViewShell& rViewShell);
~Implementation (void);
/** Process the SID_MODIFY slot.
*/
void ProcessModifyPageSlot (
SfxRequest& rRequest,
SdPage* pCurrentPage,
PageKind ePageKind);
/** Assign the given layout to the given page. This method is at the
moment merely a front end for ProcessModifyPageSlot.
@param pPage
If a NULL pointer is given then this call is ignored.
*/
void AssignLayout (
SdPage* pPage,
AutoLayout aLayout);
/** Determine the view id of the view shell. This corresponds to the
view id stored in the SfxViewFrame class.
We can not use the view of that class because with the introduction
of the multi pane GUI we do not switch the SfxViewShell anymore when
switching the view in the center pane. The view id of the
SfxViewFrame is thus not modified and we can not set it from the
outside.
The view id is still needed for the SFX to determine on start up
(e.g. after loading a document) which ViewShellBase sub class to
use. These sub classes--like OutlineViewShellBase--exist only to be
used by the SFX as factories. They only set the initial pane
configuration, nothing more.
So what we do here in essence is to return on of the
ViewShellFactoryIds that can be used to select the factory that
creates the ViewShellBase subclass with the initial pane
configuration that has in the center pane a view shell of the same
type as mrViewShell.
*/
sal_uInt16 GetViewId (void);
private:
ViewShell& mrViewShell;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impress136_SRC680 (1.10.108); FILE MERGED 2007/12/05 12:44:49 af 1.10.108.1: #i73681# Added GetImageMapDialog() method.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ViewShellImplementation.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2008-01-28 14:56:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_VIEW_SHELL_IMPLEMENTATION_HXX
#define SD_VIEW_SHELL_IMPLEMENTATION_HXX
#include "ViewShell.hxx"
#include "ViewShellManager.hxx"
#include "ToolBarManager.hxx"
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <memory>
class SvxIMapDlg;
namespace sd {
class DrawController;
/** This class contains (will contain) the implementation of methods that
have not be accessible from the outside.
*/
class ViewShell::Implementation
{
public:
bool mbIsShowingUIControls;
bool mbIsMainViewShell;
/// Set to true when the ViewShell::Init() method has been called.
bool mbIsInitialized;
/** Set to true while ViewShell::ArrangeGUIElements() is being
executed. It is used as guard against recursive execution.
*/
bool mbArrangeActive;
/** Remember a link to the sub shell factory, so that it can be
unregistered at the ViewShellManager when a ViewShell is deleted.
*/
ViewShellManager::SharedShellFactory mpSubShellFactory;
/** This update lock for the ToolBarManager exists in order to avoid
problems with tool bars being displayed while the mouse button is
pressed. Whith docked tool bars this can lead to a size change of
the view. This would change the relative mouse coordinates and thus
interpret every mouse click as move command.
*/
class ToolBarManagerLock
{
public:
/** Create a new instance. This allows the mpSelf member to be set
automatically.
*/
static ::boost::shared_ptr<ToolBarManagerLock> Create (
const ::boost::shared_ptr<ToolBarManager>& rpManager);
/** Release the lock. When the UI is captured
(Application::IsUICaptured() returns <TRUE/>) then the lock is
released later asynchronously.
@param bForce
When this flag is <TRUE/> then the lock is released even
when IsUICaptured() returns <TRUE/>.
*/
void Release (bool bForce = false);
DECL_LINK(TimeoutCallback,Timer*);
private:
::std::auto_ptr<sd::ToolBarManager::UpdateLock> mpLock;
/** The timer is used both as a safe guard to unlock the update lock
when Release() is not called explicitly. It is also used to
defer the release of the lock to a time when the UI is not
captured.
*/
Timer maTimer;
/** The shared_ptr to this allows the ToolBarManagerLock to control
its own lifetime. This, of course, does work only when no one
holds another shared_ptr longer than only temporary.
*/
::boost::shared_ptr<ToolBarManagerLock> mpSelf;
ToolBarManagerLock (const ::boost::shared_ptr<ToolBarManager>& rpManager);
~ToolBarManagerLock (void);
class Deleter;
friend class Deleter;
};
// The member is not an auto_ptr because it takes over its own life time
// control.
::boost::weak_ptr<ToolBarManagerLock> mpUpdateLockForMouse;
Implementation (ViewShell& rViewShell);
~Implementation (void);
/** Process the SID_MODIFY slot.
*/
void ProcessModifyPageSlot (
SfxRequest& rRequest,
SdPage* pCurrentPage,
PageKind ePageKind);
/** Assign the given layout to the given page. This method is at the
moment merely a front end for ProcessModifyPageSlot.
@param pPage
If a NULL pointer is given then this call is ignored.
*/
void AssignLayout (
SdPage* pPage,
AutoLayout aLayout);
/** Determine the view id of the view shell. This corresponds to the
view id stored in the SfxViewFrame class.
We can not use the view of that class because with the introduction
of the multi pane GUI we do not switch the SfxViewShell anymore when
switching the view in the center pane. The view id of the
SfxViewFrame is thus not modified and we can not set it from the
outside.
The view id is still needed for the SFX to determine on start up
(e.g. after loading a document) which ViewShellBase sub class to
use. These sub classes--like OutlineViewShellBase--exist only to be
used by the SFX as factories. They only set the initial pane
configuration, nothing more.
So what we do here in essence is to return on of the
ViewShellFactoryIds that can be used to select the factory that
creates the ViewShellBase subclass with the initial pane
configuration that has in the center pane a view shell of the same
type as mrViewShell.
*/
sal_uInt16 GetViewId (void);
/** Return a pointer to the image map dialog that is displayed in some
child window.
@return
Returns <NULL/> when the image map dialog is not available.
*/
static SvxIMapDlg* GetImageMapDialog (void);
private:
ViewShell& mrViewShell;
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "MainUI.h"
#include "ui_MainUI.h"
#include "syntaxSupport.h"
#include <LuminaXDG.h>
#include <LuminaUtils.h>
#include <QFileDialog>
#include <QDir>
#include <QKeySequence>
#include <QTimer>
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
ui->setupUi(this);
settings = new QSettings("lumina-desktop","lumina-textedit");
Custom_Syntax::SetupDefaultColors(settings); //pre-load any color settings as needed
colorDLG = new ColorDialog(settings, this);
this->setWindowTitle(tr("Text Editor"));
ui->tabWidget->clear();
closeFindS = new QShortcut(QKeySequence(Qt::Key_Escape), this);
connect(closeFindS, SIGNAL(activated()), this, SLOT(closeFindReplace()) );
ui->groupReplace->setVisible(false);
//Update the menu of available syntax highlighting modes
QStringList smodes = Custom_Syntax::availableRules();
for(int i=0; i<smodes.length(); i++){
ui->menuSyntax_Highlighting->addAction(smodes[i]);
}
ui->actionLine_Numbers->setChecked( settings->value("showLineNumbers",true).toBool() );
ui->actionWrap_Lines->setChecked( settings->value("wrapLines",true).toBool() );
//Setup any connections
connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close()) );
connect(ui->actionNew_File, SIGNAL(triggered()), this, SLOT(NewFile()) );
connect(ui->actionOpen_File, SIGNAL(triggered()), this, SLOT(OpenFile()) );
connect(ui->actionClose_File, SIGNAL(triggered()), this, SLOT(CloseFile()) );
connect(ui->actionSave_File, SIGNAL(triggered()), this, SLOT(SaveFile()) );
connect(ui->actionSave_File_As, SIGNAL(triggered()), this, SLOT(SaveFileAs()) );
connect(ui->menuSyntax_Highlighting, SIGNAL(triggered(QAction*)), this, SLOT(UpdateHighlighting(QAction*)) );
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()) );
connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabClosed(int)) );
connect(ui->actionLine_Numbers, SIGNAL(toggled(bool)), this, SLOT(showLineNumbers(bool)) );
connect(ui->actionWrap_Lines, SIGNAL(toggled(bool)), this, SLOT(wrapLines(bool)) );
connect(ui->actionCustomize_Colors, SIGNAL(triggered()), this, SLOT(ModifyColors()) );
connect(ui->actionFind, SIGNAL(triggered()), this, SLOT(openFind()) );
connect(ui->actionReplace, SIGNAL(triggered()), this, SLOT(openReplace()) );
connect(ui->tool_find_next, SIGNAL(clicked()), this, SLOT(findNext()) );
connect(ui->tool_find_prev, SIGNAL(clicked()), this, SLOT(findPrev()) );
connect(ui->tool_replace, SIGNAL(clicked()), this, SLOT(replaceOne()) );
connect(ui->tool_replace_all, SIGNAL(clicked()), this, SLOT(replaceAll()) );
connect(ui->line_find, SIGNAL(returnPressed()), this, SLOT(findNext()) );
connect(ui->line_replace, SIGNAL(returnPressed()), this, SLOT(replaceOne()) );
connect(colorDLG, SIGNAL(colorsChanged()), this, SLOT(UpdateHighlighting()) );
updateIcons();
//Now load the initial size of the window
QSize lastSize = settings->value("lastSize",QSize()).toSize();
if(lastSize.width() > this->sizeHint().width() && lastSize.height() > this->sizeHint().height() ){
this->resize(lastSize);
}
}
MainUI::~MainUI(){
}
void MainUI::LoadArguments(QStringList args){ //CLI arguments
for(int i=0; i<args.length(); i++){
OpenFile( LUtils::PathToAbsolute(args[i]) );
ui->line_find->setFocus();
}
}
// =================
// PUBLIC SLOTS
//=================
void MainUI::updateIcons(){
this->setWindowIcon( LXDG::findIcon("document-edit") );
ui->actionClose->setIcon(LXDG::findIcon("application-exit") );
ui->actionNew_File->setIcon(LXDG::findIcon("document-new") );
ui->actionOpen_File->setIcon(LXDG::findIcon("document-open") );
ui->actionClose_File->setIcon(LXDG::findIcon("document-close") );
ui->actionSave_File->setIcon(LXDG::findIcon("document-save") );
ui->actionSave_File_As->setIcon(LXDG::findIcon("document-save-as") );
ui->actionFind->setIcon(LXDG::findIcon("edit-find") );
ui->actionReplace->setIcon(LXDG::findIcon("edit-find-replace") );
ui->menuSyntax_Highlighting->setIcon( LXDG::findIcon("format-text-color") );
ui->actionCustomize_Colors->setIcon( LXDG::findIcon("format-fill-color") );
//icons for the special find/replace groupbox
ui->tool_find_next->setIcon(LXDG::findIcon("go-down-search"));
ui->tool_find_prev->setIcon(LXDG::findIcon("go-up-search"));
ui->tool_find_casesensitive->setIcon(LXDG::findIcon("format-text-italic"));
ui->tool_replace->setIcon(LXDG::findIcon("arrow-down"));
ui->tool_replace_all->setIcon(LXDG::findIcon("arrow-down-double"));
//ui->tool_find_next->setIcon(LXDG::findIcon(""));
QTimer::singleShot(0,colorDLG, SLOT(updateIcons()) );
}
// =================
// PRIVATE
//=================
PlainTextEditor* MainUI::currentEditor(){
if(ui->tabWidget->count()<1){ return 0; }
return static_cast<PlainTextEditor*>( ui->tabWidget->currentWidget() );
}
QString MainUI::currentFileDir(){
PlainTextEditor* cur = currentEditor();
QString dir;
if(cur!=0){
if(cur->currentFile().startsWith("/")){
dir = cur->currentFile().section("/",0,-2);
}
}
return dir;
}
// =================
// PRIVATE SLOTS
//=================
//Main Actions
void MainUI::NewFile(){
OpenFile(QString::number(ui->tabWidget->count()+1)+"/"+tr("New File"));
}
void MainUI::OpenFile(QString file){
QStringList files;
if(file.isEmpty()){
//Prompt for a file to open
files = QFileDialog::getOpenFileNames(this, tr("Open File(s)"), currentFileDir(), tr("Text Files (*)") );
if(files.isEmpty()){ return; } //cancelled
}else{
files << file;
}
for(int i=0; i<files.length(); i++){
PlainTextEditor *edit = new PlainTextEditor(settings, this);
connect(edit, SIGNAL(FileLoaded(QString)), this, SLOT(updateTab(QString)) );
connect(edit, SIGNAL(UnsavedChanges(QString)), this, SLOT(updateTab(QString)) );
ui->tabWidget->addTab(edit, files[i].section("/",-1));
edit->showLineNumbers(ui->actionLine_Numbers->isChecked());
edit->setLineWrapMode( ui->actionWrap_Lines->isChecked() ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
edit->setFocusPolicy(Qt::ClickFocus); //no "tabbing" into this widget
ui->tabWidget->setCurrentWidget(edit);
edit->LoadFile(files[i]);
edit->setFocus();
QApplication::processEvents(); //to catch the fileLoaded() signal
}
}
void MainUI::CloseFile(){
int index = ui->tabWidget->currentIndex();
if(index>=0){ tabClosed(index); }
}
void MainUI::SaveFile(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->SaveFile();
}
void MainUI::SaveFileAs(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->SaveFile(true);
}
void MainUI::UpdateHighlighting(QAction *act){
if(act!=0){
//Single-editor change
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->LoadSyntaxRule(act->text());
}else{
//Have every editor reload the syntax rules (color changes)
for(int i=0; i<ui->tabWidget->count(); i++){
static_cast<PlainTextEditor*>(ui->tabWidget->widget(i))->updateSyntaxColors();
}
}
}
void MainUI::showLineNumbers(bool show){
settings->setValue("showLineNumbers",show);
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
edit->showLineNumbers(show);
}
}
void MainUI::wrapLines(bool wrap){
settings->setValue("wrapLines",wrap);
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
edit->setLineWrapMode( wrap ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
}
}
void MainUI::ModifyColors(){
colorDLG->LoadColors();
colorDLG->showNormal();
}
void MainUI::updateTab(QString file){
PlainTextEditor *cur = 0;
int index = -1;
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *tmp = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
if(tmp->currentFile()==file){
cur = tmp;
index = i;
break;
}
}
if(cur==0){ return; } //should never happen
bool changes = cur->hasChange();
//qDebug() << "Update Tab:" << file << cur << changes;
ui->tabWidget->setTabText(index,(changes ? "*" : "") + file.section("/",-1));
ui->actionSave_File->setEnabled(changes);
ui->actionSave_File_As->setEnabled(changes);
this->setWindowTitle( ui->tabWidget->tabText( ui->tabWidget->currentIndex() ) );
}
void MainUI::tabChanged(){
//update the buttons/menus based on the current widget
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; } //should never happen though
bool changes = cur->hasChange();
ui->actionSave_File->setEnabled(changes);
ui->actionSave_File_As->setEnabled(changes);
this->setWindowTitle( ui->tabWidget->tabText( ui->tabWidget->currentIndex() ) );
if(!ui->line_find->hasFocus() && !ui->line_replace->hasFocus()){ ui->tabWidget->currentWidget()->setFocus(); }
}
void MainUI::tabClosed(int tab){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(tab));
if(edit==0){ return; } //should never happen
if(edit->hasChange()){
//Verify if the user wants to lose any unsaved changes
}
ui->tabWidget->removeTab(tab);
edit->deleteLater();
}
//Find/Replace functions
void MainUI::closeFindReplace(){
ui->groupReplace->setVisible(false);
PlainTextEditor *cur = currentEditor();
if(cur!=0){ cur->setFocus(); }
}
void MainUI::openFind(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
ui->groupReplace->setVisible(true);
ui->line_find->setText( cur->textCursor().selectedText() );
ui->line_replace->setText("");
ui->line_find->setFocus();
}
void MainUI::openReplace(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
ui->groupReplace->setVisible(true);
ui->line_find->setText( cur->textCursor().selectedText() );
ui->line_replace->setText("");
ui->line_replace->setFocus();
}
void MainUI::findNext(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
if(!found){
//Try starting back at the top of the file
cur->moveCursor(QTextCursor::Start);
cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
}
}
void MainUI::findPrev(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively | QTextDocument::FindBackward : QTextDocument::FindBackward );
if(!found){
//Try starting back at the bottom of the file
cur->moveCursor(QTextCursor::End);
cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively | QTextDocument::FindBackward : QTextDocument::FindBackward );
}
}
void MainUI::replaceOne(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
//See if the current selection matches the find field first
bool done = false;
if(cur->textCursor().selectedText()==ui->line_find->text()){
cur->insertPlainText(ui->line_replace->text());
done = true;
}else{
//Find/replace the next occurance of the string
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
if(found){ cur->insertPlainText(ui->line_replace->text()); done = true;}
}
if(done){
//Re-highlight the newly-inserted text
cur->find( ui->line_replace->text(), QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);
}
}
void MainUI::replaceAll(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
//See if the current selection matches the find field first
bool done = false;
if(cur->textCursor().selectedText()==ui->line_find->text()){
cur->insertPlainText(ui->line_replace->text());
done = true;
}
while( cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() ) ){
//Find/replace every occurance of the string
cur->insertPlainText(ui->line_replace->text());
done = true;
}
if(done){
//Re-highlight the newly-inserted text
cur->find( ui->line_replace->text(), QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);
}
}
<commit_msg>Adjust the single-replace logic in lumina-textedit. Have it replace the current selection match, and find the next one (don't replace the next one until the user can see it highlighted first).<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2015, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "MainUI.h"
#include "ui_MainUI.h"
#include "syntaxSupport.h"
#include <LuminaXDG.h>
#include <LuminaUtils.h>
#include <QFileDialog>
#include <QDir>
#include <QKeySequence>
#include <QTimer>
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
ui->setupUi(this);
settings = new QSettings("lumina-desktop","lumina-textedit");
Custom_Syntax::SetupDefaultColors(settings); //pre-load any color settings as needed
colorDLG = new ColorDialog(settings, this);
this->setWindowTitle(tr("Text Editor"));
ui->tabWidget->clear();
closeFindS = new QShortcut(QKeySequence(Qt::Key_Escape), this);
connect(closeFindS, SIGNAL(activated()), this, SLOT(closeFindReplace()) );
ui->groupReplace->setVisible(false);
//Update the menu of available syntax highlighting modes
QStringList smodes = Custom_Syntax::availableRules();
for(int i=0; i<smodes.length(); i++){
ui->menuSyntax_Highlighting->addAction(smodes[i]);
}
ui->actionLine_Numbers->setChecked( settings->value("showLineNumbers",true).toBool() );
ui->actionWrap_Lines->setChecked( settings->value("wrapLines",true).toBool() );
//Setup any connections
connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close()) );
connect(ui->actionNew_File, SIGNAL(triggered()), this, SLOT(NewFile()) );
connect(ui->actionOpen_File, SIGNAL(triggered()), this, SLOT(OpenFile()) );
connect(ui->actionClose_File, SIGNAL(triggered()), this, SLOT(CloseFile()) );
connect(ui->actionSave_File, SIGNAL(triggered()), this, SLOT(SaveFile()) );
connect(ui->actionSave_File_As, SIGNAL(triggered()), this, SLOT(SaveFileAs()) );
connect(ui->menuSyntax_Highlighting, SIGNAL(triggered(QAction*)), this, SLOT(UpdateHighlighting(QAction*)) );
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()) );
connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabClosed(int)) );
connect(ui->actionLine_Numbers, SIGNAL(toggled(bool)), this, SLOT(showLineNumbers(bool)) );
connect(ui->actionWrap_Lines, SIGNAL(toggled(bool)), this, SLOT(wrapLines(bool)) );
connect(ui->actionCustomize_Colors, SIGNAL(triggered()), this, SLOT(ModifyColors()) );
connect(ui->actionFind, SIGNAL(triggered()), this, SLOT(openFind()) );
connect(ui->actionReplace, SIGNAL(triggered()), this, SLOT(openReplace()) );
connect(ui->tool_find_next, SIGNAL(clicked()), this, SLOT(findNext()) );
connect(ui->tool_find_prev, SIGNAL(clicked()), this, SLOT(findPrev()) );
connect(ui->tool_replace, SIGNAL(clicked()), this, SLOT(replaceOne()) );
connect(ui->tool_replace_all, SIGNAL(clicked()), this, SLOT(replaceAll()) );
connect(ui->line_find, SIGNAL(returnPressed()), this, SLOT(findNext()) );
connect(ui->line_replace, SIGNAL(returnPressed()), this, SLOT(replaceOne()) );
connect(colorDLG, SIGNAL(colorsChanged()), this, SLOT(UpdateHighlighting()) );
updateIcons();
//Now load the initial size of the window
QSize lastSize = settings->value("lastSize",QSize()).toSize();
if(lastSize.width() > this->sizeHint().width() && lastSize.height() > this->sizeHint().height() ){
this->resize(lastSize);
}
}
MainUI::~MainUI(){
}
void MainUI::LoadArguments(QStringList args){ //CLI arguments
for(int i=0; i<args.length(); i++){
OpenFile( LUtils::PathToAbsolute(args[i]) );
ui->line_find->setFocus();
}
}
// =================
// PUBLIC SLOTS
//=================
void MainUI::updateIcons(){
this->setWindowIcon( LXDG::findIcon("document-edit") );
ui->actionClose->setIcon(LXDG::findIcon("application-exit") );
ui->actionNew_File->setIcon(LXDG::findIcon("document-new") );
ui->actionOpen_File->setIcon(LXDG::findIcon("document-open") );
ui->actionClose_File->setIcon(LXDG::findIcon("document-close") );
ui->actionSave_File->setIcon(LXDG::findIcon("document-save") );
ui->actionSave_File_As->setIcon(LXDG::findIcon("document-save-as") );
ui->actionFind->setIcon(LXDG::findIcon("edit-find") );
ui->actionReplace->setIcon(LXDG::findIcon("edit-find-replace") );
ui->menuSyntax_Highlighting->setIcon( LXDG::findIcon("format-text-color") );
ui->actionCustomize_Colors->setIcon( LXDG::findIcon("format-fill-color") );
//icons for the special find/replace groupbox
ui->tool_find_next->setIcon(LXDG::findIcon("go-down-search"));
ui->tool_find_prev->setIcon(LXDG::findIcon("go-up-search"));
ui->tool_find_casesensitive->setIcon(LXDG::findIcon("format-text-italic"));
ui->tool_replace->setIcon(LXDG::findIcon("arrow-down"));
ui->tool_replace_all->setIcon(LXDG::findIcon("arrow-down-double"));
//ui->tool_find_next->setIcon(LXDG::findIcon(""));
QTimer::singleShot(0,colorDLG, SLOT(updateIcons()) );
}
// =================
// PRIVATE
//=================
PlainTextEditor* MainUI::currentEditor(){
if(ui->tabWidget->count()<1){ return 0; }
return static_cast<PlainTextEditor*>( ui->tabWidget->currentWidget() );
}
QString MainUI::currentFileDir(){
PlainTextEditor* cur = currentEditor();
QString dir;
if(cur!=0){
if(cur->currentFile().startsWith("/")){
dir = cur->currentFile().section("/",0,-2);
}
}
return dir;
}
// =================
// PRIVATE SLOTS
//=================
//Main Actions
void MainUI::NewFile(){
OpenFile(QString::number(ui->tabWidget->count()+1)+"/"+tr("New File"));
}
void MainUI::OpenFile(QString file){
QStringList files;
if(file.isEmpty()){
//Prompt for a file to open
files = QFileDialog::getOpenFileNames(this, tr("Open File(s)"), currentFileDir(), tr("Text Files (*)") );
if(files.isEmpty()){ return; } //cancelled
}else{
files << file;
}
for(int i=0; i<files.length(); i++){
PlainTextEditor *edit = new PlainTextEditor(settings, this);
connect(edit, SIGNAL(FileLoaded(QString)), this, SLOT(updateTab(QString)) );
connect(edit, SIGNAL(UnsavedChanges(QString)), this, SLOT(updateTab(QString)) );
ui->tabWidget->addTab(edit, files[i].section("/",-1));
edit->showLineNumbers(ui->actionLine_Numbers->isChecked());
edit->setLineWrapMode( ui->actionWrap_Lines->isChecked() ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
edit->setFocusPolicy(Qt::ClickFocus); //no "tabbing" into this widget
ui->tabWidget->setCurrentWidget(edit);
edit->LoadFile(files[i]);
edit->setFocus();
QApplication::processEvents(); //to catch the fileLoaded() signal
}
}
void MainUI::CloseFile(){
int index = ui->tabWidget->currentIndex();
if(index>=0){ tabClosed(index); }
}
void MainUI::SaveFile(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->SaveFile();
}
void MainUI::SaveFileAs(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->SaveFile(true);
}
void MainUI::UpdateHighlighting(QAction *act){
if(act!=0){
//Single-editor change
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
cur->LoadSyntaxRule(act->text());
}else{
//Have every editor reload the syntax rules (color changes)
for(int i=0; i<ui->tabWidget->count(); i++){
static_cast<PlainTextEditor*>(ui->tabWidget->widget(i))->updateSyntaxColors();
}
}
}
void MainUI::showLineNumbers(bool show){
settings->setValue("showLineNumbers",show);
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
edit->showLineNumbers(show);
}
}
void MainUI::wrapLines(bool wrap){
settings->setValue("wrapLines",wrap);
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
edit->setLineWrapMode( wrap ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap);
}
}
void MainUI::ModifyColors(){
colorDLG->LoadColors();
colorDLG->showNormal();
}
void MainUI::updateTab(QString file){
PlainTextEditor *cur = 0;
int index = -1;
for(int i=0; i<ui->tabWidget->count(); i++){
PlainTextEditor *tmp = static_cast<PlainTextEditor*>(ui->tabWidget->widget(i));
if(tmp->currentFile()==file){
cur = tmp;
index = i;
break;
}
}
if(cur==0){ return; } //should never happen
bool changes = cur->hasChange();
//qDebug() << "Update Tab:" << file << cur << changes;
ui->tabWidget->setTabText(index,(changes ? "*" : "") + file.section("/",-1));
ui->actionSave_File->setEnabled(changes);
ui->actionSave_File_As->setEnabled(changes);
this->setWindowTitle( ui->tabWidget->tabText( ui->tabWidget->currentIndex() ) );
}
void MainUI::tabChanged(){
//update the buttons/menus based on the current widget
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; } //should never happen though
bool changes = cur->hasChange();
ui->actionSave_File->setEnabled(changes);
ui->actionSave_File_As->setEnabled(changes);
this->setWindowTitle( ui->tabWidget->tabText( ui->tabWidget->currentIndex() ) );
if(!ui->line_find->hasFocus() && !ui->line_replace->hasFocus()){ ui->tabWidget->currentWidget()->setFocus(); }
}
void MainUI::tabClosed(int tab){
PlainTextEditor *edit = static_cast<PlainTextEditor*>(ui->tabWidget->widget(tab));
if(edit==0){ return; } //should never happen
if(edit->hasChange()){
//Verify if the user wants to lose any unsaved changes
}
ui->tabWidget->removeTab(tab);
edit->deleteLater();
}
//Find/Replace functions
void MainUI::closeFindReplace(){
ui->groupReplace->setVisible(false);
PlainTextEditor *cur = currentEditor();
if(cur!=0){ cur->setFocus(); }
}
void MainUI::openFind(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
ui->groupReplace->setVisible(true);
ui->line_find->setText( cur->textCursor().selectedText() );
ui->line_replace->setText("");
ui->line_find->setFocus();
}
void MainUI::openReplace(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
ui->groupReplace->setVisible(true);
ui->line_find->setText( cur->textCursor().selectedText() );
ui->line_replace->setText("");
ui->line_replace->setFocus();
}
void MainUI::findNext(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
if(!found){
//Try starting back at the top of the file
cur->moveCursor(QTextCursor::Start);
cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
}
}
void MainUI::findPrev(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively | QTextDocument::FindBackward : QTextDocument::FindBackward );
if(!found){
//Try starting back at the bottom of the file
cur->moveCursor(QTextCursor::End);
cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively | QTextDocument::FindBackward : QTextDocument::FindBackward );
}
}
void MainUI::replaceOne(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
//See if the current selection matches the find field first
bool done = false;
if(cur->textCursor().selectedText()==ui->line_find->text()){
cur->insertPlainText(ui->line_replace->text());
//done = true;
}//else{
//Find/replace the next occurance of the string
bool found = cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() );
//if(found){ cur->insertPlainText(ui->line_replace->text()); done = true;}
//}
/*if(done){
//Re-highlight the newly-inserted text
cur->find( ui->line_replace->text(), QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);
}*/
}
void MainUI::replaceAll(){
PlainTextEditor *cur = currentEditor();
if(cur==0){ return; }
//See if the current selection matches the find field first
bool done = false;
if(cur->textCursor().selectedText()==ui->line_find->text()){
cur->insertPlainText(ui->line_replace->text());
done = true;
}
while( cur->find( ui->line_find->text(), ui->tool_find_casesensitive->isChecked() ? QTextDocument::FindCaseSensitively : QTextDocument::FindFlags() ) ){
//Find/replace every occurance of the string
cur->insertPlainText(ui->line_replace->text());
done = true;
}
if(done){
//Re-highlight the newly-inserted text
cur->find( ui->line_replace->text(), QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);
}
}
<|endoftext|> |
<commit_before>#include <allheaders.h>
#include <tesseract/baseapi.h>
#include <libgen.h> // for dirname
#include <cstdio> // for printf
#include <cstdlib> // for std::getenv, std::setenv
#include <string> // for std::string
#ifndef TESSERACT_FUZZER_WIDTH
# define TESSERACT_FUZZER_WIDTH 100
#endif
#ifndef TESSERACT_FUZZER_HEIGHT
# define TESSERACT_FUZZER_HEIGHT 100
#endif
class BitReader {
private:
uint8_t const *data;
size_t size;
size_t shift;
public:
BitReader(const uint8_t *data, size_t size) : data(data), size(size), shift(0) {}
int Read(void) {
if (size == 0) {
return 0;
}
const int ret = ((*data) >> shift) & 1;
shift++;
if (shift >= 8) {
shift = 0;
data++;
size--;
}
return ret;
}
};
static tesseract::TessBaseAPI *api = nullptr;
extern "C" int LLVMFuzzerInitialize(int * /*pArgc*/, char ***pArgv) {
if (std::getenv("TESSDATA_PREFIX") == nullptr) {
std::string binary_path = *pArgv[0];
const std::string filepath = dirname(&binary_path[0]);
const std::string tessdata_path = filepath + "/" + "tessdata";
if (setenv("TESSDATA_PREFIX", tessdata_path.c_str(), 1) != 0) {
printf("Setenv failed\n");
std::abort();
}
}
api = new tesseract::TessBaseAPI();
if (api->Init(nullptr, "eng") != 0) {
printf("Cannot initialize API\n");
abort();
}
/* Silence output */
api->SetVariable("debug_file", "/dev/null");
return 0;
}
static PIX *createPix(BitReader &BR, const size_t width, const size_t height) {
Image pix = pixCreate(width, height, 1);
if (pix == nullptr) {
printf("pix creation failed\n");
abort();
}
for (size_t i = 0; i < width; i++) {
for (size_t j = 0; j < height; j++) {
pixSetPixel(pix, i, j, BR.Read());
}
}
return pix;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
BitReader BR(data, size);
auto pix = createPix(BR, TESSERACT_FUZZER_WIDTH, TESSERACT_FUZZER_HEIGHT);
api->SetImage(pix);
char *outText = api->GetUTF8Text();
pix.destroy();
delete[] outText;
return 0;
}
<commit_msg>Fix broken build for fuzzer<commit_after>#include <allheaders.h>
#include <tesseract/baseapi.h>
#include <libgen.h> // for dirname
#include <cstdio> // for printf
#include <cstdlib> // for std::getenv, std::setenv
#include <string> // for std::string
#ifndef TESSERACT_FUZZER_WIDTH
# define TESSERACT_FUZZER_WIDTH 100
#endif
#ifndef TESSERACT_FUZZER_HEIGHT
# define TESSERACT_FUZZER_HEIGHT 100
#endif
class BitReader {
private:
uint8_t const *data;
size_t size;
size_t shift;
public:
BitReader(const uint8_t *data, size_t size) : data(data), size(size), shift(0) {}
int Read(void) {
if (size == 0) {
return 0;
}
const int ret = ((*data) >> shift) & 1;
shift++;
if (shift >= 8) {
shift = 0;
data++;
size--;
}
return ret;
}
};
static tesseract::TessBaseAPI *api = nullptr;
extern "C" int LLVMFuzzerInitialize(int * /*pArgc*/, char ***pArgv) {
if (std::getenv("TESSDATA_PREFIX") == nullptr) {
std::string binary_path = *pArgv[0];
const std::string filepath = dirname(&binary_path[0]);
const std::string tessdata_path = filepath + "/" + "tessdata";
if (setenv("TESSDATA_PREFIX", tessdata_path.c_str(), 1) != 0) {
printf("Setenv failed\n");
std::abort();
}
}
api = new tesseract::TessBaseAPI();
if (api->Init(nullptr, "eng") != 0) {
printf("Cannot initialize API\n");
abort();
}
/* Silence output */
api->SetVariable("debug_file", "/dev/null");
return 0;
}
static PIX *createPix(BitReader &BR, const size_t width, const size_t height) {
Pix *pix = pixCreate(width, height, 1);
if (pix == nullptr) {
printf("pix creation failed\n");
abort();
}
for (size_t i = 0; i < width; i++) {
for (size_t j = 0; j < height; j++) {
pixSetPixel(pix, i, j, BR.Read());
}
}
return pix;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
BitReader BR(data, size);
auto pix = createPix(BR, TESSERACT_FUZZER_WIDTH, TESSERACT_FUZZER_HEIGHT);
api->SetImage(pix);
char *outText = api->GetUTF8Text();
pixDestroy(&pix);
delete[] outText;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <unistd.h>
#include "io.h"
#include "bpmf.h"
using namespace std;
using namespace Eigen;
#ifdef BPMF_HYBRID_COMM
#define BPMF_GPI_COMM
#define BPMF_MPI_COMM
#endif
#ifdef BPMF_GPI_COMM
#include "gaspi.h"
#elif defined(BPMF_MPI_PUT_COMM)
#define BPMF_MPI_COMM
#include "mpi_put.h"
#elif defined(BPMF_MPI_BCAST_COMM)
#define BPMF_MPI_COMM
#include "mpi_bcast.h"
#elif defined(BPMF_MPI_ISENDIRECV_COMM)
#define BPMF_MPI_COMM
#include "mpi_isendirecv.h"
#elif defined(BPMF_NO_COMM)
#include "nocomm.h"
#else
#error no comm include
#endif
void usage()
{
std::cout << "Usage: bpmf -n <MTX> -p <MTX> [-o DIR/] [-i N] [-b N] [-f N] [-krv] [-t N] [-m MTX,MTX] [-l MTX,MTX]\n"
<< "\n"
<< "Paramaters: \n"
<< " -n MTX: Training input data\n"
<< " -p MTX: Test input data\n"
<< " [-o DIR]: Output directory for model and predictions\n"
<< " [-i N]: Number of total iterations\n"
<< " [-b N]: Number of burnin iterations\n"
<< " [-f N]: Frequency to send model other nodes (in #iters)\n"
<< " [-a F]: Noise precision (alpha)\n"
<< "\n"
<< " [-k]: Do not optimize item to node assignment\n"
<< " [-r]: Redirect stdout to file\n"
<< " [-v]: Output all samples\n"
<< " [-t N]: Number of OpenMP threads to use.\n"
<< "\n"
<< "Matrix Formats:\n"
<< " *.mtx: Sparse or dense Matrix Market format\n"
<< " *.sdm: Sparse binary double format\n"
<< " *.ddm: Dense binary double format\n"
<< std::endl;
}
int main(int argc, char *argv[])
{
Sys::Init();
{
int ch;
string fname, probename;
string mname, lname;
int nthrds = -1;
bool redirect = false;
Sys::nsims = 20;
Sys::burnin = 5;
Sys::update_freq = 1;
Sys::grain_size = 1;
while((ch = getopt(argc, argv, "krvn:t:p:i:b:f:g:w:u:v:o:s:m:l:a:d:")) != -1)
{
switch(ch)
{
case 'i': Sys::nsims = atoi(optarg); break;
case 'b': Sys::burnin = atoi(optarg); break;
case 'f': Sys::update_freq = atoi(optarg); break;
case 'g': Sys::grain_size = atoi(optarg); break;
case 't': nthrds = atoi(optarg); break;
case 'a': Sys::alpha = atof(optarg); break;
case 'd': assert(num_latent == atoi(optarg)); break;
case 'n': fname = optarg; break;
case 'p': probename = optarg; break;
//output directory matrices
case 'o': Sys::odirname = optarg; break;
case 'm': mname = optarg; break;
case 'l': lname = optarg; break;
case 'r': redirect = true; break;
case 'k': Sys::permute = false; break;
case 'v': Sys::verbose = true; break;
case '?':
case 'h':
default : usage(); Sys::Abort(1);
}
}
if (Sys::nprocs >1 || redirect) {
std::stringstream ofname;
ofname << "bpmf_" << Sys::procid << ".out";
Sys::os = new std::ofstream(ofname.str());
} else {
Sys::os = &std::cout;
}
if (fname.empty() || probename.empty()) {
usage();
Sys::Abort(1);
}
SYS movies("movs", fname, probename);
SYS users("users", movies.M, movies.Pavg);
movies.alloc_and_init();
users.alloc_and_init();
// assign users and movies to the computation nodes
movies.assign(users);
users.assign(movies);
movies.assign(users);
users.assign(movies);
// build connectivity matrix
// contains what items needs to go to what nodes
users.build_conn(movies);
movies.build_conn(users);
assert(movies.nnz() == users.nnz());
threads::init(nthrds);
long double average_items_sec = .0;
long double average_ratings_sec = .0;
char name[1024];
gethostname(name, 1024);
Sys::cout() << "hostname: " << name << endl;
Sys::cout() << "pid: " << getpid() << endl;
if (getenv("PBS_JOBID")) Sys::cout() << "jobid: " << getenv("PBS_JOBID") << endl;
if(Sys::procid == 0)
{
Sys::cout() << "num_latent: " << num_latent<<endl;
Sys::cout() << "nprocs: " << Sys::nprocs << endl;
Sys::cout() << "nthrds: " << threads::get_max_threads() << endl;
Sys::cout() << "nsims: " << Sys::nsims << endl;
Sys::cout() << "burnin: " << Sys::burnin << endl;
Sys::cout() << "grain_size: " << Sys::grain_size << endl;
Sys::cout() << "alpha: " << Sys::alpha << endl;
}
Sys::sync();
auto begin = tick();
for(int i=0; i<Sys::nsims; ++i) {
BPMF_COUNTER("main");
auto start = tick();
{
BPMF_COUNTER("movies");
movies.sample_hp();
movies.sample(users);
}
{
BPMF_COUNTER("users");
users.sample_hp();
users.sample(movies);
}
{
BPMF_COUNTER("eval");
movies.predict(users);
users.predict(movies);
}
auto stop = tick();
double items_per_sec = (users.num() + movies.num()) / (stop - start);
double ratings_per_sec = (users.nnz()) / (stop - start);
movies.print(items_per_sec, ratings_per_sec, sqrt(users.aggr_norm()), sqrt(movies.aggr_norm()));
average_items_sec += items_per_sec;
average_ratings_sec += ratings_per_sec;
if (Sys::verbose)
{
users.bcast();
write_matrix(Sys::odirname + "/U-" + std::to_string(i) + ".ddm", users.items());
movies.bcast();
write_matrix(Sys::odirname + "/V-" + std::to_string(i) + ".ddm", movies.items());
}
}
Sys::sync();
auto end = tick();
auto elapsed = end - begin;
//-- if we need to generate output files, collect all data on proc 0
if (Sys::odirname.size()) {
users.bcast();
movies.bcast();
movies.predict(users, true);
// restore original order
users.unpermuteCols(movies);
movies.unpermuteCols(users);
if (Sys::procid == 0) {
// sparse
write_matrix(Sys::odirname + "/Pavg.sdm", movies.Pavg);
write_matrix(Sys::odirname + "/Pm2.sdm", movies.Pm2);
}
}
if (Sys::procid == 0) {
Sys::cout() << "Total time: " << elapsed <<endl <<flush;
Sys::cout() << "Final Avg RMSE: " << movies.rmse_avg <<endl <<flush;
Sys::cout() << "Average items/sec: " << average_items_sec / movies.iter << endl <<flush;
Sys::cout() << "Average ratings/sec: " << average_ratings_sec / movies.iter << endl <<flush;
}
}
Sys::Finalize();
if (Sys::nprocs >1) delete Sys::os;
return 0;
}
void Sys::bcast()
{
for(int i = 0; i < num(); i++) {
#ifdef BPMF_MPI_COMM
MPI_Bcast(items().col(i).data(), num_latent, MPI_DOUBLE, proc(i), MPI_COMM_WORLD);
#else
assert(Sys::nprocs == 1);
#endif
}
}
<commit_msg>FIX: only write_matrix from proc==0<commit_after>/*
* Copyright (c) 2014-2016, imec
* All rights reserved.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <random>
#include <unistd.h>
#include "io.h"
#include "bpmf.h"
using namespace std;
using namespace Eigen;
#ifdef BPMF_HYBRID_COMM
#define BPMF_GPI_COMM
#define BPMF_MPI_COMM
#endif
#ifdef BPMF_GPI_COMM
#include "gaspi.h"
#elif defined(BPMF_MPI_PUT_COMM)
#define BPMF_MPI_COMM
#include "mpi_put.h"
#elif defined(BPMF_MPI_BCAST_COMM)
#define BPMF_MPI_COMM
#include "mpi_bcast.h"
#elif defined(BPMF_MPI_ISENDIRECV_COMM)
#define BPMF_MPI_COMM
#include "mpi_isendirecv.h"
#elif defined(BPMF_NO_COMM)
#include "nocomm.h"
#else
#error no comm include
#endif
void usage()
{
std::cout << "Usage: bpmf -n <MTX> -p <MTX> [-o DIR/] [-i N] [-b N] [-f N] [-krv] [-t N] [-m MTX,MTX] [-l MTX,MTX]\n"
<< "\n"
<< "Paramaters: \n"
<< " -n MTX: Training input data\n"
<< " -p MTX: Test input data\n"
<< " [-o DIR]: Output directory for model and predictions\n"
<< " [-i N]: Number of total iterations\n"
<< " [-b N]: Number of burnin iterations\n"
<< " [-f N]: Frequency to send model other nodes (in #iters)\n"
<< " [-a F]: Noise precision (alpha)\n"
<< "\n"
<< " [-k]: Do not optimize item to node assignment\n"
<< " [-r]: Redirect stdout to file\n"
<< " [-v]: Output all samples\n"
<< " [-t N]: Number of OpenMP threads to use.\n"
<< "\n"
<< "Matrix Formats:\n"
<< " *.mtx: Sparse or dense Matrix Market format\n"
<< " *.sdm: Sparse binary double format\n"
<< " *.ddm: Dense binary double format\n"
<< std::endl;
}
int main(int argc, char *argv[])
{
Sys::Init();
{
int ch;
string fname, probename;
string mname, lname;
int nthrds = -1;
bool redirect = false;
Sys::nsims = 20;
Sys::burnin = 5;
Sys::update_freq = 1;
Sys::grain_size = 1;
while((ch = getopt(argc, argv, "krvn:t:p:i:b:f:g:w:u:v:o:s:m:l:a:d:")) != -1)
{
switch(ch)
{
case 'i': Sys::nsims = atoi(optarg); break;
case 'b': Sys::burnin = atoi(optarg); break;
case 'f': Sys::update_freq = atoi(optarg); break;
case 'g': Sys::grain_size = atoi(optarg); break;
case 't': nthrds = atoi(optarg); break;
case 'a': Sys::alpha = atof(optarg); break;
case 'd': assert(num_latent == atoi(optarg)); break;
case 'n': fname = optarg; break;
case 'p': probename = optarg; break;
//output directory matrices
case 'o': Sys::odirname = optarg; break;
case 'm': mname = optarg; break;
case 'l': lname = optarg; break;
case 'r': redirect = true; break;
case 'k': Sys::permute = false; break;
case 'v': Sys::verbose = true; break;
case '?':
case 'h':
default : usage(); Sys::Abort(1);
}
}
if (Sys::nprocs >1 || redirect) {
std::stringstream ofname;
ofname << "bpmf_" << Sys::procid << ".out";
Sys::os = new std::ofstream(ofname.str());
} else {
Sys::os = &std::cout;
}
if (fname.empty() || probename.empty()) {
usage();
Sys::Abort(1);
}
SYS movies("movs", fname, probename);
SYS users("users", movies.M, movies.Pavg);
movies.alloc_and_init();
users.alloc_and_init();
// assign users and movies to the computation nodes
movies.assign(users);
users.assign(movies);
movies.assign(users);
users.assign(movies);
// build connectivity matrix
// contains what items needs to go to what nodes
users.build_conn(movies);
movies.build_conn(users);
assert(movies.nnz() == users.nnz());
threads::init(nthrds);
long double average_items_sec = .0;
long double average_ratings_sec = .0;
char name[1024];
gethostname(name, 1024);
Sys::cout() << "hostname: " << name << endl;
Sys::cout() << "pid: " << getpid() << endl;
if (getenv("PBS_JOBID")) Sys::cout() << "jobid: " << getenv("PBS_JOBID") << endl;
if(Sys::procid == 0)
{
Sys::cout() << "num_latent: " << num_latent<<endl;
Sys::cout() << "nprocs: " << Sys::nprocs << endl;
Sys::cout() << "nthrds: " << threads::get_max_threads() << endl;
Sys::cout() << "nsims: " << Sys::nsims << endl;
Sys::cout() << "burnin: " << Sys::burnin << endl;
Sys::cout() << "grain_size: " << Sys::grain_size << endl;
Sys::cout() << "alpha: " << Sys::alpha << endl;
}
Sys::sync();
auto begin = tick();
for(int i=0; i<Sys::nsims; ++i) {
BPMF_COUNTER("main");
auto start = tick();
{
BPMF_COUNTER("movies");
movies.sample_hp();
movies.sample(users);
}
{
BPMF_COUNTER("users");
users.sample_hp();
users.sample(movies);
}
{
BPMF_COUNTER("eval");
movies.predict(users);
users.predict(movies);
}
auto stop = tick();
double items_per_sec = (users.num() + movies.num()) / (stop - start);
double ratings_per_sec = (users.nnz()) / (stop - start);
movies.print(items_per_sec, ratings_per_sec, sqrt(users.aggr_norm()), sqrt(movies.aggr_norm()));
average_items_sec += items_per_sec;
average_ratings_sec += ratings_per_sec;
if (Sys::verbose)
{
users.bcast();
movies.bcast();
if (Sys::procid == 0)
{
write_matrix(Sys::odirname + "/U-" + std::to_string(i) + ".ddm", users.items());
write_matrix(Sys::odirname + "/V-" + std::to_string(i) + ".ddm", movies.items());
}
}
}
Sys::sync();
auto end = tick();
auto elapsed = end - begin;
//-- if we need to generate output files, collect all data on proc 0
if (Sys::odirname.size()) {
users.bcast();
movies.bcast();
movies.predict(users, true);
// restore original order
users.unpermuteCols(movies);
movies.unpermuteCols(users);
if (Sys::procid == 0) {
// sparse
write_matrix(Sys::odirname + "/Pavg.sdm", movies.Pavg);
write_matrix(Sys::odirname + "/Pm2.sdm", movies.Pm2);
}
}
if (Sys::procid == 0) {
Sys::cout() << "Total time: " << elapsed <<endl <<flush;
Sys::cout() << "Final Avg RMSE: " << movies.rmse_avg <<endl <<flush;
Sys::cout() << "Average items/sec: " << average_items_sec / movies.iter << endl <<flush;
Sys::cout() << "Average ratings/sec: " << average_ratings_sec / movies.iter << endl <<flush;
}
}
Sys::Finalize();
if (Sys::nprocs >1) delete Sys::os;
return 0;
}
void Sys::bcast()
{
for(int i = 0; i < num(); i++) {
#ifdef BPMF_MPI_COMM
MPI_Bcast(items().col(i).data(), num_latent, MPI_DOUBLE, proc(i), MPI_COMM_WORLD);
#else
assert(Sys::nprocs == 1);
#endif
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Peter Mattis (peter.mattis@gmail.com)
// Style settings: indent -kr -ci2 -cli2 -i2 -l80 -nut roachlib/merge.cc
#include <string>
#include <limits>
#include "data.pb.h"
#include "rocksdb/slice.h"
#include "roach_c.h"
namespace {
bool WillOverflow(int64_t a, int64_t b) {
// Morally MinInt64 < a+b < MaxInt64, but without overflows.
// First make sure that a <= b. If not, swap them.
if (a > b) {
std::swap(a, b);
}
// Now b is the larger of the numbers, and we compare sizes
// in a way that can never over- or underflow.
if (b > 0) {
return a > (std::numeric_limits<int64_t>::max() - b);
}
return (std::numeric_limits<int64_t>::min() - b) > a;
}
bool MergeValues(proto::Value *left, const proto::Value &right) {
if (left->has_bytes()) {
if (right.has_bytes()) {
*left->mutable_bytes() += right.bytes();
return true;
}
} else if (left->has_integer()) {
if (right.has_integer()) {
if (WillOverflow(left->integer(), right.integer())) {
return false;
}
left->set_integer(left->integer() + right.integer());
return true;
}
} else {
*left = right;
return true;
}
return false;
}
// MergeResult serializes the result Value into a byte slice.
char* MergeResult(proto::Value* result, size_t *length) {
// TODO(pmattis): Should recompute checksum here. Need a crc32
// implementation and need to verify the checksumming is identical
// to what is being done in Go. Worst case we can port the Go crc32
// back to C/C++.
result->clear_checksum();
*length = result->ByteSize();
char *value = static_cast<char*>(malloc(*length));
if (!result->SerializeToArray(value, *length)) {
return NULL;
}
return value;
}
} // namespace
// MergeOne implements the merge operator on a single pair of values.
// update is merged with existing. This method is provided for
// invocation from Go code.
char* MergeOne(
const char* existing, size_t existing_length,
const char* update, size_t update_length,
size_t* new_value_length, char** error_msg) {
*new_value_length = 0;
proto::Value result;
if (!result.ParseFromArray(existing, existing_length)) {
// Corrupted existing value.
*error_msg = (char*)"corrupted existing value";
return NULL;
}
proto::Value value;
if (!value.ParseFromArray(update, update_length)) {
// Corrupted update value.
*error_msg = (char*)"corrupted update value";
return NULL;
}
if (!MergeValues(&result, value)) {
*error_msg = (char*)"incompatible merge values";
return NULL;
}
char *new_value = MergeResult(&result, new_value_length);
if (!new_value) {
*error_msg = (char*)"serialization error";
return NULL;
}
return new_value;
}
// MergeOperator implements the RocksDB custom merge operator for
// proto.Value objects. This method is called by RocksDB when merge
// operations are encountered, either when reading a value with a
// pending merge or when compacting merge operations.
char* MergeOperator(
const char* key, size_t key_length,
const char* existing_value,
size_t existing_value_length,
const char* const* operands_list,
const size_t* operands_list_length,
int num_operands, unsigned char* success,
size_t* new_value_length)
{
// TODO(pmattis): We should not be silent about errors. It's
// currently irritating to get them logged in Go, but we should get
// it fixed up so that such logging from C++ is straightforward.
*success = false;
*new_value_length = 0;
proto::Value result;
if (!result.ParseFromArray(existing_value, existing_value_length)) {
// Corrupted existing value.
return NULL;
}
for (int i = 0; i < num_operands; ++i) {
proto::Value value;
if (!value.ParseFromArray(operands_list[i], operands_list_length[i])) {
// Corrupted operand.
return NULL;
}
if (!MergeValues(&result, value)) {
// Invalid merge operation.
return NULL;
}
}
char *new_value = MergeResult(&result, new_value_length);
if (!new_value) {
return NULL;
}
*success = true;
return new_value;
}
<commit_msg>Add TODO about testing various merge error scenarios.<commit_after>// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License. See the AUTHORS file
// for names of contributors.
//
// Author: Peter Mattis (peter.mattis@gmail.com)
// Style settings: indent -kr -ci2 -cli2 -i2 -l80 -nut roachlib/merge.cc
#include <string>
#include <limits>
#include "data.pb.h"
#include "rocksdb/slice.h"
#include "roach_c.h"
namespace {
bool WillOverflow(int64_t a, int64_t b) {
// Morally MinInt64 < a+b < MaxInt64, but without overflows.
// First make sure that a <= b. If not, swap them.
if (a > b) {
std::swap(a, b);
}
// Now b is the larger of the numbers, and we compare sizes
// in a way that can never over- or underflow.
if (b > 0) {
return a > (std::numeric_limits<int64_t>::max() - b);
}
return (std::numeric_limits<int64_t>::min() - b) > a;
}
bool MergeValues(proto::Value *left, const proto::Value &right) {
if (left->has_bytes()) {
if (right.has_bytes()) {
*left->mutable_bytes() += right.bytes();
return true;
}
} else if (left->has_integer()) {
if (right.has_integer()) {
if (WillOverflow(left->integer(), right.integer())) {
return false;
}
left->set_integer(left->integer() + right.integer());
return true;
}
} else {
*left = right;
return true;
}
return false;
}
// MergeResult serializes the result Value into a byte slice.
char* MergeResult(proto::Value* result, size_t *length) {
// TODO(pmattis): Should recompute checksum here. Need a crc32
// implementation and need to verify the checksumming is identical
// to what is being done in Go. Worst case we can port the Go crc32
// back to C/C++.
result->clear_checksum();
*length = result->ByteSize();
char *value = static_cast<char*>(malloc(*length));
if (!result->SerializeToArray(value, *length)) {
return NULL;
}
return value;
}
} // namespace
// MergeOne implements the merge operator on a single pair of values.
// update is merged with existing. This method is provided for
// invocation from Go code.
char* MergeOne(
const char* existing, size_t existing_length,
const char* update, size_t update_length,
size_t* new_value_length, char** error_msg) {
*new_value_length = 0;
proto::Value result;
if (!result.ParseFromArray(existing, existing_length)) {
// Corrupted existing value.
*error_msg = (char*)"corrupted existing value";
return NULL;
}
proto::Value value;
if (!value.ParseFromArray(update, update_length)) {
// Corrupted update value.
*error_msg = (char*)"corrupted update value";
return NULL;
}
if (!MergeValues(&result, value)) {
*error_msg = (char*)"incompatible merge values";
return NULL;
}
char *new_value = MergeResult(&result, new_value_length);
if (!new_value) {
*error_msg = (char*)"serialization error";
return NULL;
}
return new_value;
}
// MergeOperator implements the RocksDB custom merge operator for
// proto.Value objects. This method is called by RocksDB when merge
// operations are encountered, either when reading a value with a
// pending merge or when compacting merge operations.
char* MergeOperator(
const char* key, size_t key_length,
const char* existing_value,
size_t existing_value_length,
const char* const* operands_list,
const size_t* operands_list_length,
int num_operands, unsigned char* success,
size_t* new_value_length)
{
// TODO(pmattis): Taken from the old merger code, below are some
// details about how errors returned by the merge operator are
// handled. Need to test various error scenarios and decide on
// desired behavior. Clear the key and it's gone. Corrupt it
// properly and RocksDB might refuse to work with it at all until
// you clear it manually, which may also not be what we want. The
// problem with merges is that RocksDB won't really carry them out
// while we have a chance to talk back to clients.
//
// If we indicate failure (*success = false), then the call to the
// merger via rocksdb_merge will not return an error, but simply
// remove or truncate the offending key (at least when the settings
// specify that missing keys should be created; otherwise a
// corruption error will be returned, but likely only after the next
// read of the key). In effect, there is no propagation of error
// information to the client.
// TODO(pmattis): We should not be silent about errors. It's
// currently irritating to get them logged in Go, but we should get
// it fixed up so that such logging from C++ is straightforward.
*success = false;
*new_value_length = 0;
proto::Value result;
if (!result.ParseFromArray(existing_value, existing_value_length)) {
// Corrupted existing value.
return NULL;
}
for (int i = 0; i < num_operands; ++i) {
proto::Value value;
if (!value.ParseFromArray(operands_list[i], operands_list_length[i])) {
// Corrupted operand.
return NULL;
}
if (!MergeValues(&result, value)) {
// Invalid merge operation.
return NULL;
}
}
char *new_value = MergeResult(&result, new_value_length);
if (!new_value) {
return NULL;
}
*success = true;
return new_value;
}
<|endoftext|> |
<commit_before>#ifdef HAVE_CONFIG_H
# include "../config.h"
#endif // HAVE_CONFIG_H
#ifdef STDC_HEADERS
# include <string.h>
# include <stdlib.h>
#endif // STDC_HEADERS
#ifdef HAVE_STDIO_H
# include <stdio.h>
#endif // HAVE_STDIO_H
#include "../src/i18n.hh"
#include "bsetroot.hh"
#include <iostream>
using namespace std;
bsetroot::bsetroot(int argc, char **argv, char *dpy_name)
: BaseDisplay(argv[0], dpy_name) {
pixmaps = (Pixmap *) 0;
grad = fore = back = (char *) 0;
Bool mod = False, sol = False, grd = False;
int mod_x = 0, mod_y = 0, i = 0;
img_ctrl = new BImageControl*[10];
for (; i < getNumberOfScreens(); i++) {
img_ctrl[i] = new BImageControl(this, getScreenInfo(i), True);
}
for (i = 1; i < argc; i++) {
if (! strcmp("-help", argv[i])) {
usage();
} else if ((! strcmp("-fg", argv[i])) ||
(! strcmp("-foreground", argv[i])) ||
(! strcmp("-from", argv[i]))) {
if ((++i) >= argc)
usage(1);
fore = argv[i];
} else if ((! strcmp("-bg", argv[i])) ||
(! strcmp("-background", argv[i])) ||
(! strcmp("-to", argv[i]))) {
if ((++i) >= argc)
usage(1);
back = argv[i];
} else if (! strcmp("-solid", argv[i])) {
if ((++i) >= argc)
usage(1);
fore = argv[i];
sol = True;
} else if (! strcmp("-mod", argv[i])) {
if ((++i) >= argc)
usage();
mod_x = atoi(argv[i]);
if ((++i) >= argc)
usage();
mod_y = atoi(argv[i]);
if (mod_x < 1)
mod_x = 1;
if (mod_y < 1)
mod_y = 1;
mod = True;
} else if (! strcmp("-gradient", argv[i])) {
if ((++i) >= argc)
usage();
grad = argv[i];
grd = True;
} else if (! strcmp("-display", argv[i])) {
// -display passed through tests earlier... we just skip it now
i++;
} else
usage();
}
if ((mod + sol + grd) != True) {
fprintf(stderr,
I18n::instance()->
getMessage(
FBNLS::bsetrootSet, FBNLS::bsetrootMustSpecify,
"%s: error: must specify on of: -solid, -mod, -gradient\n"),
getApplicationName());
usage(2);
}
display = getXDisplay();
num_screens = getNumberOfScreens();
if (sol && fore)
solid();
else if (mod && mod_x && mod_y && fore && back)
modula(mod_x, mod_y);
else if (grd && grad && fore && back)
gradient();
else
usage();
}
bsetroot::~bsetroot(void) {
XKillClient(display, AllTemporary);
if (pixmaps) { // should always be true
XSetCloseDownMode(display, RetainTemporary);
delete [] pixmaps;
}
#ifdef DEBUG
else
cerr<<"~bsetroot: why don't we have any pixmaps?"<<endl;
#endif // DEBUG
if (img_ctrl) {
int i = 0;
for (; i < num_screens; i++)
delete img_ctrl[i];
delete [] img_ctrl;
}
}
//------------ setRootAtoms ---------------
// set root pixmap atoms so that apps like
// Eterm and xchat will be able to use
// transparent background
//-----------------------------------------
void bsetroot::setRootAtoms(Pixmap pixmap, int screen) {
Atom atom_root, atom_eroot, type;
unsigned char *data_root, *data_eroot;
int format;
unsigned long length, after;
atom_root = XInternAtom(display, "_XROOTMAP_ID", true);
atom_eroot = XInternAtom(display, "ESETROOT_PMAP_ID", true);
// doing this to clean up after old background
if (atom_root != None && atom_eroot != None) {
XGetWindowProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_root, 0L, 1L, false, AnyPropertyType,
&type, &format, &length, &after, &data_root);
if (type == XA_PIXMAP) {
XGetWindowProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_eroot, 0L, 1L, False, AnyPropertyType,
&type, &format, &length, &after, &data_eroot);
if (data_root && data_eroot && type == XA_PIXMAP &&
*((Pixmap *) data_root) == *((Pixmap *) data_eroot)) {
XKillClient(display, *((Pixmap *) data_root));
}
}
}
atom_root = XInternAtom(display, "_XROOTPMAP_ID", false);
atom_eroot = XInternAtom(display, "ESETROOT_PMAP_ID", false);
if (atom_root == None || atom_eroot == None) {
cerr<<"couldn't create pixmap atoms, giving up!"<<endl;
exit(1);
}
// setting new background atoms
XChangeProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pixmap, 1);
XChangeProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_eroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pixmap, 1);
}
//-------------- solid --------------------
// draws pixmaps with a single color
//-----------------------------------------
void bsetroot::solid(void) {
register int screen = 0;
pixmaps = new Pixmap[getNumberOfScreens()];
for (; screen < getNumberOfScreens(); screen++) {
BColor c;
GC gc;
XGCValues gcv;
img_ctrl[screen]->parseColor(&c, fore);
if (! c.isAllocated())
c.setPixel(BlackPixel(getXDisplay(), screen));
gcv.foreground = c.pixel();
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground , &gcv);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
XFillRectangle(getXDisplay(), pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight());
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
XFreeGC(getXDisplay(), gc);
}
}
//-------------- modula ------------------
// draws pixmaps with an 16x16 pattern with
// fg and bg colors.
//-----------------------------------------
void bsetroot::modula(int x, int y) {
char data[32];
long pattern;
register int screen, i;
pixmaps = new Pixmap[getNumberOfScreens()];
for (pattern = 0, screen = 0; screen < getNumberOfScreens(); screen++) {
for (i = 0; i < 16; i++) {
pattern <<= 1;
if ((i % x) == 0)
pattern |= 0x0001;
}
for (i = 0; i < 16; i++) {
if ((i % y) == 0) {
data[(i * 2)] = (char) 0xff;
data[(i * 2) + 1] = (char) 0xff;
} else {
data[(i * 2)] = pattern & 0xff;
data[(i * 2) + 1] = (pattern >> 8) & 0xff;
}
}
BColor f, b;
GC gc;
Pixmap bitmap, r_bitmap;
XGCValues gcv;
bitmap = XCreateBitmapFromData(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), data, 16, 16);
// bitmap used as tile, needs to have the same depth as background pixmap
r_bitmap = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), 16, 16,
getScreenInfo(screen)->getDepth());
img_ctrl[screen]->parseColor(&f, fore);
img_ctrl[screen]->parseColor(&b, back);
if (! f.isAllocated())
f.setPixel(WhitePixel(getXDisplay(), screen));
if (! b.isAllocated())
b.setPixel(BlackPixel(getXDisplay(), screen));
gcv.foreground = f.pixel();
gcv.background = b.pixel();
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground | GCBackground, &gcv);
// copying bitmap to the one going to be used as tile
XCopyPlane(getXDisplay(), bitmap, r_bitmap, gc,
0, 0, 16, 16, 0, 0, 1l);
XSetTile(getXDisplay(), gc, r_bitmap);
XSetFillStyle(getXDisplay(), gc, FillTiled);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
XFillRectangle(getXDisplay(), pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight());
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
XFreeGC(getXDisplay(), gc);
XFreePixmap(getXDisplay(), bitmap);
XFreePixmap(getXDisplay(), r_bitmap);
}
}
//-------------- gradient -----------------
// draws pixmaps with a fluxbox texure
//-----------------------------------------
void bsetroot::gradient(void) {
register int screen;
// using temporaray pixmap and then copying it to background pixmap, as it'll
// get crashed somewhere on the way causing apps like XChat chrashing
// as the pixmap has been destroyed
Pixmap tmp;
pixmaps = new Pixmap[getNumberOfScreens()];
for (screen = 0; screen < getNumberOfScreens(); screen++) {
BTexture texture;
GC gc;
XGCValues gcv;
img_ctrl[screen]->parseTexture(&texture, grad);
img_ctrl[screen]->parseColor(&texture.color(), fore);
img_ctrl[screen]->parseColor(&texture.colorTo(), back);
if (! texture.color().isAllocated())
texture.color().setPixel(WhitePixel(getXDisplay(), screen));
if (! texture.colorTo().isAllocated())
texture.colorTo().setPixel(BlackPixel(getXDisplay(), screen));
tmp = img_ctrl[screen]->renderImage(getScreenInfo(screen)->getWidth(),
getScreenInfo(screen)->getHeight(), &texture);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground , &gcv);
XCopyArea(getXDisplay(), tmp, pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
0, 0);
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
if (! (getScreenInfo(screen)->getVisual()->c_class & 1)) {
img_ctrl[screen]->removeImage(tmp);
img_ctrl[screen]->timeout();
}
XFreeGC(getXDisplay(), gc);
}
}
//-------------- usage --------------------
// shows information about usage
//-----------------------------------------
void bsetroot::usage(int exit_code) {
fprintf(stderr,
I18n::instance()->getMessage(
FBNLS::bsetrootSet, FBNLS::bsetrootUsage,
"%s 2.1 : (c) 2002 Claes Nasten\n"
"%s 2.0 : (c) 1997-2000 Brad Hughes\n\n"
" -display <string> display connection\n"
" -mod <x> <y> modula pattern\n"
" -foreground, -fg <color> modula foreground color\n"
" -background, -bg <color> modula background color\n\n"
" -gradient <texture> gradient texture\n"
" -from <color> gradient start color\n"
" -to <color> gradient end color\n\n"
" -solid <color> solid color\n\n"
" -help print this help text and exit\n"),
getApplicationName(), getApplicationName());
exit(exit_code);
}
int main(int argc, char **argv) {
char *display_name = (char *) 0;
int i = 1;
NLSInit("blackbox.cat");
for (; i < argc; i++) {
if (! strcmp(argv[i], "-display")) {
// check for -display option
if ((++i) >= argc) {
fprintf(stderr,
I18n::instance()->getMessage(
FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
"error: '-display' requires an argument\n"));
::exit(1);
}
display_name = argv[i];
}
}
bsetroot app(argc, argv, display_name);
return (0);
}
<commit_msg>BColor and BTexture<commit_after>#ifdef HAVE_CONFIG_H
# include "../config.h"
#endif // HAVE_CONFIG_H
#ifdef STDC_HEADERS
# include <string.h>
# include <stdlib.h>
#endif // STDC_HEADERS
#ifdef HAVE_STDIO_H
# include <stdio.h>
#endif // HAVE_STDIO_H
#include "../src/i18n.hh"
#include "bsetroot.hh"
#include <iostream>
using namespace std;
bsetroot::bsetroot(int argc, char **argv, char *dpy_name)
: BaseDisplay(argv[0], dpy_name) {
pixmaps = (Pixmap *) 0;
grad = fore = back = (char *) 0;
Bool mod = False, sol = False, grd = False;
int mod_x = 0, mod_y = 0, i = 0;
img_ctrl = new BImageControl*[10];
for (; i < getNumberOfScreens(); i++) {
img_ctrl[i] = new BImageControl(this, getScreenInfo(i), True);
}
for (i = 1; i < argc; i++) {
if (! strcmp("-help", argv[i])) {
usage();
} else if ((! strcmp("-fg", argv[i])) ||
(! strcmp("-foreground", argv[i])) ||
(! strcmp("-from", argv[i]))) {
if ((++i) >= argc)
usage(1);
fore = argv[i];
} else if ((! strcmp("-bg", argv[i])) ||
(! strcmp("-background", argv[i])) ||
(! strcmp("-to", argv[i]))) {
if ((++i) >= argc)
usage(1);
back = argv[i];
} else if (! strcmp("-solid", argv[i])) {
if ((++i) >= argc)
usage(1);
fore = argv[i];
sol = True;
} else if (! strcmp("-mod", argv[i])) {
if ((++i) >= argc)
usage();
mod_x = atoi(argv[i]);
if ((++i) >= argc)
usage();
mod_y = atoi(argv[i]);
if (mod_x < 1)
mod_x = 1;
if (mod_y < 1)
mod_y = 1;
mod = True;
} else if (! strcmp("-gradient", argv[i])) {
if ((++i) >= argc)
usage();
grad = argv[i];
grd = True;
} else if (! strcmp("-display", argv[i])) {
// -display passed through tests earlier... we just skip it now
i++;
} else
usage();
}
if ((mod + sol + grd) != True) {
fprintf(stderr,
I18n::instance()->
getMessage(
FBNLS::bsetrootSet, FBNLS::bsetrootMustSpecify,
"%s: error: must specify on of: -solid, -mod, -gradient\n"),
getApplicationName());
usage(2);
}
display = getXDisplay();
num_screens = getNumberOfScreens();
if (sol && fore)
solid();
else if (mod && mod_x && mod_y && fore && back)
modula(mod_x, mod_y);
else if (grd && grad && fore && back)
gradient();
else
usage();
}
bsetroot::~bsetroot(void) {
XKillClient(display, AllTemporary);
if (pixmaps) { // should always be true
XSetCloseDownMode(display, RetainTemporary);
delete [] pixmaps;
}
#ifdef DEBUG
else
cerr<<"~bsetroot: why don't we have any pixmaps?"<<endl;
#endif // DEBUG
if (img_ctrl) {
int i = 0;
for (; i < num_screens; i++)
delete img_ctrl[i];
delete [] img_ctrl;
}
}
//------------ setRootAtoms ---------------
// set root pixmap atoms so that apps like
// Eterm and xchat will be able to use
// transparent background
//-----------------------------------------
void bsetroot::setRootAtoms(Pixmap pixmap, int screen) {
Atom atom_root, atom_eroot, type;
unsigned char *data_root, *data_eroot;
int format;
unsigned long length, after;
atom_root = XInternAtom(display, "_XROOTMAP_ID", true);
atom_eroot = XInternAtom(display, "ESETROOT_PMAP_ID", true);
// doing this to clean up after old background
if (atom_root != None && atom_eroot != None) {
XGetWindowProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_root, 0L, 1L, false, AnyPropertyType,
&type, &format, &length, &after, &data_root);
if (type == XA_PIXMAP) {
XGetWindowProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_eroot, 0L, 1L, False, AnyPropertyType,
&type, &format, &length, &after, &data_eroot);
if (data_root && data_eroot && type == XA_PIXMAP &&
*((Pixmap *) data_root) == *((Pixmap *) data_eroot)) {
XKillClient(display, *((Pixmap *) data_root));
}
}
}
atom_root = XInternAtom(display, "_XROOTPMAP_ID", false);
atom_eroot = XInternAtom(display, "ESETROOT_PMAP_ID", false);
if (atom_root == None || atom_eroot == None) {
cerr<<"couldn't create pixmap atoms, giving up!"<<endl;
exit(1);
}
// setting new background atoms
XChangeProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pixmap, 1);
XChangeProperty(display, getScreenInfo(screen)->getRootWindow(),
atom_eroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pixmap, 1);
}
//-------------- solid --------------------
// draws pixmaps with a single color
//-----------------------------------------
void bsetroot::solid(void) {
register int screen = 0;
pixmaps = new Pixmap[getNumberOfScreens()];
for (; screen < getNumberOfScreens(); screen++) {
FbTk::Color c;
GC gc;
XGCValues gcv;
img_ctrl[screen]->parseColor(&c, fore);
if (! c.isAllocated())
c.setPixel(BlackPixel(getXDisplay(), screen));
gcv.foreground = c.pixel();
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground , &gcv);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
XFillRectangle(getXDisplay(), pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight());
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
XFreeGC(getXDisplay(), gc);
}
}
//-------------- modula ------------------
// draws pixmaps with an 16x16 pattern with
// fg and bg colors.
//-----------------------------------------
void bsetroot::modula(int x, int y) {
char data[32];
long pattern;
register int screen, i;
pixmaps = new Pixmap[getNumberOfScreens()];
for (pattern = 0, screen = 0; screen < getNumberOfScreens(); screen++) {
for (i = 0; i < 16; i++) {
pattern <<= 1;
if ((i % x) == 0)
pattern |= 0x0001;
}
for (i = 0; i < 16; i++) {
if ((i % y) == 0) {
data[(i * 2)] = (char) 0xff;
data[(i * 2) + 1] = (char) 0xff;
} else {
data[(i * 2)] = pattern & 0xff;
data[(i * 2) + 1] = (pattern >> 8) & 0xff;
}
}
FbTk::Color f, b;
GC gc;
Pixmap bitmap, r_bitmap;
XGCValues gcv;
bitmap = XCreateBitmapFromData(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), data, 16, 16);
// bitmap used as tile, needs to have the same depth as background pixmap
r_bitmap = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), 16, 16,
getScreenInfo(screen)->getDepth());
img_ctrl[screen]->parseColor(&f, fore);
img_ctrl[screen]->parseColor(&b, back);
if (! f.isAllocated())
f.setPixel(WhitePixel(getXDisplay(), screen));
if (! b.isAllocated())
b.setPixel(BlackPixel(getXDisplay(), screen));
gcv.foreground = f.pixel();
gcv.background = b.pixel();
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground | GCBackground, &gcv);
// copying bitmap to the one going to be used as tile
XCopyPlane(getXDisplay(), bitmap, r_bitmap, gc,
0, 0, 16, 16, 0, 0, 1l);
XSetTile(getXDisplay(), gc, r_bitmap);
XSetFillStyle(getXDisplay(), gc, FillTiled);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
XFillRectangle(getXDisplay(), pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight());
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
XFreeGC(getXDisplay(), gc);
XFreePixmap(getXDisplay(), bitmap);
XFreePixmap(getXDisplay(), r_bitmap);
}
}
//-------------- gradient -----------------
// draws pixmaps with a fluxbox texure
//-----------------------------------------
void bsetroot::gradient(void) {
register int screen;
// using temporaray pixmap and then copying it to background pixmap, as it'll
// get crashed somewhere on the way causing apps like XChat chrashing
// as the pixmap has been destroyed
Pixmap tmp;
pixmaps = new Pixmap[getNumberOfScreens()];
for (screen = 0; screen < getNumberOfScreens(); screen++) {
FbTk::Texture texture;
GC gc;
XGCValues gcv;
img_ctrl[screen]->parseTexture(&texture, grad);
img_ctrl[screen]->parseColor(&texture.color(), fore);
img_ctrl[screen]->parseColor(&texture.colorTo(), back);
if (! texture.color().isAllocated())
texture.color().setPixel(WhitePixel(getXDisplay(), screen));
if (! texture.colorTo().isAllocated())
texture.colorTo().setPixel(BlackPixel(getXDisplay(), screen));
tmp = img_ctrl[screen]->renderImage(getScreenInfo(screen)->getWidth(),
getScreenInfo(screen)->getHeight(), &texture);
pixmaps[screen] = XCreatePixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(),
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
getScreenInfo(screen)->getDepth());
gc = XCreateGC(getXDisplay(), getScreenInfo(screen)->getRootWindow(),
GCForeground , &gcv);
XCopyArea(getXDisplay(), tmp, pixmaps[screen], gc, 0, 0,
getScreenInfo(screen)->getWidth(), getScreenInfo(screen)->getHeight(),
0, 0);
setRootAtoms(pixmaps[screen], screen);
XSetWindowBackgroundPixmap(getXDisplay(),
getScreenInfo(screen)->getRootWindow(), pixmaps[screen]);
XClearWindow(getXDisplay(), getScreenInfo(screen)->getRootWindow());
if (! (getScreenInfo(screen)->getVisual()->c_class & 1)) {
img_ctrl[screen]->removeImage(tmp);
img_ctrl[screen]->timeout();
}
XFreeGC(getXDisplay(), gc);
}
}
//-------------- usage --------------------
// shows information about usage
//-----------------------------------------
void bsetroot::usage(int exit_code) {
fprintf(stderr,
I18n::instance()->getMessage(
FBNLS::bsetrootSet, FBNLS::bsetrootUsage,
"%s 2.1 : (c) 2002 Claes Nasten\n"
"%s 2.0 : (c) 1997-2000 Brad Hughes\n\n"
" -display <string> display connection\n"
" -mod <x> <y> modula pattern\n"
" -foreground, -fg <color> modula foreground color\n"
" -background, -bg <color> modula background color\n\n"
" -gradient <texture> gradient texture\n"
" -from <color> gradient start color\n"
" -to <color> gradient end color\n\n"
" -solid <color> solid color\n\n"
" -help print this help text and exit\n"),
getApplicationName(), getApplicationName());
exit(exit_code);
}
int main(int argc, char **argv) {
char *display_name = (char *) 0;
int i = 1;
NLSInit("blackbox.cat");
for (; i < argc; i++) {
if (! strcmp(argv[i], "-display")) {
// check for -display option
if ((++i) >= argc) {
fprintf(stderr,
I18n::instance()->getMessage(
FBNLS::mainSet, FBNLS::mainDISPLAYRequiresArg,
"error: '-display' requires an argument\n"));
::exit(1);
}
display_name = argv[i];
}
}
bsetroot app(argc, argv, display_name);
return (0);
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <re2jit/threads.h>
static rejit_thread_t *rejit_thread_new(rejit_threadset_t *r)
{
rejit_thread_t *t;
if (r->free) {
// Reuse dead threads to cut on malloc-related costs.
t = r->free;
r->free = t->next;
} else {
t = (rejit_thread_t *) malloc(sizeof(rejit_thread_t) + sizeof(int) * r->ngroups);
if (t == NULL) {
return NULL;
}
memset(t->groups, 255, sizeof(int) * r->ngroups);
t->category.ref = t;
rejit_list_init(&t->category);
}
rejit_list_init(t);
return t;
}
static rejit_thread_t *rejit_thread_entry(rejit_threadset_t *r)
{
rejit_thread_t *t = rejit_thread_new(r);
if (t == NULL) {
return NULL;
}
t->entry = r->entry;
rejit_list_append(r->all_threads.last, t);
rejit_list_append(r->queues[r->active_queue].last, &t->category);
return t;
}
rejit_threadset_t *rejit_thread_init(const char *input, size_t length, void *entry, int flags, int ngroups)
{
rejit_threadset_t *r = (rejit_threadset_t *) calloc(sizeof(rejit_threadset_t), 1);
if (r == NULL) {
return NULL;
}
rejit_list_init(&r->all_threads);
size_t i;
for (i = 0; i <= RE2JIT_THREAD_LOOKAHEAD; i++) {
rejit_list_init(&r->queues[i]);
}
r->entry = entry;
r->flags = flags;
r->input = input;
r->length = length;
r->ngroups = ngroups;
if (rejit_thread_entry(r) == NULL) {
free(r);
return NULL;
}
return r;
}
void rejit_thread_free(rejit_threadset_t *r)
{
rejit_thread_t *a, *b;
#define FREE_LIST(init, end) do { \
for (a = init; a != end; ) { \
b = a; \
a = a->next; \
free(b); \
} \
} while (0)
FREE_LIST(r->free, NULL);
FREE_LIST(r->all_threads.first, rejit_list_end(&r->all_threads));
free(r);
#undef FREE_LIST
}
int rejit_thread_dispatch(rejit_threadset_t *r, int max_steps)
{
size_t queue = r->active_queue;
do {
struct st_rejit_thread_ref_t *t = r->queues[queue].first;
while (t != rejit_list_end(&r->queues[queue])) {
r->running = t->ref;
// TODO something with `t->ref->entry`.
// NOTE thread should never run `dispatch`! It should return here.
if (!--max_steps) {
r->active_queue = queue;
return 1;
}
t = r->queues[queue].first;
}
queue = (queue + 1) % (RE2JIT_THREAD_LOOKAHEAD + 1);
if (!(r->flags & RE2JIT_ANCHOR_START) && r->length) {
if (rejit_thread_entry(r) == NULL) {
// XOO < *ac was completely screwed out of memory
// and nothing can fix that!!*
}
}
} while (r->input++, r->length--);
// Doesn't matter which queue is active now...
return 0;
}
void rejit_thread_fork(rejit_threadset_t *r, void *entry)
{
rejit_thread_t *t = rejit_thread_new(r);
rejit_thread_t *p = r->running;
if (t == NULL) {
// :33 < oh shit
return;
}
memcpy(t->groups, p->groups, sizeof(int) * r->ngroups);
t->entry = entry;
rejit_list_append(p, t);
rejit_list_append(&p->category, &t->category);
}
void rejit_thread_match(rejit_threadset_t *r)
{
rejit_thread_t *p = r->running;
if ((r->flags & RE2JIT_ANCHOR_END) && r->length) {
// No, it did not. Not EOF yet.
rejit_thread_fail(r);
return;
}
while (p->next != rejit_list_end(&r->all_threads)) {
// Can safely fail all less important threads. If they fail, this one
// has matched, so whatever. If they match, this one contains better results.
r->running = p->next;
rejit_thread_fail(r);
}
rejit_list_remove(&p->category);
}
void rejit_thread_fail(rejit_threadset_t *r)
{
rejit_thread_t *p = r->running;
rejit_list_remove(p);
rejit_list_remove(&p->category);
p->next = r->free;
r->free = p;
}
void rejit_thread_wait(rejit_threadset_t *r, size_t shift)
{
size_t queue = (r->active_queue + shift) % (RE2JIT_THREAD_LOOKAHEAD + 1);
rejit_thread_t *p = r->running;
rejit_list_remove(&p->category);
rejit_list_append(r->queues[queue].last, &p->category);
}
int rejit_thread_result(rejit_threadset_t *r, int **groups)
{
if (r->all_threads.first == rejit_list_end(&r->all_threads)) {
return 0;
}
*groups = r->all_threads.first->groups;
return 1;
}
<commit_msg>Make rejit_thread_dispatch safe to call after it finished.<commit_after>#include <stdlib.h>
#include <string.h>
#include <re2jit/threads.h>
static rejit_thread_t *rejit_thread_new(rejit_threadset_t *r)
{
rejit_thread_t *t;
if (r->free) {
// Reuse dead threads to cut on malloc-related costs.
t = r->free;
r->free = t->next;
} else {
t = (rejit_thread_t *) malloc(sizeof(rejit_thread_t) + sizeof(int) * r->ngroups);
if (t == NULL) {
return NULL;
}
memset(t->groups, 255, sizeof(int) * r->ngroups);
t->category.ref = t;
rejit_list_init(&t->category);
}
rejit_list_init(t);
return t;
}
static rejit_thread_t *rejit_thread_entry(rejit_threadset_t *r)
{
rejit_thread_t *t = rejit_thread_new(r);
if (t == NULL) {
return NULL;
}
t->entry = r->entry;
rejit_list_append(r->all_threads.last, t);
rejit_list_append(r->queues[r->active_queue].last, &t->category);
return t;
}
rejit_threadset_t *rejit_thread_init(const char *input, size_t length, void *entry, int flags, int ngroups)
{
rejit_threadset_t *r = (rejit_threadset_t *) calloc(sizeof(rejit_threadset_t), 1);
if (r == NULL) {
return NULL;
}
rejit_list_init(&r->all_threads);
size_t i;
for (i = 0; i <= RE2JIT_THREAD_LOOKAHEAD; i++) {
rejit_list_init(&r->queues[i]);
}
r->entry = entry;
r->flags = flags;
r->input = input;
r->length = length;
r->ngroups = ngroups;
if (rejit_thread_entry(r) == NULL) {
free(r);
return NULL;
}
return r;
}
void rejit_thread_free(rejit_threadset_t *r)
{
rejit_thread_t *a, *b;
#define FREE_LIST(init, end) do { \
for (a = init; a != end; ) { \
b = a; \
a = a->next; \
free(b); \
} \
} while (0)
FREE_LIST(r->free, NULL);
FREE_LIST(r->all_threads.first, rejit_list_end(&r->all_threads));
free(r);
#undef FREE_LIST
}
int rejit_thread_dispatch(rejit_threadset_t *r, int max_steps)
{
size_t queue = r->active_queue;
while (1) {
struct st_rejit_thread_ref_t *t = r->queues[queue].first;
while (t != rejit_list_end(&r->queues[queue])) {
r->running = t->ref;
// TODO something with `t->ref->entry`.
// NOTE thread should never run `dispatch`! It should return here.
if (!--max_steps) {
r->active_queue = queue;
return 1;
}
t = r->queues[queue].first;
}
queue = (queue + 1) % (RE2JIT_THREAD_LOOKAHEAD + 1);
if (!r->length) {
return 0;
}
if (!(r->flags & RE2JIT_ANCHOR_START)) {
if (rejit_thread_entry(r) == NULL) {
// XOO < *ac was completely screwed out of memory
// and nothing can fix that!!*
}
}
r->input++;
r->length--;
}
}
void rejit_thread_fork(rejit_threadset_t *r, void *entry)
{
rejit_thread_t *t = rejit_thread_new(r);
rejit_thread_t *p = r->running;
if (t == NULL) {
// :33 < oh shit
return;
}
memcpy(t->groups, p->groups, sizeof(int) * r->ngroups);
t->entry = entry;
rejit_list_append(p, t);
rejit_list_append(&p->category, &t->category);
}
void rejit_thread_match(rejit_threadset_t *r)
{
rejit_thread_t *p = r->running;
if ((r->flags & RE2JIT_ANCHOR_END) && r->length) {
// No, it did not. Not EOF yet.
rejit_thread_fail(r);
return;
}
while (p->next != rejit_list_end(&r->all_threads)) {
// Can safely fail all less important threads. If they fail, this one
// has matched, so whatever. If they match, this one contains better results.
r->running = p->next;
rejit_thread_fail(r);
}
rejit_list_remove(&p->category);
}
void rejit_thread_fail(rejit_threadset_t *r)
{
rejit_thread_t *p = r->running;
rejit_list_remove(p);
rejit_list_remove(&p->category);
p->next = r->free;
r->free = p;
}
void rejit_thread_wait(rejit_threadset_t *r, size_t shift)
{
size_t queue = (r->active_queue + shift) % (RE2JIT_THREAD_LOOKAHEAD + 1);
rejit_thread_t *p = r->running;
rejit_list_remove(&p->category);
rejit_list_append(r->queues[queue].last, &p->category);
}
int rejit_thread_result(rejit_threadset_t *r, int **groups)
{
if (r->all_threads.first == rejit_list_end(&r->all_threads)) {
return 0;
}
*groups = r->all_threads.first->groups;
return 1;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Cloudius Systems
*/
#include "row_cache.hh"
#include "core/memory.hh"
#include "core/do_with.hh"
#include "core/future-util.hh"
#include <seastar/core/scollectd.hh>
#include "memtable.hh"
static logging::logger logger("cache");
cache_tracker& global_cache_tracker() {
static thread_local cache_tracker instance;
return instance;
}
cache_tracker::cache_tracker() {
setup_collectd();
_region.make_evictable([this] {
with_allocator(_region.allocator(), [this] {
assert(!_lru.empty());
_lru.pop_back_and_dispose(current_deleter<cache_entry>());
});
});
}
cache_tracker::~cache_tracker() {
clear();
}
void
cache_tracker::setup_collectd() {
_collectd_registrations = std::make_unique<scollectd::registrations>(scollectd::registrations({
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "bytes", "used")
, scollectd::make_typed(scollectd::data_type::GAUGE, [this] { return _region.occupancy().used_space(); })
),
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "total_operations", "hits")
, scollectd::make_typed(scollectd::data_type::DERIVE, _hits)
),
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "total_operations", "misses")
, scollectd::make_typed(scollectd::data_type::DERIVE, _misses)
),
}));
}
void cache_tracker::clear() {
with_allocator(_region.allocator(), [this] {
_lru.clear_and_dispose(current_deleter<cache_entry>());
});
}
void cache_tracker::touch(cache_entry& e) {
++_hits;
_lru.erase(_lru.iterator_to(e));
_lru.push_front(e);
}
void cache_tracker::insert(cache_entry& entry) {
++_misses;
_lru.push_front(entry);
}
allocation_strategy& cache_tracker::allocator() {
return _region.allocator();
}
logalloc::region& cache_tracker::region() {
return _region;
}
// Reader which populates the cache using data from the delegate.
class populating_reader {
row_cache& _cache;
mutation_reader _delegate;
public:
populating_reader(row_cache& cache, mutation_reader delegate)
: _cache(cache)
, _delegate(std::move(delegate))
{ }
future<mutation_opt> operator()() {
return _delegate().then([this] (mutation_opt&& mo) {
if (mo) {
_cache.populate(*mo);
}
return std::move(mo);
});
}
};
mutation_reader
row_cache::make_reader(const query::partition_range& range) {
if (range.is_singular()) {
const query::ring_position& pos = range.start()->value();
if (!pos.has_key()) {
warn(unimplemented::cause::RANGE_QUERIES);
return populating_reader(*this, _underlying(range));
}
const dht::decorated_key& dk = pos.as_decorated_key();
auto i = _partitions.find(dk, cache_entry::compare(_schema));
if (i != _partitions.end()) {
cache_entry& e = *i;
_tracker.touch(e);
++_stats.hits;
return make_reader_returning(mutation(_schema, dk, e.partition()));
} else {
++_stats.misses;
return populating_reader(*this, _underlying(range));
}
}
warn(unimplemented::cause::RANGE_QUERIES);
return populating_reader(*this, _underlying(range));
}
row_cache::~row_cache() {
with_allocator(_tracker.allocator(), [this] {
_partitions.clear_and_dispose(current_deleter<cache_entry>());
});
}
void row_cache::populate(const mutation& m) {
with_allocator(_tracker.allocator(), [this, &m] {
auto i = _partitions.lower_bound(m.decorated_key(), cache_entry::compare(_schema));
if (i == _partitions.end() || !i->key().equal(*_schema, m.decorated_key())) {
cache_entry* entry = current_allocator().construct<cache_entry>(m.decorated_key(), m.partition());
_tracker.insert(*entry);
_partitions.insert(i, *entry);
} else {
_tracker.touch(*i);
// We cache whole partitions right now, so if cache already has this partition,
// it must be complete, so do nothing.
}
});
}
future<> row_cache::update(memtable& m, negative_mutation_reader underlying_negative) {
_tracker.region().merge(m._region); // Now all data in memtable belongs to cache
with_allocator(_tracker.allocator(), [this, &m, underlying_negative = std::move(underlying_negative)] {
auto i = m.partitions.begin();
const schema& s = *m.schema();
while (i != m.partitions.end()) {
partition_entry& mem_e = *i;
// FIXME: Optimize knowing we lookup in-order.
auto cache_i = _partitions.lower_bound(mem_e.key(), cache_entry::compare(_schema));
// If cache doesn't contain the entry we cannot insert it because the mutation may be incomplete.
// FIXME: keep a bitmap indicating which sstables we do cover, so we don't have to
// search it.
if (cache_i != _partitions.end() && cache_i->key().equal(s, mem_e.key())) {
cache_entry& entry = *cache_i;
_tracker.touch(entry);
entry.partition().apply(s, std::move(mem_e.partition()));
} else if (underlying_negative(mem_e.key().key()) == negative_mutation_reader_result::definitely_doesnt_exists) {
cache_entry* entry = current_allocator().construct<cache_entry>(mem_e.key(), mem_e.partition());
_tracker.insert(*entry);
_partitions.insert(cache_i, *entry);
}
i = m.partitions.erase(i);
current_allocator().destroy(&mem_e);
}
});
// FIXME: yield voluntarily every now and then to cap latency.
return make_ready_future<>();
}
row_cache::row_cache(schema_ptr s, mutation_source fallback_factory, cache_tracker& tracker)
: _tracker(tracker)
, _schema(std::move(s))
, _partitions(cache_entry::compare(_schema))
, _underlying(std::move(fallback_factory))
{ }
cache_entry::cache_entry(cache_entry&& o) noexcept
: _key(std::move(o._key))
, _p(std::move(o._p))
, _lru_link()
, _cache_link()
{
{
auto prev = o._lru_link.prev_;
o._lru_link.unlink();
cache_tracker::lru_type::node_algorithms::link_after(prev, _lru_link.this_ptr());
}
{
using container_type = row_cache::partitions_type;
container_type::node_algorithms::replace_node(o._cache_link.this_ptr(), _cache_link.this_ptr());
container_type::node_algorithms::init(o._cache_link.this_ptr());
}
}
<commit_msg>row_cache: yield while moving data to cache<commit_after>/*
* Copyright 2015 Cloudius Systems
*/
#include "row_cache.hh"
#include "core/memory.hh"
#include "core/do_with.hh"
#include "core/future-util.hh"
#include <seastar/core/scollectd.hh>
#include "memtable.hh"
static logging::logger logger("cache");
cache_tracker& global_cache_tracker() {
static thread_local cache_tracker instance;
return instance;
}
cache_tracker::cache_tracker() {
setup_collectd();
_region.make_evictable([this] {
with_allocator(_region.allocator(), [this] {
assert(!_lru.empty());
_lru.pop_back_and_dispose(current_deleter<cache_entry>());
});
});
}
cache_tracker::~cache_tracker() {
clear();
}
void
cache_tracker::setup_collectd() {
_collectd_registrations = std::make_unique<scollectd::registrations>(scollectd::registrations({
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "bytes", "used")
, scollectd::make_typed(scollectd::data_type::GAUGE, [this] { return _region.occupancy().used_space(); })
),
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "total_operations", "hits")
, scollectd::make_typed(scollectd::data_type::DERIVE, _hits)
),
scollectd::add_polled_metric(scollectd::type_instance_id("cache"
, scollectd::per_cpu_plugin_instance
, "total_operations", "misses")
, scollectd::make_typed(scollectd::data_type::DERIVE, _misses)
),
}));
}
void cache_tracker::clear() {
with_allocator(_region.allocator(), [this] {
_lru.clear_and_dispose(current_deleter<cache_entry>());
});
}
void cache_tracker::touch(cache_entry& e) {
++_hits;
_lru.erase(_lru.iterator_to(e));
_lru.push_front(e);
}
void cache_tracker::insert(cache_entry& entry) {
++_misses;
_lru.push_front(entry);
}
allocation_strategy& cache_tracker::allocator() {
return _region.allocator();
}
logalloc::region& cache_tracker::region() {
return _region;
}
// Reader which populates the cache using data from the delegate.
class populating_reader {
row_cache& _cache;
mutation_reader _delegate;
public:
populating_reader(row_cache& cache, mutation_reader delegate)
: _cache(cache)
, _delegate(std::move(delegate))
{ }
future<mutation_opt> operator()() {
return _delegate().then([this] (mutation_opt&& mo) {
if (mo) {
_cache.populate(*mo);
}
return std::move(mo);
});
}
};
mutation_reader
row_cache::make_reader(const query::partition_range& range) {
if (range.is_singular()) {
const query::ring_position& pos = range.start()->value();
if (!pos.has_key()) {
warn(unimplemented::cause::RANGE_QUERIES);
return populating_reader(*this, _underlying(range));
}
const dht::decorated_key& dk = pos.as_decorated_key();
auto i = _partitions.find(dk, cache_entry::compare(_schema));
if (i != _partitions.end()) {
cache_entry& e = *i;
_tracker.touch(e);
++_stats.hits;
return make_reader_returning(mutation(_schema, dk, e.partition()));
} else {
++_stats.misses;
return populating_reader(*this, _underlying(range));
}
}
warn(unimplemented::cause::RANGE_QUERIES);
return populating_reader(*this, _underlying(range));
}
row_cache::~row_cache() {
with_allocator(_tracker.allocator(), [this] {
_partitions.clear_and_dispose(current_deleter<cache_entry>());
});
}
void row_cache::populate(const mutation& m) {
with_allocator(_tracker.allocator(), [this, &m] {
auto i = _partitions.lower_bound(m.decorated_key(), cache_entry::compare(_schema));
if (i == _partitions.end() || !i->key().equal(*_schema, m.decorated_key())) {
cache_entry* entry = current_allocator().construct<cache_entry>(m.decorated_key(), m.partition());
_tracker.insert(*entry);
_partitions.insert(i, *entry);
} else {
_tracker.touch(*i);
// We cache whole partitions right now, so if cache already has this partition,
// it must be complete, so do nothing.
}
});
}
future<> row_cache::update(memtable& m, negative_mutation_reader underlying_negative) {
_tracker.region().merge(m._region); // Now all data in memtable belongs to cache
return repeat([this, &m, underlying_negative = std::move(underlying_negative)] () mutable {
return with_allocator(_tracker.allocator(), [this, &m, &underlying_negative] () {
unsigned quota = 30;
auto i = m.partitions.begin();
const schema& s = *m.schema();
while (i != m.partitions.end() && quota-- != 0) {
partition_entry& mem_e = *i;
// FIXME: Optimize knowing we lookup in-order.
auto cache_i = _partitions.lower_bound(mem_e.key(), cache_entry::compare(_schema));
// If cache doesn't contain the entry we cannot insert it because the mutation may be incomplete.
// FIXME: keep a bitmap indicating which sstables we do cover, so we don't have to
// search it.
if (cache_i != _partitions.end() && cache_i->key().equal(s, mem_e.key())) {
cache_entry& entry = *cache_i;
_tracker.touch(entry);
entry.partition().apply(s, std::move(mem_e.partition()));
} else if (underlying_negative(mem_e.key().key()) == negative_mutation_reader_result::definitely_doesnt_exists) {
cache_entry* entry = current_allocator().construct<cache_entry>(mem_e.key(), mem_e.partition());
_tracker.insert(*entry);
_partitions.insert(cache_i, *entry);
}
i = m.partitions.erase(i);
current_allocator().destroy(&mem_e);
}
return make_ready_future<stop_iteration>(m.partitions.empty() ? stop_iteration::yes : stop_iteration::no);
});
});
}
row_cache::row_cache(schema_ptr s, mutation_source fallback_factory, cache_tracker& tracker)
: _tracker(tracker)
, _schema(std::move(s))
, _partitions(cache_entry::compare(_schema))
, _underlying(std::move(fallback_factory))
{ }
cache_entry::cache_entry(cache_entry&& o) noexcept
: _key(std::move(o._key))
, _p(std::move(o._p))
, _lru_link()
, _cache_link()
{
{
auto prev = o._lru_link.prev_;
o._lru_link.unlink();
cache_tracker::lru_type::node_algorithms::link_after(prev, _lru_link.this_ptr());
}
{
using container_type = row_cache::partitions_type;
container_type::node_algorithms::replace_node(o._cache_link.this_ptr(), _cache_link.this_ptr());
container_type::node_algorithms::init(o._cache_link.this_ptr());
}
}
<|endoftext|> |
<commit_before>#ifndef RANGER_UTIL_RW_LOCK_HPP
#define RANGER_UTIL_RW_LOCK_HPP
#include <mutex>
#include <condition_variable>
namespace ranger { namespace util {
class rw_lock
{
public:
rw_lock() = default;
rw_lock(const rw_lock&) = delete;
rw_lock& operator = (const rw_lock&) = delete;
void read_lock()
{
std::lock_guard<std::mutex> lock(m_mtx);
++m_rlc;
}
void read_unlock()
{
std::unique_lock<std::mutex> lock(m_mtx);
if (--m_rlc == 0)
{
lock.unlock();
m_cv.notify_all();
}
}
void write_lock()
{
std::unique_lock<std::mutex> lock(m_mtx);
m_cv.wait(lock, [this] { return m_rlc == 0; });
lock.release();
}
void write_unlock()
{
m_mtx.unlock();
}
private:
std::mutex m_mtx;
std::condition_variable m_cv;
size_t m_rlc = 0;
};
} }
#endif // RANGER_UTIL_RW_LOCK_HPP
<commit_msg>rw_lock.hpp缩进调整。<commit_after>#ifndef RANGER_UTIL_RW_LOCK_HPP
#define RANGER_UTIL_RW_LOCK_HPP
#include <mutex>
#include <condition_variable>
namespace ranger { namespace util {
class rw_lock
{
public:
rw_lock() = default;
rw_lock(const rw_lock&) = delete;
rw_lock& operator = (const rw_lock&) = delete;
void read_lock()
{
std::lock_guard<std::mutex> lock(m_mtx);
++m_rlc;
}
void read_unlock()
{
std::unique_lock<std::mutex> lock(m_mtx);
if (--m_rlc == 0)
{
lock.unlock();
m_cv.notify_all();
}
}
void write_lock()
{
std::unique_lock<std::mutex> lock(m_mtx);
m_cv.wait(lock, [this] { return m_rlc == 0; });
lock.release();
}
void write_unlock()
{
m_mtx.unlock();
}
private:
std::mutex m_mtx;
std::condition_variable m_cv;
size_t m_rlc = 0;
};
} }
#endif // RANGER_UTIL_RW_LOCK_HPP
<|endoftext|> |
<commit_before>//===- ValueTypes.cpp - Tablegen extended ValueType implementation --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The MVT type is used by tablegen as well as in LLVM. In order to handle
// extended types, the MVT type uses support functions that call into
// LLVM's type system code. These aren't accessible in tablegen, so this
// file provides simple replacements.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/Streams.h"
#include <map>
#include <vector>
using namespace llvm;
namespace llvm {
class Type {
public:
virtual unsigned getSizeInBits() const = 0;
};
}
class ExtendedIntegerType : public Type {
unsigned BitWidth;
public:
explicit ExtendedIntegerType(unsigned bits)
: BitWidth(bits) {}
unsigned getSizeInBits() const {
return getBitWidth();
}
unsigned getBitWidth() const {
return BitWidth;
}
};
class ExtendedVectorType : public Type {
MVT ElementType;
unsigned NumElements;
public:
ExtendedVectorType(MVT elty, unsigned num)
: ElementType(elty), NumElements(num) {}
unsigned getSizeInBits() const {
return getNumElements() * getElementType().getSizeInBits();
}
MVT getElementType() const {
return ElementType;
}
unsigned getNumElements() const {
return NumElements;
}
};
static std::map<unsigned, const Type *>
ExtendedIntegerTypeMap;
static std::map<std::pair<uintptr_t, uintptr_t>, const Type *>
ExtendedVectorTypeMap;
MVT MVT::getExtendedIntegerVT(unsigned BitWidth) {
const Type *&ET = ExtendedIntegerTypeMap[BitWidth];
if (!ET) ET = new ExtendedIntegerType(BitWidth);
MVT VT;
VT.LLVMTy = ET;
assert(VT.isExtended() && "Type is not extended!");
return VT;
}
MVT MVT::getExtendedVectorVT(MVT VT, unsigned NumElements) {
const Type *&ET = ExtendedVectorTypeMap[std::make_pair(VT.getRawBits(),
NumElements)];
if (!ET) ET = new ExtendedVectorType(VT, NumElements);
MVT ResultVT;
ResultVT.LLVMTy = ET;
assert(ResultVT.isExtended() && "Type is not extended!");
return ResultVT;
}
bool MVT::isExtendedFloatingPoint() const {
assert(isExtended() && "Type is not extended!");
// Extended floating-point types are not supported yet.
return false;
}
bool MVT::isExtendedInteger() const {
assert(isExtended() && "Type is not extended!");
return dynamic_cast<const ExtendedIntegerType *>(LLVMTy) != 0;
}
bool MVT::isExtendedVector() const {
assert(isExtended() && "Type is not extended!");
return dynamic_cast<const ExtendedVectorType *>(LLVMTy) != 0;
}
bool MVT::isExtended64BitVector() const {
assert(isExtended() && "Type is not extended!");
return isExtendedVector() && getSizeInBits() == 64;
}
bool MVT::isExtended128BitVector() const {
assert(isExtended() && "Type is not extended!");
return isExtendedVector() && getSizeInBits() == 128;
}
MVT MVT::getExtendedVectorElementType() const {
assert(isExtendedVector() && "Type is not an extended vector!");
return static_cast<const ExtendedVectorType *>(LLVMTy)->getElementType();
}
unsigned MVT::getExtendedVectorNumElements() const {
assert(isExtendedVector() && "Type is not an extended vector!");
return static_cast<const ExtendedVectorType *>(LLVMTy)->getNumElements();
}
unsigned MVT::getExtendedSizeInBits() const {
assert(isExtended() && "Type is not extended!");
return LLVMTy->getSizeInBits();
}
<commit_msg>Give tablegen's Type a destructor, to suppress spurious "Type has virtual functions but non-virtual destructor" warnings.<commit_after>//===- ValueTypes.cpp - Tablegen extended ValueType implementation --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The MVT type is used by tablegen as well as in LLVM. In order to handle
// extended types, the MVT type uses support functions that call into
// LLVM's type system code. These aren't accessible in tablegen, so this
// file provides simple replacements.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/Streams.h"
#include <map>
#include <vector>
using namespace llvm;
namespace llvm {
class Type {
public:
virtual unsigned getSizeInBits() const = 0;
virtual ~Type() {}
};
}
class ExtendedIntegerType : public Type {
unsigned BitWidth;
public:
explicit ExtendedIntegerType(unsigned bits)
: BitWidth(bits) {}
unsigned getSizeInBits() const {
return getBitWidth();
}
unsigned getBitWidth() const {
return BitWidth;
}
};
class ExtendedVectorType : public Type {
MVT ElementType;
unsigned NumElements;
public:
ExtendedVectorType(MVT elty, unsigned num)
: ElementType(elty), NumElements(num) {}
unsigned getSizeInBits() const {
return getNumElements() * getElementType().getSizeInBits();
}
MVT getElementType() const {
return ElementType;
}
unsigned getNumElements() const {
return NumElements;
}
};
static std::map<unsigned, const Type *>
ExtendedIntegerTypeMap;
static std::map<std::pair<uintptr_t, uintptr_t>, const Type *>
ExtendedVectorTypeMap;
MVT MVT::getExtendedIntegerVT(unsigned BitWidth) {
const Type *&ET = ExtendedIntegerTypeMap[BitWidth];
if (!ET) ET = new ExtendedIntegerType(BitWidth);
MVT VT;
VT.LLVMTy = ET;
assert(VT.isExtended() && "Type is not extended!");
return VT;
}
MVT MVT::getExtendedVectorVT(MVT VT, unsigned NumElements) {
const Type *&ET = ExtendedVectorTypeMap[std::make_pair(VT.getRawBits(),
NumElements)];
if (!ET) ET = new ExtendedVectorType(VT, NumElements);
MVT ResultVT;
ResultVT.LLVMTy = ET;
assert(ResultVT.isExtended() && "Type is not extended!");
return ResultVT;
}
bool MVT::isExtendedFloatingPoint() const {
assert(isExtended() && "Type is not extended!");
// Extended floating-point types are not supported yet.
return false;
}
bool MVT::isExtendedInteger() const {
assert(isExtended() && "Type is not extended!");
return dynamic_cast<const ExtendedIntegerType *>(LLVMTy) != 0;
}
bool MVT::isExtendedVector() const {
assert(isExtended() && "Type is not extended!");
return dynamic_cast<const ExtendedVectorType *>(LLVMTy) != 0;
}
bool MVT::isExtended64BitVector() const {
assert(isExtended() && "Type is not extended!");
return isExtendedVector() && getSizeInBits() == 64;
}
bool MVT::isExtended128BitVector() const {
assert(isExtended() && "Type is not extended!");
return isExtendedVector() && getSizeInBits() == 128;
}
MVT MVT::getExtendedVectorElementType() const {
assert(isExtendedVector() && "Type is not an extended vector!");
return static_cast<const ExtendedVectorType *>(LLVMTy)->getElementType();
}
unsigned MVT::getExtendedVectorNumElements() const {
assert(isExtendedVector() && "Type is not an extended vector!");
return static_cast<const ExtendedVectorType *>(LLVMTy)->getNumElements();
}
unsigned MVT::getExtendedSizeInBits() const {
assert(isExtended() && "Type is not extended!");
return LLVMTy->getSizeInBits();
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <vbahelper/helperdecl.hxx>
#include "vbauserform.hxx"
#include <com/sun/star/awt/XControl.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/awt/XWindow2.hpp>
#include <com/sun/star/awt/PosSize.hpp>
#include <com/sun/star/beans/PropertyConcept.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/util/MeasureUnit.hpp>
#include <basic/sbx.hxx>
#include <basic/sbstar.hxx>
#include <basic/sbmeth.hxx>
#include "vbacontrols.hxx"
using namespace ::ooo::vba;
using namespace ::com::sun::star;
// some little notes
// XDialog implementation has the following interesting bits
// a Controls property ( which is an array of the container controls )
// each item in the controls array is a XControl, where the model is
// basically a property bag
// additionally the XDialog instance has itself a model
// this model has a ControlModels ( array of models ) property
// the models in ControlModels can be accessed by name
// also the XDialog is a XControl ( to access the model above
ScVbaUserForm::ScVbaUserForm( uno::Sequence< uno::Any > const& aArgs, uno::Reference< uno::XComponentContext >const& xContext ) throw ( lang::IllegalArgumentException ) : ScVbaUserForm_BASE( getXSomethingFromArgs< XHelperInterface >( aArgs, 0 ), xContext, getXSomethingFromArgs< uno::XInterface >( aArgs, 1 ), getXSomethingFromArgs< frame::XModel >( aArgs, 2 ), static_cast< ooo::vba::AbstractGeometryAttributes* >(0) ), mbDispose( true )
{
m_xDialog.set( m_xControl, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
m_xProps.set( xControl->getModel(), uno::UNO_QUERY_THROW );
setGeometryHelper( new UserFormGeometryHelper( xContext, xControl, 0.0, 0.0 ) );
if ( aArgs.getLength() >= 4 )
aArgs[ 3 ] >>= m_sLibName;
}
ScVbaUserForm::~ScVbaUserForm()
{
}
void SAL_CALL
ScVbaUserForm::Show( ) throw (uno::RuntimeException, std::exception)
{
SAL_INFO("vbahelper", "ScVbaUserForm::Show( )");
short aRet = 0;
mbDispose = true;
if ( m_xDialog.is() )
{
// try to center dialog on model window
if( m_xModel.is() ) try
{
uno::Reference< frame::XController > xController( m_xModel->getCurrentController(), uno::UNO_SET_THROW );
uno::Reference< frame::XFrame > xFrame( xController->getFrame(), uno::UNO_SET_THROW );
uno::Reference< awt::XWindow > xWindow( xFrame->getContainerWindow(), uno::UNO_SET_THROW );
awt::Rectangle aPosSize = xWindow->getPosSize(); // already in pixel
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XWindow > xControlWindow( xControl->getPeer(), uno::UNO_QUERY_THROW );
xControlWindow->setPosSize(static_cast<sal_Int32>((aPosSize.Width - getWidth()) / 2.0), static_cast<sal_Int32>((aPosSize.Height - getHeight()) / 2.0), 0, 0, awt::PosSize::POS );
}
catch( uno::Exception& )
{
}
aRet = m_xDialog->execute();
}
SAL_INFO("vbahelper", "ScVbaUserForm::Show() execute returned " << aRet);
if ( mbDispose )
{
try
{
uno::Reference< lang::XComponent > xComp( m_xDialog, uno::UNO_QUERY_THROW );
m_xDialog = NULL;
xComp->dispose();
mbDispose = false;
}
catch( uno::Exception& )
{
}
}
}
OUString SAL_CALL
ScVbaUserForm::getCaption() throw (uno::RuntimeException, std::exception)
{
OUString sCaption;
m_xProps->getPropertyValue( "Title" ) >>= sCaption;
return sCaption;
}
void
ScVbaUserForm::setCaption( const OUString& _caption ) throw (uno::RuntimeException, std::exception)
{
m_xProps->setPropertyValue( "Title", uno::makeAny( _caption ) );
}
sal_Bool SAL_CALL
ScVbaUserForm::getVisible() throw (uno::RuntimeException, std::exception)
{
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XWindow2 > xControlWindow( xControl->getPeer(), uno::UNO_QUERY_THROW );
return xControlWindow->isVisible();
}
void SAL_CALL
ScVbaUserForm::setVisible( sal_Bool bVis ) throw (uno::RuntimeException, std::exception)
{
if ( bVis )
Show();
else
Hide();
}
double SAL_CALL ScVbaUserForm::getInnerWidth() throw (uno::RuntimeException, std::exception)
{
return mpGeometryHelper->getInnerWidth();
}
void SAL_CALL ScVbaUserForm::setInnerWidth( double fInnerWidth ) throw (uno::RuntimeException, std::exception)
{
mpGeometryHelper->setInnerWidth( fInnerWidth );
}
double SAL_CALL ScVbaUserForm::getInnerHeight() throw (uno::RuntimeException, std::exception)
{
return mpGeometryHelper->getInnerHeight();
}
void SAL_CALL ScVbaUserForm::setInnerHeight( double fInnerHeight ) throw (uno::RuntimeException, std::exception)
{
mpGeometryHelper->setInnerHeight( fInnerHeight );
}
void SAL_CALL
ScVbaUserForm::Hide( ) throw (uno::RuntimeException, std::exception)
{
mbDispose = false; // hide not dispose
if ( m_xDialog.is() )
m_xDialog->endExecute();
}
void SAL_CALL
ScVbaUserForm::RePaint( ) throw (uno::RuntimeException, std::exception)
{
// #STUB
// do nothing
}
void SAL_CALL
ScVbaUserForm::UnloadObject( ) throw (uno::RuntimeException, std::exception)
{
mbDispose = true;
if ( m_xDialog.is() )
m_xDialog->endExecute();
}
OUString
ScVbaUserForm::getServiceImplName()
{
return OUString("ScVbaUserForm");
}
uno::Sequence< OUString >
ScVbaUserForm::getServiceNames()
{
static uno::Sequence< OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = "ooo.vba.excel.UserForm";
}
return aServiceNames;
}
uno::Reference< beans::XIntrospectionAccess > SAL_CALL
ScVbaUserForm::getIntrospection( ) throw (uno::RuntimeException, std::exception)
{
return uno::Reference< beans::XIntrospectionAccess >();
}
uno::Any SAL_CALL
ScVbaUserForm::invoke( const OUString& /*aFunctionName*/, const uno::Sequence< uno::Any >& /*aParams*/, uno::Sequence< ::sal_Int16 >& /*aOutParamIndex*/, uno::Sequence< uno::Any >& /*aOutParam*/ ) throw (lang::IllegalArgumentException, script::CannotConvertException, reflection::InvocationTargetException, uno::RuntimeException, std::exception)
{
throw uno::RuntimeException(); // unsupported operation
}
void SAL_CALL
ScVbaUserForm::setValue( const OUString& aPropertyName, const uno::Any& aValue ) throw (beans::UnknownPropertyException, script::CannotConvertException, reflection::InvocationTargetException, uno::RuntimeException, std::exception)
{
uno::Any aObject = getValue( aPropertyName );
// in case the dialog is already closed the VBA implementation should not throw exceptions
if ( aObject.hasValue() )
{
// The Object *must* support XDefaultProperty here because getValue will
// only return properties that are Objects ( e.g. controls )
// e.g. Userform1.aControl = something
// 'aControl' has to support XDefaultProperty to make sense here
uno::Reference< script::XDefaultProperty > xDfltProp( aObject, uno::UNO_QUERY_THROW );
OUString aDfltPropName = xDfltProp->getDefaultPropertyName();
uno::Reference< beans::XIntrospectionAccess > xUnoAccess( getIntrospectionAccess( aObject ) );
uno::Reference< beans::XPropertySet > xPropSet( xUnoAccess->queryAdapter( ::getCppuType( (const uno::Reference< beans::XPropertySet > *)0 ) ), uno::UNO_QUERY_THROW );
xPropSet->setPropertyValue( aDfltPropName, aValue );
}
}
uno::Reference< awt::XControl >
ScVbaUserForm::nestedSearch( const OUString& aPropertyName, uno::Reference< awt::XControlContainer >& xContainer )
{
uno::Reference< awt::XControl > xControl = xContainer->getControl( aPropertyName );
if ( !xControl.is() )
{
uno::Sequence< uno::Reference< awt::XControl > > aControls = xContainer->getControls();
const uno::Reference< awt::XControl >* pCtrl = aControls.getConstArray();
const uno::Reference< awt::XControl >* pCtrlsEnd = pCtrl + aControls.getLength();
for ( ; pCtrl < pCtrlsEnd; ++pCtrl )
{
uno::Reference< awt::XControlContainer > xC( *pCtrl, uno::UNO_QUERY );
if ( xC.is() )
{
xControl.set( nestedSearch( aPropertyName, xC ) );
if ( xControl.is() )
break;
}
}
}
return xControl;
}
uno::Any SAL_CALL
ScVbaUserForm::getValue( const OUString& aPropertyName ) throw (beans::UnknownPropertyException, uno::RuntimeException, std::exception)
{
uno::Any aResult;
// in case the dialog is already closed the VBA implementation should not throw exceptions
if ( m_xDialog.is() )
{
uno::Reference< awt::XControl > xDialogControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControlContainer > xContainer( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControl > xControl = nestedSearch( aPropertyName, xContainer );
xContainer->getControl( aPropertyName );
if ( xControl.is() )
{
uno::Reference< msforms::XControl > xVBAControl = ScVbaControlFactory::createUserformControl( mxContext, xControl, xDialogControl, m_xModel, mpGeometryHelper->getOffsetX(), mpGeometryHelper->getOffsetY() );
ScVbaControl* pControl = dynamic_cast< ScVbaControl* >( xVBAControl.get() );
if ( !m_sLibName.isEmpty() )
pControl->setLibraryAndCodeName( m_sLibName.concat( "." ).concat( getName() ) );
aResult = uno::makeAny( xVBAControl );
}
}
return aResult;
}
::sal_Bool SAL_CALL
ScVbaUserForm::hasMethod( const OUString& /*aName*/ ) throw (uno::RuntimeException, std::exception)
{
return sal_False;
}
uno::Any SAL_CALL
ScVbaUserForm::Controls( const uno::Any& index ) throw (uno::RuntimeException, std::exception)
{
// if the dialog already closed we should do nothing, but the VBA will call methods of the Controls objects
// thus we have to provide a dummy object in this case
uno::Reference< awt::XControl > xDialogControl( m_xDialog, uno::UNO_QUERY );
uno::Reference< XCollection > xControls( new ScVbaControls( this, mxContext, xDialogControl, m_xModel, mpGeometryHelper->getOffsetX(), mpGeometryHelper->getOffsetY() ) );
if ( index.hasValue() )
return uno::makeAny( xControls->Item( index, uno::Any() ) );
return uno::makeAny( xControls );
}
::sal_Bool SAL_CALL
ScVbaUserForm::hasProperty( const OUString& aName ) throw (uno::RuntimeException, std::exception)
{
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY );
SAL_INFO("vbahelper", "ScVbaUserForm::hasProperty(" << aName << ") " << xControl.is() );
if ( xControl.is() )
{
uno::Reference< beans::XPropertySet > xDlgProps( xControl->getModel(), uno::UNO_QUERY );
if ( xDlgProps.is() )
{
uno::Reference< container::XNameContainer > xAllChildren( xDlgProps->getPropertyValue( "AllDialogChildren" ), uno::UNO_QUERY_THROW );
sal_Bool bRes = xAllChildren->hasByName( aName );
SAL_INFO("vbahelper", "ScVbaUserForm::hasProperty(" << aName << ") " << xAllChildren.is() << " ---> " << bRes );
return bRes;
}
}
return sal_False;
}
namespace userform
{
namespace sdecl = comphelper::service_decl;
sdecl::vba_service_class_<ScVbaUserForm, sdecl::with_args<true> > serviceImpl;
extern sdecl::ServiceDecl const serviceDecl(
serviceImpl,
"ScVbaUserForm",
"ooo.vba.msforms.UserForm" );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#982489 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <vbahelper/helperdecl.hxx>
#include "vbauserform.hxx"
#include <com/sun/star/awt/XControl.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/awt/XWindow2.hpp>
#include <com/sun/star/awt/PosSize.hpp>
#include <com/sun/star/beans/PropertyConcept.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/util/MeasureUnit.hpp>
#include <basic/sbx.hxx>
#include <basic/sbstar.hxx>
#include <basic/sbmeth.hxx>
#include "vbacontrols.hxx"
using namespace ::ooo::vba;
using namespace ::com::sun::star;
// some little notes
// XDialog implementation has the following interesting bits
// a Controls property ( which is an array of the container controls )
// each item in the controls array is a XControl, where the model is
// basically a property bag
// additionally the XDialog instance has itself a model
// this model has a ControlModels ( array of models ) property
// the models in ControlModels can be accessed by name
// also the XDialog is a XControl ( to access the model above
ScVbaUserForm::ScVbaUserForm( uno::Sequence< uno::Any > const& aArgs, uno::Reference< uno::XComponentContext >const& xContext ) throw ( lang::IllegalArgumentException ) : ScVbaUserForm_BASE( getXSomethingFromArgs< XHelperInterface >( aArgs, 0 ), xContext, getXSomethingFromArgs< uno::XInterface >( aArgs, 1 ), getXSomethingFromArgs< frame::XModel >( aArgs, 2 ), static_cast< ooo::vba::AbstractGeometryAttributes* >(0) ), mbDispose( true )
{
m_xDialog.set( m_xControl, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
m_xProps.set( xControl->getModel(), uno::UNO_QUERY_THROW );
setGeometryHelper( new UserFormGeometryHelper( xContext, xControl, 0.0, 0.0 ) );
if ( aArgs.getLength() >= 4 )
aArgs[ 3 ] >>= m_sLibName;
}
ScVbaUserForm::~ScVbaUserForm()
{
}
void SAL_CALL
ScVbaUserForm::Show( ) throw (uno::RuntimeException, std::exception)
{
SAL_INFO("vbahelper", "ScVbaUserForm::Show( )");
short aRet = 0;
mbDispose = true;
if ( m_xDialog.is() )
{
// try to center dialog on model window
if( m_xModel.is() ) try
{
uno::Reference< frame::XController > xController( m_xModel->getCurrentController(), uno::UNO_SET_THROW );
uno::Reference< frame::XFrame > xFrame( xController->getFrame(), uno::UNO_SET_THROW );
uno::Reference< awt::XWindow > xWindow( xFrame->getContainerWindow(), uno::UNO_SET_THROW );
awt::Rectangle aPosSize = xWindow->getPosSize(); // already in pixel
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XWindow > xControlWindow( xControl->getPeer(), uno::UNO_QUERY_THROW );
xControlWindow->setPosSize(static_cast<sal_Int32>((aPosSize.Width - getWidth()) / 2.0), static_cast<sal_Int32>((aPosSize.Height - getHeight()) / 2.0), 0, 0, awt::PosSize::POS );
}
catch( uno::Exception& )
{
}
aRet = m_xDialog->execute();
}
SAL_INFO("vbahelper", "ScVbaUserForm::Show() execute returned " << aRet);
if ( mbDispose )
{
try
{
uno::Reference< lang::XComponent > xComp( m_xDialog, uno::UNO_QUERY_THROW );
m_xDialog = NULL;
xComp->dispose();
mbDispose = false;
}
catch( uno::Exception& )
{
}
}
}
OUString SAL_CALL
ScVbaUserForm::getCaption() throw (uno::RuntimeException, std::exception)
{
OUString sCaption;
m_xProps->getPropertyValue( "Title" ) >>= sCaption;
return sCaption;
}
void
ScVbaUserForm::setCaption( const OUString& _caption ) throw (uno::RuntimeException, std::exception)
{
m_xProps->setPropertyValue( "Title", uno::makeAny( _caption ) );
}
sal_Bool SAL_CALL
ScVbaUserForm::getVisible() throw (uno::RuntimeException, std::exception)
{
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XWindow2 > xControlWindow( xControl->getPeer(), uno::UNO_QUERY_THROW );
return xControlWindow->isVisible();
}
void SAL_CALL
ScVbaUserForm::setVisible( sal_Bool bVis ) throw (uno::RuntimeException, std::exception)
{
if ( bVis )
Show();
else
Hide();
}
double SAL_CALL ScVbaUserForm::getInnerWidth() throw (uno::RuntimeException, std::exception)
{
return mpGeometryHelper->getInnerWidth();
}
void SAL_CALL ScVbaUserForm::setInnerWidth( double fInnerWidth ) throw (uno::RuntimeException, std::exception)
{
mpGeometryHelper->setInnerWidth( fInnerWidth );
}
double SAL_CALL ScVbaUserForm::getInnerHeight() throw (uno::RuntimeException, std::exception)
{
return mpGeometryHelper->getInnerHeight();
}
void SAL_CALL ScVbaUserForm::setInnerHeight( double fInnerHeight ) throw (uno::RuntimeException, std::exception)
{
mpGeometryHelper->setInnerHeight( fInnerHeight );
}
void SAL_CALL
ScVbaUserForm::Hide( ) throw (uno::RuntimeException, std::exception)
{
mbDispose = false; // hide not dispose
if ( m_xDialog.is() )
m_xDialog->endExecute();
}
void SAL_CALL
ScVbaUserForm::RePaint( ) throw (uno::RuntimeException, std::exception)
{
// #STUB
// do nothing
}
void SAL_CALL
ScVbaUserForm::UnloadObject( ) throw (uno::RuntimeException, std::exception)
{
mbDispose = true;
if ( m_xDialog.is() )
m_xDialog->endExecute();
}
OUString
ScVbaUserForm::getServiceImplName()
{
return OUString("ScVbaUserForm");
}
uno::Sequence< OUString >
ScVbaUserForm::getServiceNames()
{
static uno::Sequence< OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = "ooo.vba.excel.UserForm";
}
return aServiceNames;
}
uno::Reference< beans::XIntrospectionAccess > SAL_CALL
ScVbaUserForm::getIntrospection( ) throw (uno::RuntimeException, std::exception)
{
return uno::Reference< beans::XIntrospectionAccess >();
}
uno::Any SAL_CALL
ScVbaUserForm::invoke( const OUString& /*aFunctionName*/, const uno::Sequence< uno::Any >& /*aParams*/, uno::Sequence< ::sal_Int16 >& /*aOutParamIndex*/, uno::Sequence< uno::Any >& /*aOutParam*/ ) throw (lang::IllegalArgumentException, script::CannotConvertException, reflection::InvocationTargetException, uno::RuntimeException, std::exception)
{
throw uno::RuntimeException(); // unsupported operation
}
void SAL_CALL
ScVbaUserForm::setValue( const OUString& aPropertyName, const uno::Any& aValue ) throw (beans::UnknownPropertyException, script::CannotConvertException, reflection::InvocationTargetException, uno::RuntimeException, std::exception)
{
uno::Any aObject = getValue( aPropertyName );
// in case the dialog is already closed the VBA implementation should not throw exceptions
if ( aObject.hasValue() )
{
// The Object *must* support XDefaultProperty here because getValue will
// only return properties that are Objects ( e.g. controls )
// e.g. Userform1.aControl = something
// 'aControl' has to support XDefaultProperty to make sense here
uno::Reference< script::XDefaultProperty > xDfltProp( aObject, uno::UNO_QUERY_THROW );
OUString aDfltPropName = xDfltProp->getDefaultPropertyName();
uno::Reference< beans::XIntrospectionAccess > xUnoAccess( getIntrospectionAccess( aObject ) );
uno::Reference< beans::XPropertySet > xPropSet( xUnoAccess->queryAdapter( ::getCppuType( (const uno::Reference< beans::XPropertySet > *)0 ) ), uno::UNO_QUERY_THROW );
xPropSet->setPropertyValue( aDfltPropName, aValue );
}
}
uno::Reference< awt::XControl >
ScVbaUserForm::nestedSearch( const OUString& aPropertyName, uno::Reference< awt::XControlContainer >& xContainer )
{
uno::Reference< awt::XControl > xControl = xContainer->getControl( aPropertyName );
if ( !xControl.is() )
{
uno::Sequence< uno::Reference< awt::XControl > > aControls = xContainer->getControls();
const uno::Reference< awt::XControl >* pCtrl = aControls.getConstArray();
const uno::Reference< awt::XControl >* pCtrlsEnd = pCtrl + aControls.getLength();
for ( ; pCtrl < pCtrlsEnd; ++pCtrl )
{
uno::Reference< awt::XControlContainer > xC( *pCtrl, uno::UNO_QUERY );
if ( xC.is() )
{
xControl.set( nestedSearch( aPropertyName, xC ) );
if ( xControl.is() )
break;
}
}
}
return xControl;
}
uno::Any SAL_CALL
ScVbaUserForm::getValue( const OUString& aPropertyName ) throw (beans::UnknownPropertyException, uno::RuntimeException, std::exception)
{
uno::Any aResult;
// in case the dialog is already closed the VBA implementation should not throw exceptions
if ( m_xDialog.is() )
{
uno::Reference< awt::XControl > xDialogControl( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControlContainer > xContainer( m_xDialog, uno::UNO_QUERY_THROW );
uno::Reference< awt::XControl > xControl = nestedSearch( aPropertyName, xContainer );
xContainer->getControl( aPropertyName );
if ( xControl.is() )
{
uno::Reference< msforms::XControl > xVBAControl = ScVbaControlFactory::createUserformControl( mxContext, xControl, xDialogControl, m_xModel, mpGeometryHelper->getOffsetX(), mpGeometryHelper->getOffsetY() );
ScVbaControl* pControl = dynamic_cast< ScVbaControl* >( xVBAControl.get() );
if (pControl && !m_sLibName.isEmpty())
pControl->setLibraryAndCodeName( m_sLibName.concat( "." ).concat( getName() ) );
aResult = uno::makeAny( xVBAControl );
}
}
return aResult;
}
::sal_Bool SAL_CALL
ScVbaUserForm::hasMethod( const OUString& /*aName*/ ) throw (uno::RuntimeException, std::exception)
{
return sal_False;
}
uno::Any SAL_CALL
ScVbaUserForm::Controls( const uno::Any& index ) throw (uno::RuntimeException, std::exception)
{
// if the dialog already closed we should do nothing, but the VBA will call methods of the Controls objects
// thus we have to provide a dummy object in this case
uno::Reference< awt::XControl > xDialogControl( m_xDialog, uno::UNO_QUERY );
uno::Reference< XCollection > xControls( new ScVbaControls( this, mxContext, xDialogControl, m_xModel, mpGeometryHelper->getOffsetX(), mpGeometryHelper->getOffsetY() ) );
if ( index.hasValue() )
return uno::makeAny( xControls->Item( index, uno::Any() ) );
return uno::makeAny( xControls );
}
::sal_Bool SAL_CALL
ScVbaUserForm::hasProperty( const OUString& aName ) throw (uno::RuntimeException, std::exception)
{
uno::Reference< awt::XControl > xControl( m_xDialog, uno::UNO_QUERY );
SAL_INFO("vbahelper", "ScVbaUserForm::hasProperty(" << aName << ") " << xControl.is() );
if ( xControl.is() )
{
uno::Reference< beans::XPropertySet > xDlgProps( xControl->getModel(), uno::UNO_QUERY );
if ( xDlgProps.is() )
{
uno::Reference< container::XNameContainer > xAllChildren( xDlgProps->getPropertyValue( "AllDialogChildren" ), uno::UNO_QUERY_THROW );
sal_Bool bRes = xAllChildren->hasByName( aName );
SAL_INFO("vbahelper", "ScVbaUserForm::hasProperty(" << aName << ") " << xAllChildren.is() << " ---> " << bRes );
return bRes;
}
}
return sal_False;
}
namespace userform
{
namespace sdecl = comphelper::service_decl;
sdecl::vba_service_class_<ScVbaUserForm, sdecl::with_args<true> > serviceImpl;
extern sdecl::ServiceDecl const serviceDecl(
serviceImpl,
"ScVbaUserForm",
"ooo.vba.msforms.UserForm" );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _JPEG_TRANSFROM_HXX
#define _JPEG_TRANSFORM_HXX
#include <tools/solar.h>
#include <vcl/graph.hxx>
class JpegTransform
{
sal_uInt16 maRotate;
SvStream& mrInputStream;
SvStream& mrOutputStream;
public:
JpegTransform(SvStream& rInputStream, SvStream& rOutputStream);
virtual ~JpegTransform();
void setRotate(sal_uInt16 aRotate);
bool perform();
};
#endif // _JPEG_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wheader-guard<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _JPEG_TRANSFORM_HXX
#define _JPEG_TRANSFORM_HXX
#include <tools/solar.h>
#include <vcl/graph.hxx>
class JpegTransform
{
sal_uInt16 maRotate;
SvStream& mrInputStream;
SvStream& mrOutputStream;
public:
JpegTransform(SvStream& rInputStream, SvStream& rOutputStream);
virtual ~JpegTransform();
void setRotate(sal_uInt16 aRotate);
bool perform();
};
#endif // _JPEG_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "include/a_devdiag.h"
#include "include/netstructures.h"
void a_devdiag() {
pcap_if_t *alldevs;
char errbuf[PCAP_ERRBUF_SIZE];
if (pcap_findalldevs(&alldevs, errbuf) == -1) {
printf("Could not find all network devices: %s\n", errbuf);
exit(1);
}
int i = 0;
pcap_if_t *d;
for (d = alldevs; d; d = d->next) {
printf("%d. %s", ++i, d->name);
if (d->description) {
printf(" - %s (%s)\n\n", d->description, getDeviceStatus(d));
}
}
int inum;
printf("Enter the interface number (1-%d): ", i);
scanf_s("%d", &inum);
for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);
pcap_t *adhandle;
if ((adhandle = pcap_open_live(d->name, 65536, 1000, NULL, errbuf)) == NULL) {
printf("Unable to open the network adapter! %s is not supported by WinPcap\n", d->name);
pcap_freealldevs(alldevs);
exit(1);
}
if (pcap_datalink(adhandle) != DLT_EN10MB) {
printf("Not using an ethernet device: output may not always be correct.\n");
}
u_int netmask;
if (d->addresses != NULL) {
netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else {
netmask = 0xffffff;
}
struct bpf_program fcode;
char a_packetfilter[] = "ip and udp";
if (pcap_compile(adhandle, &fcode, a_packetfilter, 1, netmask) < 0) {
printf("Unable to compile packet filter!\n");
pcap_freealldevs(alldevs);
exit(1);
}
if (pcap_setfilter(adhandle, &fcode) < 0) {
printf("Unable to set packet filter!\n");
pcap_freealldevs(alldevs);
exit(1);
}
pcap_freealldevs(alldevs);
printf("\nStarting active diagnostics...\n\n");
pcap_loop(adhandle, INFINITE, a_packethandler, NULL);
}
char* getDeviceStatus(pcap_if_t* d) {
return "status";
}
void a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
struct tm ltime;
char timestr[16];
ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport, dport;
time_t local_tv_sec;
(VOID)(param);
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime(timestr, sizeof(timestr), "%H:%M:%S", <ime);
printf("%s,%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
ih = (ip_header *)(pkt_data + 14);
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *)((u_char *)ih + ip_len);
sport = ntohs(uh->sport);
dport = ntohs(uh->dport);
printf("%d.%d.%d.%d:%d -> %d.%d.%d.%d:%d \n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
}<commit_msg>Detected whether or not a network device is active<commit_after>#include "include/a_devdiag.h"
#include "include/netstructures.h"
void a_devdiag() {
pcap_if_t *alldevs;
char errbuf[PCAP_ERRBUF_SIZE];
if (pcap_findalldevs(&alldevs, errbuf) == -1) {
printf("Could not find all network devices: %s\n", errbuf);
exit(1);
}
int i = 0;
pcap_if_t *d;
for (d = alldevs; d; d = d->next) {
printf("%d. %s", ++i, d->name);
if (d->description) {
printf(" - %s (%s)\n\n", d->description, getDeviceStatus(d));
}
}
int inum;
printf("Enter the interface number (1-%d): ", i);
scanf_s("%d", &inum);
for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);
pcap_t *adhandle;
if ((adhandle = pcap_open_live(d->name, 65536, 1, 1000, errbuf)) == NULL) {
printf("Unable to open the network adapter! %s is not supported by WinPcap\n", d->name);
pcap_freealldevs(alldevs);
exit(1);
}
if (pcap_datalink(adhandle) != DLT_EN10MB) {
printf("Not using an ethernet device: output may not always be correct.\n");
}
u_int netmask;
if (d->addresses != NULL) {
netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
}
else {
netmask = 0xffffff;
}
struct bpf_program fcode;
char a_packetfilter[] = "ip and udp";
if (pcap_compile(adhandle, &fcode, a_packetfilter, 1, netmask) < 0) {
printf("Unable to compile packet filter!\n");
pcap_freealldevs(alldevs);
exit(1);
}
if (pcap_setfilter(adhandle, &fcode) < 0) {
printf("Unable to set packet filter!\n");
pcap_freealldevs(alldevs);
exit(1);
}
pcap_freealldevs(alldevs);
printf("\nStarting active diagnostics...\n\n");
pcap_loop(adhandle, INFINITE, a_packethandler, NULL);
}
char* getDeviceStatus(pcap_if_t* d) {
int count = 1;
pcap_t *_d;
char _errbuf[PCAP_ERRBUF_SIZE];
if ((_d = pcap_open_live(d->name, 100, 1, 1000, _errbuf)) == NULL) {
printf("Unable to open device %s.\n", d->name);
return "err";
}
const u_char *pkt_data;
struct pcap_pkthdr *header;
int res;
res = pcap_next_ex(_d, &header, &pkt_data);
if (res == 0) {
return "timeout";
}
else {
return "active";
}
}
void a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {
struct tm ltime;
char timestr[16];
ip_header *ih;
udp_header *uh;
u_int ip_len;
u_short sport, dport;
time_t local_tv_sec;
(VOID)(param);
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime(timestr, sizeof(timestr), "%H:%M:%S", <ime);
printf("%s,%.6d len:%d ", timestr, header->ts.tv_usec, header->len);
ih = (ip_header *)(pkt_data + 14);
ip_len = (ih->ver_ihl & 0xf) * 4;
uh = (udp_header *)((u_char *)ih + ip_len);
sport = ntohs(uh->sport);
dport = ntohs(uh->dport);
printf("%d.%d.%d.%d:%d -> %d.%d.%d.%d:%d \n",
ih->saddr.byte1,
ih->saddr.byte2,
ih->saddr.byte3,
ih->saddr.byte4,
sport,
ih->daddr.byte1,
ih->daddr.byte2,
ih->daddr.byte3,
ih->daddr.byte4,
dport);
}<|endoftext|> |
<commit_before>#include <vsmc/utility/tuple_manip.hpp>
#include <vsmc/internal/traits.hpp>
#include <cassert>
namespace temp_ns {
VSMC_DEFINE_TUPLE_APPLY(Vector, std::vector)
}
int main ()
{
assert(VSMC_HAS_CXX11_VARIADIC_TEMPLATES);
using vsmc::cxx11::is_same;
typedef std::tuple<> empty;
typedef std::tuple<char, short, int, long> full;
typedef std::tuple<char, short> tp1;
typedef std::tuple<int, long> tp2;
{
typedef vsmc::TuplePushFront<empty, int>::type t1;
assert((is_same<t1, std::tuple<int> >::value));
typedef vsmc::TuplePushFront<t1, char>::type t2;
assert((is_same<t2, std::tuple<char, int> >::value));
typedef vsmc::TuplePushFront<t2, long>::type t3;
assert((is_same<t3, std::tuple<long, char, int> >::value));
}
{
typedef vsmc::TuplePushBack<empty, int>::type t1;
assert((is_same<t1, std::tuple<int> >::value));
typedef vsmc::TuplePushBack<t1, char>::type t2;
assert((is_same<t2, std::tuple<int, char> >::value));
typedef vsmc::TuplePushBack<t2, long>::type t3;
assert((is_same<t3, std::tuple<int, char, long> >::value));
}
{
typedef vsmc::TuplePopFront<full>::type t1;
assert((is_same<t1, std::tuple<short, int, long> >::value));
typedef vsmc::TuplePopFront<t1>::type t2;
assert((is_same<t2, std::tuple<int, long> >::value));
typedef vsmc::TuplePopFront<t2>::type t3;
assert((is_same<t3, std::tuple<long> >::value));
typedef vsmc::TuplePopFront<t3>::type t4;
assert((is_same<t4, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopBack<full>::type t1;
assert((is_same<t1, std::tuple<char, short, int> >::value));
typedef vsmc::TuplePopBack<t1>::type t2;
assert((is_same<t2, std::tuple<char, short> >::value));
typedef vsmc::TuplePopBack<t2>::type t3;
assert((is_same<t3, std::tuple<char> >::value));
typedef vsmc::TuplePopBack<t3>::type t4;
assert((is_same<t4, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopFrontN<full, 0>::type t0;
assert((is_same<t0, std::tuple<char, short, int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 1>::type t1;
assert((is_same<t1, std::tuple<short, int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 2>::type t2;
assert((is_same<t2, std::tuple<int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 3>::type t3;
assert((is_same<t3, std::tuple<long> >::value));
typedef vsmc::TuplePopFrontN<full, 4>::type t4;
assert((is_same<t4, std::tuple<> >::value));
typedef vsmc::TuplePopFrontN<full, 5>::type t5;
assert((is_same<t5, std::tuple<> >::value));
typedef vsmc::TuplePopFrontN<empty, 1>::type t6;
assert((is_same<t6, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopBackN<full, 0>::type t0;
assert((is_same<t0, std::tuple<char, short, int, long> >::value));
typedef vsmc::TuplePopBackN<full, 1>::type t1;
assert((is_same<t1, std::tuple<char, short, int> >::value));
typedef vsmc::TuplePopBackN<full, 2>::type t2;
assert((is_same<t2, std::tuple<char, short> >::value));
typedef vsmc::TuplePopBackN<full, 3>::type t3;
assert((is_same<t3, std::tuple<char> >::value));
typedef vsmc::TuplePopBackN<full, 4>::type t4;
assert((is_same<t4, std::tuple<> >::value));
typedef vsmc::TuplePopBackN<full, 5>::type t5;
assert((is_same<t5, std::tuple<> >::value));
typedef vsmc::TuplePopBackN<empty, 1>::type t6;
assert((is_same<t6, std::tuple<> >::value));
}
{
typedef vsmc::TupleMerge<tp1, tp2>::type t1;
assert((is_same<t1, std::tuple<char, short, int, long> >::value));
typedef vsmc::TupleMerge<tp2, tp1>::type t2;
assert((is_same<t2, std::tuple<int, long, char, short> >::value));
typedef vsmc::TupleMerge<tp1, empty>::type t3;
assert((is_same<t3, tp1>::value));
typedef vsmc::TupleMerge<empty, tp1>::type t4;
assert((is_same<t4, tp1>::value));
typedef vsmc::TupleMerge<empty, empty>::type t5;
assert((is_same<t5, empty>::value));
}
{
typedef vsmc::TupleCat<
empty, full, empty, tp1, empty, tp2, empty>::type t1;
assert((is_same<t1, std::tuple<
char, short, int, long, char, short, int, long> >::value));
}
{
typedef temp_ns::TupleApplyVector<full>::type tc;
assert((is_same<tc, std::tuple<
std::vector<char>,
std::vector<short>,
std::vector<int>,
std::vector<long> > >::value));
}
return 0;
}
<commit_msg>fix Tuple test<commit_after>#include <vsmc/utility/tuple_manip.hpp>
template <typename VecType, typename TpType>
inline void assign_vec (VecType &vec, const TpType &tp, vsmc::Position<0>)
{
std::get<0>(vec).push_back(std::get<0>(tp));
}
template <typename VecType, typename TpType, std::size_t Pos>
inline void assign_vec (VecType &vec, const TpType &tp, vsmc::Position<Pos>)
{
std::get<Pos>(vec).push_back(std::get<Pos>(tp));
assign_vec(vec, tp, vsmc::Position<Pos - 1>());
}
template <typename... Types>
inline std::tuple<std::vector<Types>...> create_vec (
const std::tuple<Types...> &tp)
{
std::tuple<std::vector<Types>...> vec;
assign_vec(vec, tp, vsmc::Position<sizeof...(Types) - 1>());
return vec;
}
int main ()
{
assert(VSMC_HAS_CXX11_VARIADIC_TEMPLATES);
using vsmc::cxx11::is_same;
typedef std::tuple<> empty;
typedef std::tuple<char, short, int, long> full;
typedef std::tuple<char, short> tp1;
typedef std::tuple<int, long> tp2;
{
typedef vsmc::TuplePushFront<empty, int>::type t1;
assert((is_same<t1, std::tuple<int> >::value));
typedef vsmc::TuplePushFront<t1, char>::type t2;
assert((is_same<t2, std::tuple<char, int> >::value));
typedef vsmc::TuplePushFront<t2, long>::type t3;
assert((is_same<t3, std::tuple<long, char, int> >::value));
}
{
typedef vsmc::TuplePushBack<empty, int>::type t1;
assert((is_same<t1, std::tuple<int> >::value));
typedef vsmc::TuplePushBack<t1, char>::type t2;
assert((is_same<t2, std::tuple<int, char> >::value));
typedef vsmc::TuplePushBack<t2, long>::type t3;
assert((is_same<t3, std::tuple<int, char, long> >::value));
}
{
typedef vsmc::TuplePopFront<full>::type t1;
assert((is_same<t1, std::tuple<short, int, long> >::value));
typedef vsmc::TuplePopFront<t1>::type t2;
assert((is_same<t2, std::tuple<int, long> >::value));
typedef vsmc::TuplePopFront<t2>::type t3;
assert((is_same<t3, std::tuple<long> >::value));
typedef vsmc::TuplePopFront<t3>::type t4;
assert((is_same<t4, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopBack<full>::type t1;
assert((is_same<t1, std::tuple<char, short, int> >::value));
typedef vsmc::TuplePopBack<t1>::type t2;
assert((is_same<t2, std::tuple<char, short> >::value));
typedef vsmc::TuplePopBack<t2>::type t3;
assert((is_same<t3, std::tuple<char> >::value));
typedef vsmc::TuplePopBack<t3>::type t4;
assert((is_same<t4, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopFrontN<full, 0>::type t0;
assert((is_same<t0, std::tuple<char, short, int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 1>::type t1;
assert((is_same<t1, std::tuple<short, int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 2>::type t2;
assert((is_same<t2, std::tuple<int, long> >::value));
typedef vsmc::TuplePopFrontN<full, 3>::type t3;
assert((is_same<t3, std::tuple<long> >::value));
typedef vsmc::TuplePopFrontN<full, 4>::type t4;
assert((is_same<t4, std::tuple<> >::value));
typedef vsmc::TuplePopFrontN<full, 5>::type t5;
assert((is_same<t5, std::tuple<> >::value));
typedef vsmc::TuplePopFrontN<empty, 1>::type t6;
assert((is_same<t6, std::tuple<> >::value));
}
{
typedef vsmc::TuplePopBackN<full, 0>::type t0;
assert((is_same<t0, std::tuple<char, short, int, long> >::value));
typedef vsmc::TuplePopBackN<full, 1>::type t1;
assert((is_same<t1, std::tuple<char, short, int> >::value));
typedef vsmc::TuplePopBackN<full, 2>::type t2;
assert((is_same<t2, std::tuple<char, short> >::value));
typedef vsmc::TuplePopBackN<full, 3>::type t3;
assert((is_same<t3, std::tuple<char> >::value));
typedef vsmc::TuplePopBackN<full, 4>::type t4;
assert((is_same<t4, std::tuple<> >::value));
typedef vsmc::TuplePopBackN<full, 5>::type t5;
assert((is_same<t5, std::tuple<> >::value));
typedef vsmc::TuplePopBackN<empty, 1>::type t6;
assert((is_same<t6, std::tuple<> >::value));
}
{
typedef vsmc::TupleMerge<tp1, tp2>::type t1;
assert((is_same<t1, std::tuple<char, short, int, long> >::value));
typedef vsmc::TupleMerge<tp2, tp1>::type t2;
assert((is_same<t2, std::tuple<int, long, char, short> >::value));
typedef vsmc::TupleMerge<tp1, empty>::type t3;
assert((is_same<t3, tp1>::value));
typedef vsmc::TupleMerge<empty, tp1>::type t4;
assert((is_same<t4, tp1>::value));
typedef vsmc::TupleMerge<empty, empty>::type t5;
assert((is_same<t5, empty>::value));
}
{
typedef vsmc::TupleCat<
empty, full, empty, tp1, empty, tp2, empty>::type t1;
assert((is_same<t1, std::tuple<
char, short, int, long, char, short, int, long> >::value));
}
{
full tp;
std::get<0>(tp) = 0;
std::get<1>(tp) = 1;
std::get<2>(tp) = 2;
std::get<3>(tp) = 3;
std::tuple<
std::vector<char>,
std::vector<short>,
std::vector<int>,
std::vector<long>
> vec = create_vec(tp);
assert((std::get<0>(tp) == std::get<0>(vec)[0]));
assert((std::get<1>(tp) == std::get<1>(vec)[0]));
assert((std::get<2>(tp) == std::get<2>(vec)[0]));
assert((std::get<3>(tp) == std::get<3>(vec)[0]));
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <cstdlib>
#ifdef CLEVER_WIN32
# include <direct.h>
# include <windows.h>
# define PATH_MAX MAX_PATH
#else
# include <dirent.h>
# include <unistd.h>
# include <sys/resource.h>
# include <sys/time.h>
#endif
#include "core/value.h"
#include "modules/std/sys/sys.h"
#include "types/native_types.h"
#include "core/pkgmanager.h"
#include "core/cexception.h"
#ifndef PATH_MAX
# define PATH_MAX 1024
#endif
namespace clever { namespace packages { namespace std {
namespace sys {
// Int system(String command)
// Calls a command and returns the exit code
static CLEVER_FUNCTION(system)
{
if (!clever_static_check_args("s")) {
return;
}
result->setInt(::system(args[0]->getStr()->c_str()));
}
// void putenv(String env)
// Sets an environment variable
static CLEVER_FUNCTION(putenv)
{
if (!clever_static_check_args("s")) {
return;
}
::putenv(const_cast<char*>(args[0]->getStr()->c_str()));
}
// String getenv(String env)
// Gets an environment variable
static CLEVER_FUNCTION(getenv)
{
if (!clever_static_check_args("s")) {
return;
}
const char* ret = ::getenv(const_cast<char*>(args[0]->getStr()->c_str()));
if (ret) {
result->setStr(CSTRINGT(ret));
} else {
result->setStr(CSTRING(""));
}
}
// String getcwd()
// Gets the current working directory
static CLEVER_FUNCTION(getcwd)
{
if (!clever_static_check_no_args()) {
return;
}
char temp[PATH_MAX];
const char* path = ::getcwd(temp, PATH_MAX);
result->setStr(CSTRING(path ? path : ""));
}
// String argv(Int n)
// Get n-th argv value
static CLEVER_FUNCTION(argv)
{
/*
size_t i = static_cast<size_t>(CLEVER_ARG_INT(0));
if (i >= (size_t)*g_clever_argc) {
CLEVER_RETURN_EMPTY_STR();
} else {
CLEVER_RETURN_STR(CSTRINGT((*g_clever_argv)[i]));
}
*/
}
// Int argc()
// Get argc value
static CLEVER_FUNCTION(argc)
{
if (!clever_static_check_no_args()) {
return;
}
// CLEVER_RETURN_INT(*g_clever_argc);
}
// Void sleep(Int time)
// Sleep for 'time' milliseconds
static CLEVER_FUNCTION(sleep)
{
if (!clever_static_check_args("i")) {
return;
}
int time = static_cast<int>(args[0]->getInt());
#ifdef CLEVER_WIN32
SleepEx(time, false);
#else
usleep(time * 1000);
#endif
}
// Int clock()
// Returns the execution clock
static CLEVER_FUNCTION(clock)
{
if (!clever_static_check_no_args()) {
return;
}
result->setInt(clock());
}
} // clever::packages::std::os
// Initializes Standard module
CLEVER_MODULE_INIT(SYSModule)
{
addFunction(new Function("system", &CLEVER_NS_FNAME(sys, system)));
addFunction(new Function("putenv", &CLEVER_NS_FNAME(sys, putenv)));
addFunction(new Function("getenv", &CLEVER_NS_FNAME(sys, getenv)));
addFunction(new Function("getcwd", &CLEVER_NS_FNAME(sys, getcwd)));
addFunction(new Function("argc", &CLEVER_NS_FNAME(sys, argc)));
addFunction(new Function("argv", &CLEVER_NS_FNAME(sys, argv)));
addFunction(new Function("sleep", &CLEVER_NS_FNAME(sys, sleep)));
addFunction(new Function("clock", &CLEVER_NS_FNAME(sys, clock)));
}
}}} // clever::packages::std
<commit_msg>- Fix comments<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include <cstdlib>
#ifdef CLEVER_WIN32
# include <direct.h>
# include <windows.h>
# define PATH_MAX MAX_PATH
#else
# include <dirent.h>
# include <unistd.h>
# include <sys/resource.h>
# include <sys/time.h>
#endif
#include "core/value.h"
#include "modules/std/sys/sys.h"
#include "types/native_types.h"
#include "core/pkgmanager.h"
#include "core/cexception.h"
#ifndef PATH_MAX
# define PATH_MAX 1024
#endif
namespace clever { namespace packages { namespace std {
namespace sys {
// system(string command)
// Calls a command and returns the exit code
static CLEVER_FUNCTION(system)
{
if (!clever_static_check_args("s")) {
return;
}
result->setInt(::system(args[0]->getStr()->c_str()));
}
// putenv(string env)
// Sets an environment variable
static CLEVER_FUNCTION(putenv)
{
if (!clever_static_check_args("s")) {
return;
}
::putenv(const_cast<char*>(args[0]->getStr()->c_str()));
}
// getenv(string env)
// Gets an environment variable
static CLEVER_FUNCTION(getenv)
{
if (!clever_static_check_args("s")) {
return;
}
const char* ret = ::getenv(const_cast<char*>(args[0]->getStr()->c_str()));
if (ret) {
result->setStr(CSTRINGT(ret));
} else {
result->setStr(CSTRING(""));
}
}
// getcwd()
// Gets the current working directory
static CLEVER_FUNCTION(getcwd)
{
if (!clever_static_check_no_args()) {
return;
}
char temp[PATH_MAX];
const char* path = ::getcwd(temp, PATH_MAX);
result->setStr(CSTRING(path ? path : ""));
}
// argv(int n)
// Get n-th argv value
static CLEVER_FUNCTION(argv)
{
/*
size_t i = static_cast<size_t>(CLEVER_ARG_INT(0));
if (i >= (size_t)*g_clever_argc) {
CLEVER_RETURN_EMPTY_STR();
} else {
CLEVER_RETURN_STR(CSTRINGT((*g_clever_argv)[i]));
}
*/
}
// argc()
// Get argc value
static CLEVER_FUNCTION(argc)
{
if (!clever_static_check_no_args()) {
return;
}
// CLEVER_RETURN_INT(*g_clever_argc);
}
// sleep(int time)
// Sleep for 'time' milliseconds
static CLEVER_FUNCTION(sleep)
{
if (!clever_static_check_args("i")) {
return;
}
int time = static_cast<int>(args[0]->getInt());
#ifdef CLEVER_WIN32
SleepEx(time, false);
#else
usleep(time * 1000);
#endif
}
// clock()
// Returns the execution clock
static CLEVER_FUNCTION(clock)
{
if (!clever_static_check_no_args()) {
return;
}
result->setInt(clock());
}
} // clever::packages::std::sys
// Initializes Standard module
CLEVER_MODULE_INIT(SYSModule)
{
addFunction(new Function("system", &CLEVER_NS_FNAME(sys, system)));
addFunction(new Function("putenv", &CLEVER_NS_FNAME(sys, putenv)));
addFunction(new Function("getenv", &CLEVER_NS_FNAME(sys, getenv)));
addFunction(new Function("getcwd", &CLEVER_NS_FNAME(sys, getcwd)));
addFunction(new Function("argc", &CLEVER_NS_FNAME(sys, argc)));
addFunction(new Function("argv", &CLEVER_NS_FNAME(sys, argv)));
addFunction(new Function("sleep", &CLEVER_NS_FNAME(sys, sleep)));
addFunction(new Function("clock", &CLEVER_NS_FNAME(sys, clock)));
}
}}} // clever::packages::std
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_vcl.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:47:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): Generated on 2006-09-01 17:50:18.342046
#ifdef PRECOMPILED_HEADERS
#endif
<commit_msg>INTEGRATION: CWS pchfix04 (1.2.100); FILE MERGED 2006/12/22 14:21:27 hjs 1.2.100.1: #i72801# just make sure it's not empty<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_vcl.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-05-10 16:29:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): Generated on 2006-09-01 17:50:18.342046
#ifdef PRECOMPILED_HEADERS
#include <tools/debug.hxx>
#endif
<|endoftext|> |
<commit_before><commit_msg>XubString->OUString<commit_after><|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdio.h>
#include <poll.h>
#include "salgdiimpl.hxx"
#include "vcl/salbtype.hxx"
#include "unx/pixmap.hxx"
#include "unx/salunx.h"
#include "unx/saldata.hxx"
#include "unx/saldisp.hxx"
#include "unx/salbmp.h"
#include "unx/salgdi.h"
#include "unx/salframe.h"
#include "unx/salvd.h"
#include "unx/x11/x11gdiimpl.h"
#include <unx/x11/xlimits.hxx>
#include "xrender_peer.hxx"
#include "generic/printergfx.hxx"
#include "vcl/bmpacc.hxx"
#include <outdata.hxx>
#include <boost/scoped_ptr.hpp>
void X11SalGraphics::CopyScreenArea( Display* pDisplay,
Drawable aSrc, SalX11Screen nXScreenSrc, int nSrcDepth,
Drawable aDest, SalX11Screen nXScreenDest, int nDestDepth,
GC aDestGC,
int src_x, int src_y,
unsigned int w, unsigned int h,
int dest_x, int dest_y )
{
if( nSrcDepth == nDestDepth )
{
if( nXScreenSrc == nXScreenDest )
XCopyArea( pDisplay, aSrc, aDest, aDestGC,
src_x, src_y, w, h, dest_x, dest_y );
else
{
GetGenericData()->ErrorTrapPush();
XImage* pImage = XGetImage( pDisplay, aSrc, src_x, src_y, w, h,
AllPlanes, ZPixmap );
if( pImage )
{
if( pImage->data )
XPutImage( pDisplay, aDest, aDestGC, pImage,
0, 0, dest_x, dest_y, w, h );
XDestroyImage( pImage );
}
GetGenericData()->ErrorTrapPop();
}
}
else
{
X11SalBitmap aBM;
aBM.ImplCreateFromDrawable( aSrc, nXScreenSrc, nSrcDepth, src_x, src_y, w, h );
SalTwoRect aTwoRect;
aTwoRect.mnSrcX = aTwoRect.mnSrcY = 0;
aTwoRect.mnSrcWidth = aTwoRect.mnDestWidth = w;
aTwoRect.mnSrcHeight = aTwoRect.mnDestHeight = h;
aTwoRect.mnDestX = dest_x;
aTwoRect.mnDestY = dest_y;
aBM.ImplDraw( aDest, nXScreenDest, nDestDepth, aTwoRect,aDestGC );
}
}
X11Pixmap* X11SalGraphics::GetPixmapFromScreen( const Rectangle& rRect )
{
X11GraphicsImpl* pImpl = dynamic_cast<X11GraphicsImpl*>(mpImpl.get());
return pImpl->GetPixmapFromScreen( rRect );
}
bool X11SalGraphics::RenderPixmapToScreen( X11Pixmap* pPixmap, int nX, int nY )
{
SAL_INFO( "vcl", "RenderPixmapToScreen" );
X11GraphicsImpl& rImpl = dynamic_cast<X11GraphicsImpl&>(*mpImpl.get());
return rImpl.RenderPixmapToScreen( pPixmap, nX, nY );
}
extern "C"
{
static Bool GraphicsExposePredicate( Display*, XEvent* pEvent, XPointer pFrameWindow )
{
Bool bRet = False;
if( (pEvent->type == GraphicsExpose || pEvent->type == NoExpose) &&
pEvent->xnoexpose.drawable == reinterpret_cast<Drawable>(pFrameWindow) )
{
bRet = True;
}
return bRet;
}
}
void X11SalGraphics::YieldGraphicsExpose()
{
// get frame if necessary
SalFrame* pFrame = m_pFrame;
Display* pDisplay = GetXDisplay();
::Window aWindow = GetDrawable();
if( ! pFrame )
{
const std::list< SalFrame* >& rFrames = GetGenericData()->GetSalDisplay()->getFrames();
for( std::list< SalFrame* >::const_iterator it = rFrames.begin(); it != rFrames.end() && ! pFrame; ++it )
{
const SystemEnvData* pEnvData = (*it)->GetSystemData();
if( Drawable(pEnvData->aWindow) == aWindow )
pFrame = *it;
}
if( ! pFrame )
return;
}
XEvent aEvent;
while( XCheckTypedWindowEvent( pDisplay, aWindow, Expose, &aEvent ) )
{
SalPaintEvent aPEvt( aEvent.xexpose.x, aEvent.xexpose.y, aEvent.xexpose.width+1, aEvent.xexpose.height+1 );
pFrame->CallCallback( SALEVENT_PAINT, &aPEvt );
}
do
{
if( ! GetDisplay()->XIfEventWithTimeout( &aEvent, reinterpret_cast<XPointer>(aWindow), GraphicsExposePredicate ) )
// this should not happen at all; still sometimes it happens
break;
if( aEvent.type == NoExpose )
break;
if( pFrame )
{
SalPaintEvent aPEvt( aEvent.xgraphicsexpose.x, aEvent.xgraphicsexpose.y, aEvent.xgraphicsexpose.width+1, aEvent.xgraphicsexpose.height+1 );
pFrame->CallCallback( SALEVENT_PAINT, &aPEvt );
}
} while( aEvent.xgraphicsexpose.count != 0 );
}
void X11SalGraphics::copyBits( const SalTwoRect& rPosAry,
SalGraphics *pSSrcGraphics )
{
mpImpl->copyBits( rPosAry, pSSrcGraphics );
}
void X11SalGraphics::copyArea ( long nDestX, long nDestY,
long nSrcX, long nSrcY,
long nSrcWidth, long nSrcHeight,
sal_uInt16 n )
{
mpImpl->copyArea( nDestX, nDestY, nSrcX, nSrcY, nSrcWidth, nSrcHeight, n );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap )
{
mpImpl->drawBitmap( rPosAry, rSalBitmap );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rPosAry,
const SalBitmap& rSrcBitmap,
const SalBitmap& rMaskBitmap )
{
mpImpl->drawBitmap( rPosAry, rSrcBitmap, rMaskBitmap );
}
bool X11SalGraphics::drawAlphaBitmap( const SalTwoRect& rTR,
const SalBitmap& rSrcBitmap, const SalBitmap& rAlphaBmp )
{
return mpImpl->drawAlphaBitmap( rTR, rSrcBitmap, rAlphaBmp );
}
bool X11SalGraphics::drawAlphaBitmap( const SalTwoRect& rTR,
const SalBitmap& rBitmap )
{
return mpImpl->drawAlphaBitmap( rTR, rBitmap );
}
bool X11SalGraphics::drawTransformedBitmap(
const basegfx::B2DPoint& rNull,
const basegfx::B2DPoint& rX,
const basegfx::B2DPoint& rY,
const SalBitmap& rSourceBitmap,
const SalBitmap* pAlphaBitmap)
{
return mpImpl->drawTransformedBitmap( rNull, rX, rY, rSourceBitmap, pAlphaBitmap );
}
bool X11SalGraphics::drawAlphaRect( long nX, long nY, long nWidth,
long nHeight, sal_uInt8 nTransparency )
{
return mpImpl->drawAlphaRect( nX, nY, nWidth, nHeight, nTransparency );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rRect,
const SalBitmap& rBitmap,
SalColor nColor )
{
mpImpl->drawBitmap( rRect, rBitmap, nColor );
}
void X11SalGraphics::drawMask( const SalTwoRect& rPosAry,
const SalBitmap &rSalBitmap,
SalColor nMaskColor )
{
mpImpl->drawMask( rPosAry, rSalBitmap, nMaskColor );
}
SalBitmap *X11SalGraphics::getBitmap( long nX, long nY, long nDX, long nDY )
{
return mpImpl->getBitmap( nX, nY, nDX, nDY );
}
SalColor X11SalGraphics::getPixel( long nX, long nY )
{
return mpImpl->getPixel( nX, nY );
}
void X11SalGraphics::invert( long nX,
long nY,
long nDX,
long nDY,
SalInvert nFlags )
{
mpImpl->invert( nX, nY, nDX, nDY, nFlags );
}
bool X11SalGraphics::supportsOperation( OutDevSupportType eType ) const
{
bool bRet = false;
switch( eType )
{
case OutDevSupport_TransparentRect:
case OutDevSupport_B2DDraw:
{
XRenderPeer& rPeer = XRenderPeer::GetInstance();
const SalDisplay* pSalDisp = GetDisplay();
const SalVisual& rSalVis = pSalDisp->GetVisual( m_nXScreen );
Visual* pDstXVisual = rSalVis.GetVisual();
XRenderPictFormat* pDstVisFmt = rPeer.FindVisualFormat( pDstXVisual );
if( pDstVisFmt )
bRet = true;
}
break;
default: break;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1251588 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <stdio.h>
#include <poll.h>
#include "salgdiimpl.hxx"
#include "vcl/salbtype.hxx"
#include "unx/pixmap.hxx"
#include "unx/salunx.h"
#include "unx/saldata.hxx"
#include "unx/saldisp.hxx"
#include "unx/salbmp.h"
#include "unx/salgdi.h"
#include "unx/salframe.h"
#include "unx/salvd.h"
#include "unx/x11/x11gdiimpl.h"
#include <unx/x11/xlimits.hxx>
#include "xrender_peer.hxx"
#include "generic/printergfx.hxx"
#include "vcl/bmpacc.hxx"
#include <outdata.hxx>
#include <boost/scoped_ptr.hpp>
void X11SalGraphics::CopyScreenArea( Display* pDisplay,
Drawable aSrc, SalX11Screen nXScreenSrc, int nSrcDepth,
Drawable aDest, SalX11Screen nXScreenDest, int nDestDepth,
GC aDestGC,
int src_x, int src_y,
unsigned int w, unsigned int h,
int dest_x, int dest_y )
{
if( nSrcDepth == nDestDepth )
{
if( nXScreenSrc == nXScreenDest )
XCopyArea( pDisplay, aSrc, aDest, aDestGC,
src_x, src_y, w, h, dest_x, dest_y );
else
{
GetGenericData()->ErrorTrapPush();
XImage* pImage = XGetImage( pDisplay, aSrc, src_x, src_y, w, h,
AllPlanes, ZPixmap );
if( pImage )
{
if( pImage->data )
XPutImage( pDisplay, aDest, aDestGC, pImage,
0, 0, dest_x, dest_y, w, h );
XDestroyImage( pImage );
}
GetGenericData()->ErrorTrapPop();
}
}
else
{
X11SalBitmap aBM;
aBM.ImplCreateFromDrawable( aSrc, nXScreenSrc, nSrcDepth, src_x, src_y, w, h );
SalTwoRect aTwoRect;
aTwoRect.mnSrcX = aTwoRect.mnSrcY = 0;
aTwoRect.mnSrcWidth = aTwoRect.mnDestWidth = w;
aTwoRect.mnSrcHeight = aTwoRect.mnDestHeight = h;
aTwoRect.mnDestX = dest_x;
aTwoRect.mnDestY = dest_y;
aBM.ImplDraw( aDest, nXScreenDest, nDestDepth, aTwoRect,aDestGC );
}
}
X11Pixmap* X11SalGraphics::GetPixmapFromScreen( const Rectangle& rRect )
{
X11GraphicsImpl& rImpl = dynamic_cast<X11GraphicsImpl&>(*mpImpl.get());
return rImpl.GetPixmapFromScreen( rRect );
}
bool X11SalGraphics::RenderPixmapToScreen( X11Pixmap* pPixmap, int nX, int nY )
{
SAL_INFO( "vcl", "RenderPixmapToScreen" );
X11GraphicsImpl& rImpl = dynamic_cast<X11GraphicsImpl&>(*mpImpl.get());
return rImpl.RenderPixmapToScreen( pPixmap, nX, nY );
}
extern "C"
{
static Bool GraphicsExposePredicate( Display*, XEvent* pEvent, XPointer pFrameWindow )
{
Bool bRet = False;
if( (pEvent->type == GraphicsExpose || pEvent->type == NoExpose) &&
pEvent->xnoexpose.drawable == reinterpret_cast<Drawable>(pFrameWindow) )
{
bRet = True;
}
return bRet;
}
}
void X11SalGraphics::YieldGraphicsExpose()
{
// get frame if necessary
SalFrame* pFrame = m_pFrame;
Display* pDisplay = GetXDisplay();
::Window aWindow = GetDrawable();
if( ! pFrame )
{
const std::list< SalFrame* >& rFrames = GetGenericData()->GetSalDisplay()->getFrames();
for( std::list< SalFrame* >::const_iterator it = rFrames.begin(); it != rFrames.end() && ! pFrame; ++it )
{
const SystemEnvData* pEnvData = (*it)->GetSystemData();
if( Drawable(pEnvData->aWindow) == aWindow )
pFrame = *it;
}
if( ! pFrame )
return;
}
XEvent aEvent;
while( XCheckTypedWindowEvent( pDisplay, aWindow, Expose, &aEvent ) )
{
SalPaintEvent aPEvt( aEvent.xexpose.x, aEvent.xexpose.y, aEvent.xexpose.width+1, aEvent.xexpose.height+1 );
pFrame->CallCallback( SALEVENT_PAINT, &aPEvt );
}
do
{
if( ! GetDisplay()->XIfEventWithTimeout( &aEvent, reinterpret_cast<XPointer>(aWindow), GraphicsExposePredicate ) )
// this should not happen at all; still sometimes it happens
break;
if( aEvent.type == NoExpose )
break;
if( pFrame )
{
SalPaintEvent aPEvt( aEvent.xgraphicsexpose.x, aEvent.xgraphicsexpose.y, aEvent.xgraphicsexpose.width+1, aEvent.xgraphicsexpose.height+1 );
pFrame->CallCallback( SALEVENT_PAINT, &aPEvt );
}
} while( aEvent.xgraphicsexpose.count != 0 );
}
void X11SalGraphics::copyBits( const SalTwoRect& rPosAry,
SalGraphics *pSSrcGraphics )
{
mpImpl->copyBits( rPosAry, pSSrcGraphics );
}
void X11SalGraphics::copyArea ( long nDestX, long nDestY,
long nSrcX, long nSrcY,
long nSrcWidth, long nSrcHeight,
sal_uInt16 n )
{
mpImpl->copyArea( nDestX, nDestY, nSrcX, nSrcY, nSrcWidth, nSrcHeight, n );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap )
{
mpImpl->drawBitmap( rPosAry, rSalBitmap );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rPosAry,
const SalBitmap& rSrcBitmap,
const SalBitmap& rMaskBitmap )
{
mpImpl->drawBitmap( rPosAry, rSrcBitmap, rMaskBitmap );
}
bool X11SalGraphics::drawAlphaBitmap( const SalTwoRect& rTR,
const SalBitmap& rSrcBitmap, const SalBitmap& rAlphaBmp )
{
return mpImpl->drawAlphaBitmap( rTR, rSrcBitmap, rAlphaBmp );
}
bool X11SalGraphics::drawAlphaBitmap( const SalTwoRect& rTR,
const SalBitmap& rBitmap )
{
return mpImpl->drawAlphaBitmap( rTR, rBitmap );
}
bool X11SalGraphics::drawTransformedBitmap(
const basegfx::B2DPoint& rNull,
const basegfx::B2DPoint& rX,
const basegfx::B2DPoint& rY,
const SalBitmap& rSourceBitmap,
const SalBitmap* pAlphaBitmap)
{
return mpImpl->drawTransformedBitmap( rNull, rX, rY, rSourceBitmap, pAlphaBitmap );
}
bool X11SalGraphics::drawAlphaRect( long nX, long nY, long nWidth,
long nHeight, sal_uInt8 nTransparency )
{
return mpImpl->drawAlphaRect( nX, nY, nWidth, nHeight, nTransparency );
}
void X11SalGraphics::drawBitmap( const SalTwoRect& rRect,
const SalBitmap& rBitmap,
SalColor nColor )
{
mpImpl->drawBitmap( rRect, rBitmap, nColor );
}
void X11SalGraphics::drawMask( const SalTwoRect& rPosAry,
const SalBitmap &rSalBitmap,
SalColor nMaskColor )
{
mpImpl->drawMask( rPosAry, rSalBitmap, nMaskColor );
}
SalBitmap *X11SalGraphics::getBitmap( long nX, long nY, long nDX, long nDY )
{
return mpImpl->getBitmap( nX, nY, nDX, nDY );
}
SalColor X11SalGraphics::getPixel( long nX, long nY )
{
return mpImpl->getPixel( nX, nY );
}
void X11SalGraphics::invert( long nX,
long nY,
long nDX,
long nDY,
SalInvert nFlags )
{
mpImpl->invert( nX, nY, nDX, nDY, nFlags );
}
bool X11SalGraphics::supportsOperation( OutDevSupportType eType ) const
{
bool bRet = false;
switch( eType )
{
case OutDevSupport_TransparentRect:
case OutDevSupport_B2DDraw:
{
XRenderPeer& rPeer = XRenderPeer::GetInstance();
const SalDisplay* pSalDisp = GetDisplay();
const SalVisual& rSalVis = pSalDisp->GetVisual( m_nXScreen );
Visual* pDstXVisual = rSalVis.GetVisual();
XRenderPictFormat* pDstVisFmt = rPeer.FindVisualFormat( pDstXVisual );
if( pDstVisFmt )
bRet = true;
}
break;
default: break;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>remove obsolete pieces, and erroneous conditional<commit_after><|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cassert>
#include <stdexcept>
#include <thread>
#include <chrono>
#include <sstream>
#include <bh.h>
#include "InstructionScheduler.hpp"
#include "UserFuncArg.hpp"
#include "Scalar.hpp"
#include "Reduce.hpp"
InstructionScheduler::InstructionScheduler()
: batch(NULL) {}
bh_error InstructionScheduler::schedule(bh_ir* bhir)
{
for (bh_intp i = 0; i < bhir->ninstr; ++i)
{
bh_instruction* inst = &(bhir->instr_list[i]);
if (inst->opcode != BH_NONE)
{
#ifdef DEBUG
bh_pprint_instr(inst);
#endif
bh_error res;
switch (inst->opcode)
{
case BH_SYNC:
sync(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_DISCARD:
discard(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_FREE:
bh_data_free(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_ADD_REDUCE:
case BH_MULTIPLY_REDUCE:
case BH_MINIMUM_REDUCE:
case BH_MAXIMUM_REDUCE:
case BH_LOGICAL_AND_REDUCE:
case BH_BITWISE_AND_REDUCE:
case BH_LOGICAL_OR_REDUCE:
case BH_BITWISE_OR_REDUCE:
case BH_LOGICAL_XOR_REDUCE:
case BH_BITWISE_XOR_REDUCE:
case BH_ADD_ACCUMULATE:
case BH_MULTIPLY_ACCUMULATE:
res = reduce(inst);
break;
default:
if (inst->opcode <= BH_MAX_OPCODE_ID)
res = ufunc(inst);
else
res = extmethod(inst);
}
if (res != BH_SUCCESS)
{
return res;
}
}
}
/* End of batch cleanup */
executeBatch();
return BH_SUCCESS;
}
void InstructionScheduler::compileAndRun(SourceKernelCall sourceKernel)
{
size_t functionID = sourceKernel.id().first;
std::map<size_t,size_t>::iterator kidit = knownKernelID.find(functionID);
if (kidit != knownKernelID.end())
{
KernelID kernelID(sourceKernel.functionID(),0);
if (kidit->second == sourceKernel.literalID())
{
kernelID.second = kidit->second;
}
kernelMutex.lock();
if (callQueue.empty())
{
KernelMap::iterator kit = kernelMap.find(kernelID);
assert(kit != kernelMap.end());
if (kernelID.second == 0)
{
kit->second.call(sourceKernel.allParameters(), sourceKernel.shape());
sourceKernel.deleteBuffers();
} else {
kit->second.call(sourceKernel.valueParameters(), sourceKernel.shape());
sourceKernel.deleteBuffers();
}
} else {
callQueue.push_back(std::make_pair(kernelID,sourceKernel));
}
kernelMutex.unlock();
} else { // New Kernel
knownKernelID.insert(sourceKernel.id());
kernelMutex.lock();
callQueue.push_back(std::make_pair(sourceKernel.id(),sourceKernel));
kernelMutex.unlock();
std::thread(&InstructionScheduler::build, this, sourceKernel.id(), sourceKernel.source()).detach();
std::thread(&InstructionScheduler::build, this, KernelID(functionID,0), sourceKernel.source()).detach();
}
}
void InstructionScheduler::executeBatch()
{
if (batch)
{
try {
SourceKernelCall sourceKernel = batch->generateKernel();
sourceKernel.setDiscard(discardSet);
compileAndRun(sourceKernel);
}
catch(BatchException be)
{
if (!discardSet.empty())
{
kernelMutex.lock();
if (!callQueue.empty())
{
SourceKernelCall& sourceKernel = callQueue.back().second;
for (BaseArray *ba: discardSet)
{
sourceKernel.addDiscard(ba);
}
kernelMutex.unlock();
}
else {
kernelMutex.unlock();
for (BaseArray *ba: discardSet)
{
delete ba;
}
}
}
}
discardSet.clear();
delete batch;
batch = 0;
}
}
void InstructionScheduler::build(KernelID kernelID, const std::string source)
{
std::stringstream kname;
kname << "kernel" << std::hex << kernelID.first << (kernelID.second==0?"":"_");
Kernel kernel(source, kname.str(), (kernelID.second==0?"":"-DSTATIC_KERNEL"));
kernelMutex.lock();
kernelMap.insert(std::make_pair(kernelID, kernel));
while (!callQueue.empty())
{
KernelCall kernelCall = callQueue.front();
KernelMap::iterator kit = kernelMap.find(kernelCall.first);
if (kit != kernelMap.end())
{
kit->second.call((kernelID.second==0?
kernelCall.second.allParameters():
kernelCall.second.valueParameters()),
kernelCall.second.shape());
kernelCall.second.deleteBuffers();
callQueue.pop_front();
}
else
break;
}
kernelMutex.unlock();
}
void InstructionScheduler::sync(bh_base* base)
{
//TODO postpone sync
// We may recieve sync for arrays I don't own
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
return;
}
if (batch && batch->write(it->second))
{
executeBatch();
}
while (!callQueue.empty())
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
it->second->sync();
}
void InstructionScheduler::discard(bh_base* base)
{
// We may recieve discard for arrays I don't own
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
return;
}
if (batch && !batch->discard(it->second))
{
discardSet.insert(it->second);
}
else
{
kernelMutex.lock();
if (!callQueue.empty())
{
callQueue.back().second.addDiscard(it->second);
kernelMutex.unlock();
}
else {
kernelMutex.unlock();
delete it->second;
}
}
arrayMap.erase(it);
}
std::vector<KernelParameter*> InstructionScheduler::getKernelParameters(bh_instruction* inst)
{
bh_intp nops = bh_operands(inst->opcode);
assert(nops > 0);
std::vector<KernelParameter*> operands(nops);
for (int i = 0; i < nops; ++i)
{
if (bh_is_constant(&(inst->operand[i])))
{
operands[i] = new Scalar(inst->constant);
continue;
}
bh_base* base = inst->operand[i].base;
if (!resourceManager->float64support() && base->type == BH_FLOAT64)
{
throw BH_TYPE_NOT_SUPPORTED;
}
// Is it a new base array we haven't heard of before?
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
// Then create it
BaseArray* ba = new BaseArray(base, resourceManager);
arrayMap[base] = ba;
operands[i] = ba;
}
else
{
operands[i] = it->second;
}
}
return operands;
}
bh_error InstructionScheduler::ufunc(bh_instruction* inst)
{
try {
std::vector<KernelParameter*> operands = getKernelParameters(inst);
if (batch)
{
try {
batch->add(inst, operands);
}
catch (BatchException& be)
{
executeBatch();
batch = new InstructionBatch(inst, operands);
}
} else {
batch = new InstructionBatch(inst, operands);
}
return BH_SUCCESS;
}
catch (bh_error e)
{
return e;
}
}
bh_error InstructionScheduler::reduce(bh_instruction* inst)
{
if(inst->operand[1].ndim < 2)
{
// TODO these two syncs are a hack. Are we sure this is correct?????
sync(inst->operand[1].base);
sync(inst->operand[0].base);
bh_ir bhir;
bh_error err = bh_ir_create(&bhir, 1, inst);
if(err != BH_SUCCESS)
return err;
return resourceManager->childExecute(&bhir);
}
std::vector<KernelParameter*> operands = getKernelParameters(inst);
if (batch && (batch->access(static_cast<BaseArray*>(operands[0])) ||
batch->write(static_cast<BaseArray*>(operands[1]))))
{
executeBatch();
}
try {
SourceKernelCall sourceKernel = Reduce::generateKernel(inst, operands);
compileAndRun(sourceKernel);
}
catch (bh_error e)
{
return e;
}
return BH_SUCCESS;
}
void InstructionScheduler::registerFunction(bh_opcode opcode, bh_extmethod_impl extmethod_impl)
{
if(functionMap.find(opcode) != functionMap.end())
{
std::cerr << "[GPU-VE] Warning, multiple registrations of the same extension method: " <<
opcode << std::endl;
}
functionMap[opcode] = extmethod_impl;
}
bh_error InstructionScheduler::extmethod(bh_instruction* inst)
{
FunctionMap::iterator fit = functionMap.find(inst->opcode);
if (fit == functionMap.end())
{
return BH_EXTMETHOD_NOT_SUPPORTED;
}
try {
UserFuncArg userFuncArg;
userFuncArg.resourceManager = resourceManager;
userFuncArg.operands = getKernelParameters(inst);
// If the instruction batch accesses any of the output operands it need to be executed first
BaseArray* ba = dynamic_cast<BaseArray*>(userFuncArg.operands[0]);
if (batch && ba && batch->access(ba))
{
executeBatch();
}
// If the instruction batch writes to any of the input operands it need to be executed first
for (int i = 1; i < bh_operands(inst->opcode); ++i)
{
BaseArray* ba = dynamic_cast<BaseArray*>(userFuncArg.operands[i]);
if (batch && ba && batch->write(ba))
{
executeBatch();
}
}
// Execute the extension method
return fit->second(inst, &userFuncArg);
}
catch (bh_error e)
{
return e;
}
}
<commit_msg>Handle Kernel known, bun instance compile not done<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cassert>
#include <stdexcept>
#include <thread>
#include <chrono>
#include <sstream>
#include <bh.h>
#include "InstructionScheduler.hpp"
#include "UserFuncArg.hpp"
#include "Scalar.hpp"
#include "Reduce.hpp"
InstructionScheduler::InstructionScheduler()
: batch(NULL) {}
bh_error InstructionScheduler::schedule(bh_ir* bhir)
{
for (bh_intp i = 0; i < bhir->ninstr; ++i)
{
bh_instruction* inst = &(bhir->instr_list[i]);
if (inst->opcode != BH_NONE)
{
#ifdef DEBUG
bh_pprint_instr(inst);
#endif
bh_error res;
switch (inst->opcode)
{
case BH_SYNC:
sync(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_DISCARD:
discard(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_FREE:
bh_data_free(inst->operand[0].base);
res = BH_SUCCESS;
break;
case BH_ADD_REDUCE:
case BH_MULTIPLY_REDUCE:
case BH_MINIMUM_REDUCE:
case BH_MAXIMUM_REDUCE:
case BH_LOGICAL_AND_REDUCE:
case BH_BITWISE_AND_REDUCE:
case BH_LOGICAL_OR_REDUCE:
case BH_BITWISE_OR_REDUCE:
case BH_LOGICAL_XOR_REDUCE:
case BH_BITWISE_XOR_REDUCE:
case BH_ADD_ACCUMULATE:
case BH_MULTIPLY_ACCUMULATE:
res = reduce(inst);
break;
default:
if (inst->opcode <= BH_MAX_OPCODE_ID)
res = ufunc(inst);
else
res = extmethod(inst);
}
if (res != BH_SUCCESS)
{
return res;
}
}
}
/* End of batch cleanup */
executeBatch();
return BH_SUCCESS;
}
void InstructionScheduler::compileAndRun(SourceKernelCall sourceKernel)
{
size_t functionID = sourceKernel.id().first;
std::map<size_t,size_t>::iterator kidit = knownKernelID.find(functionID);
if (kidit != knownKernelID.end())
{
KernelID kernelID(sourceKernel.functionID(),0);
if (kidit->second == sourceKernel.literalID())
{
kernelID.second = kidit->second;
}
kernelMutex.lock();
if (callQueue.empty())
{
KernelMap::iterator kit = kernelMap.find(kernelID);
if (kit == kernelMap.end())
{
callQueue.push_back(std::make_pair(kernelID,sourceKernel));
} else {
if (kernelID.second == 0)
{
kit->second.call(sourceKernel.allParameters(), sourceKernel.shape());
sourceKernel.deleteBuffers();
} else {
kit->second.call(sourceKernel.valueParameters(), sourceKernel.shape());
sourceKernel.deleteBuffers();
}
}
} else {
callQueue.push_back(std::make_pair(kernelID,sourceKernel));
}
kernelMutex.unlock();
} else { // New Kernel
knownKernelID.insert(sourceKernel.id());
kernelMutex.lock();
callQueue.push_back(std::make_pair(sourceKernel.id(),sourceKernel));
kernelMutex.unlock();
std::thread(&InstructionScheduler::build, this, sourceKernel.id(), sourceKernel.source()).detach();
std::thread(&InstructionScheduler::build, this, KernelID(functionID,0), sourceKernel.source()).detach();
}
}
void InstructionScheduler::executeBatch()
{
if (batch)
{
try {
SourceKernelCall sourceKernel = batch->generateKernel();
sourceKernel.setDiscard(discardSet);
compileAndRun(sourceKernel);
}
catch(BatchException be)
{
if (!discardSet.empty())
{
kernelMutex.lock();
if (!callQueue.empty())
{
SourceKernelCall& sourceKernel = callQueue.back().second;
for (BaseArray *ba: discardSet)
{
sourceKernel.addDiscard(ba);
}
kernelMutex.unlock();
}
else {
kernelMutex.unlock();
for (BaseArray *ba: discardSet)
{
delete ba;
}
}
}
}
discardSet.clear();
delete batch;
batch = 0;
}
}
void InstructionScheduler::build(KernelID kernelID, const std::string source)
{
std::stringstream kname;
kname << "kernel" << std::hex << kernelID.first << (kernelID.second==0?"":"_");
Kernel kernel(source, kname.str(), (kernelID.second==0?"":"-DSTATIC_KERNEL"));
kernelMutex.lock();
kernelMap.insert(std::make_pair(kernelID, kernel));
while (!callQueue.empty())
{
KernelCall kernelCall = callQueue.front();
KernelMap::iterator kit = kernelMap.find(kernelCall.first);
if (kit != kernelMap.end())
{
kit->second.call((kernelID.second==0?
kernelCall.second.allParameters():
kernelCall.second.valueParameters()),
kernelCall.second.shape());
kernelCall.second.deleteBuffers();
callQueue.pop_front();
}
else
break;
}
kernelMutex.unlock();
}
void InstructionScheduler::sync(bh_base* base)
{
//TODO postpone sync
// We may recieve sync for arrays I don't own
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
return;
}
if (batch && batch->write(it->second))
{
executeBatch();
}
while (!callQueue.empty())
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
it->second->sync();
}
void InstructionScheduler::discard(bh_base* base)
{
// We may recieve discard for arrays I don't own
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
return;
}
if (batch && !batch->discard(it->second))
{
discardSet.insert(it->second);
}
else
{
kernelMutex.lock();
if (!callQueue.empty())
{
callQueue.back().second.addDiscard(it->second);
kernelMutex.unlock();
}
else {
kernelMutex.unlock();
delete it->second;
}
}
arrayMap.erase(it);
}
std::vector<KernelParameter*> InstructionScheduler::getKernelParameters(bh_instruction* inst)
{
bh_intp nops = bh_operands(inst->opcode);
assert(nops > 0);
std::vector<KernelParameter*> operands(nops);
for (int i = 0; i < nops; ++i)
{
if (bh_is_constant(&(inst->operand[i])))
{
operands[i] = new Scalar(inst->constant);
continue;
}
bh_base* base = inst->operand[i].base;
if (!resourceManager->float64support() && base->type == BH_FLOAT64)
{
throw BH_TYPE_NOT_SUPPORTED;
}
// Is it a new base array we haven't heard of before?
ArrayMap::iterator it = arrayMap.find(base);
if (it == arrayMap.end())
{
// Then create it
BaseArray* ba = new BaseArray(base, resourceManager);
arrayMap[base] = ba;
operands[i] = ba;
}
else
{
operands[i] = it->second;
}
}
return operands;
}
bh_error InstructionScheduler::ufunc(bh_instruction* inst)
{
try {
std::vector<KernelParameter*> operands = getKernelParameters(inst);
if (batch)
{
try {
batch->add(inst, operands);
}
catch (BatchException& be)
{
executeBatch();
batch = new InstructionBatch(inst, operands);
}
} else {
batch = new InstructionBatch(inst, operands);
}
return BH_SUCCESS;
}
catch (bh_error e)
{
return e;
}
}
bh_error InstructionScheduler::reduce(bh_instruction* inst)
{
if(inst->operand[1].ndim < 2)
{
// TODO these two syncs are a hack. Are we sure this is correct?????
sync(inst->operand[1].base);
sync(inst->operand[0].base);
bh_ir bhir;
bh_error err = bh_ir_create(&bhir, 1, inst);
if(err != BH_SUCCESS)
return err;
return resourceManager->childExecute(&bhir);
}
std::vector<KernelParameter*> operands = getKernelParameters(inst);
if (batch && (batch->access(static_cast<BaseArray*>(operands[0])) ||
batch->write(static_cast<BaseArray*>(operands[1]))))
{
executeBatch();
}
try {
SourceKernelCall sourceKernel = Reduce::generateKernel(inst, operands);
compileAndRun(sourceKernel);
}
catch (bh_error e)
{
return e;
}
return BH_SUCCESS;
}
void InstructionScheduler::registerFunction(bh_opcode opcode, bh_extmethod_impl extmethod_impl)
{
if(functionMap.find(opcode) != functionMap.end())
{
std::cerr << "[GPU-VE] Warning, multiple registrations of the same extension method: " <<
opcode << std::endl;
}
functionMap[opcode] = extmethod_impl;
}
bh_error InstructionScheduler::extmethod(bh_instruction* inst)
{
FunctionMap::iterator fit = functionMap.find(inst->opcode);
if (fit == functionMap.end())
{
return BH_EXTMETHOD_NOT_SUPPORTED;
}
try {
UserFuncArg userFuncArg;
userFuncArg.resourceManager = resourceManager;
userFuncArg.operands = getKernelParameters(inst);
// If the instruction batch accesses any of the output operands it need to be executed first
BaseArray* ba = dynamic_cast<BaseArray*>(userFuncArg.operands[0]);
if (batch && ba && batch->access(ba))
{
executeBatch();
}
// If the instruction batch writes to any of the input operands it need to be executed first
for (int i = 1; i < bh_operands(inst->opcode); ++i)
{
BaseArray* ba = dynamic_cast<BaseArray*>(userFuncArg.operands[i]);
if (batch && ba && batch->write(ba))
{
executeBatch();
}
}
// Execute the extension method
return fit->second(inst, &userFuncArg);
}
catch (bh_error e)
{
return e;
}
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <node_object_wrap.h>
#include <unicode/unistr.h>
#include <unicode/usprep.h>
#include <cstring>
#include <exception>
using namespace v8;
using namespace node;
/*** Utility ***/
static Handle<Value> throwTypeError(const char *msg)
{
return ThrowException(Exception::TypeError(String::New(msg)));
}
/* supports return of just enum */
class UnknownProfileException : public std::exception {
};
class StringPrep : public ObjectWrap {
public:
static void Initialize(Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "prepare", Prepare);
target->Set(String::NewSymbol("StringPrep"), t->GetFunction());
}
bool good() const
{
return U_SUCCESS(error);
}
const char *errorName() const
{
return u_errorName(error);
}
Handle<Value> makeException() const
{
return Exception::Error(String::New(errorName()));
}
protected:
/*** Constructor ***/
static Handle<Value> New(const Arguments& args)
{
HandleScope scope;
if (args.Length() == 1 && args[0]->IsString())
{
String::Utf8Value arg0(args[0]->ToString());
UStringPrepProfileType profileType;
try
{
profileType = parseProfileType(arg0);
}
catch (UnknownProfileException &)
{
return throwTypeError("Unknown StringPrep profile");
}
StringPrep *self = new StringPrep(profileType);
if (self->good())
{
self->Wrap(args.This());
return args.This();
}
else
{
Handle<Value> exception = self->makeException();
delete self;
return ThrowException(exception);
}
}
else
return throwTypeError("Bad argument.");
}
StringPrep(const UStringPrepProfileType profileType)
: error(U_ZERO_ERROR)
{
profile = usprep_openByType(profileType, &error);
}
/*** Destructor ***/
~StringPrep()
{
if (profile)
usprep_close(profile);
}
/*** Prepare ***/
static Handle<Value> Prepare(const Arguments& args)
{
HandleScope scope;
if (args.Length() == 1 && args[0]->IsString())
{
StringPrep *self = ObjectWrap::Unwrap<StringPrep>(args.This());
String::Value arg0(args[0]->ToString());
return scope.Close(self->prepare(arg0));
}
else
return throwTypeError("Bad argument.");
}
Handle<Value> prepare(String::Value &str)
{
size_t destLen = str.length();
UChar *dest = NULL;
while(!dest)
{
dest = new UChar[destLen];
size_t w = usprep_prepare(profile,
*str, str.length(),
dest, destLen,
USPREP_DEFAULT, NULL, &error);
if (error == U_BUFFER_OVERFLOW_ERROR)
{
// retry with a dest buffer twice as large
destLen *= 2;
delete[] dest;
dest = NULL;
}
else if (!good())
{
// other error, just bail out
delete[] dest;
return ThrowException(makeException());
}
else
destLen = w;
}
Local<String> result = String::New(dest, destLen);
delete[] dest;
return result;
}
private:
UStringPrepProfile *profile;
UErrorCode error;
static enum UStringPrepProfileType parseProfileType(String::Utf8Value &profile)
throw(UnknownProfileException)
{
if (strcasecmp(*profile, "nameprep") == 0)
return USPREP_RFC3491_NAMEPREP;
if (strcasecmp(*profile, "nfs4_cs_prep") == 0)
return USPREP_RFC3530_NFS4_CS_PREP;
if (strcasecmp(*profile, "nfs4_cs_prep") == 0)
return USPREP_RFC3530_NFS4_CS_PREP_CI;
if (strcasecmp(*profile, "nfs4_cis_prep") == 0)
return USPREP_RFC3530_NFS4_CIS_PREP;
if (strcasecmp(*profile, "nfs4_mixed_prep prefix") == 0)
return USPREP_RFC3530_NFS4_MIXED_PREP_PREFIX;
if (strcasecmp(*profile, "nfs4_mixed_prep suffix") == 0)
return USPREP_RFC3530_NFS4_MIXED_PREP_SUFFIX;
if (strcasecmp(*profile, "iscsi") == 0)
return USPREP_RFC3722_ISCSI;
if (strcasecmp(*profile, "nodeprep") == 0)
return USPREP_RFC3920_NODEPREP;
if (strcasecmp(*profile, "resourceprep") == 0)
return USPREP_RFC3920_RESOURCEPREP;
if (strcasecmp(*profile, "mib") == 0)
return USPREP_RFC4011_MIB;
if (strcasecmp(*profile, "saslprep") == 0)
return USPREP_RFC4013_SASLPREP;
if (strcasecmp(*profile, "trace") == 0)
return USPREP_RFC4505_TRACE;
if (strcasecmp(*profile, "ldap") == 0)
return USPREP_RFC4518_LDAP;
if (strcasecmp(*profile, "ldapci") == 0)
return USPREP_RFC4518_LDAP_CI;
throw UnknownProfileException();
}
};
/*** Initialization ***/
extern "C" void init(Handle<Object> target)
{
HandleScope scope;
StringPrep::Initialize(target);
}
<commit_msg>accept more arguments<commit_after>#include <node.h>
#include <node_object_wrap.h>
#include <unicode/unistr.h>
#include <unicode/usprep.h>
#include <cstring>
#include <exception>
using namespace v8;
using namespace node;
/*** Utility ***/
static Handle<Value> throwTypeError(const char *msg)
{
return ThrowException(Exception::TypeError(String::New(msg)));
}
/* supports return of just enum */
class UnknownProfileException : public std::exception {
};
class StringPrep : public ObjectWrap {
public:
static void Initialize(Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "prepare", Prepare);
target->Set(String::NewSymbol("StringPrep"), t->GetFunction());
}
bool good() const
{
return U_SUCCESS(error);
}
const char *errorName() const
{
return u_errorName(error);
}
Handle<Value> makeException() const
{
return Exception::Error(String::New(errorName()));
}
protected:
/*** Constructor ***/
static Handle<Value> New(const Arguments& args)
{
HandleScope scope;
if (args.Length() >= 1 && args[0]->IsString())
{
String::Utf8Value arg0(args[0]->ToString());
UStringPrepProfileType profileType;
try
{
profileType = parseProfileType(arg0);
}
catch (UnknownProfileException &)
{
return throwTypeError("Unknown StringPrep profile");
}
StringPrep *self = new StringPrep(profileType);
if (self->good())
{
self->Wrap(args.This());
return args.This();
}
else
{
Handle<Value> exception = self->makeException();
delete self;
return ThrowException(exception);
}
}
else
return throwTypeError("Bad argument.");
}
StringPrep(const UStringPrepProfileType profileType)
: error(U_ZERO_ERROR)
{
profile = usprep_openByType(profileType, &error);
}
/*** Destructor ***/
~StringPrep()
{
if (profile)
usprep_close(profile);
}
/*** Prepare ***/
static Handle<Value> Prepare(const Arguments& args)
{
HandleScope scope;
if (args.Length() >= 1 && args[0]->IsString())
{
StringPrep *self = ObjectWrap::Unwrap<StringPrep>(args.This());
String::Value arg0(args[0]->ToString());
return scope.Close(self->prepare(arg0));
}
else
return throwTypeError("Bad argument.");
}
Handle<Value> prepare(String::Value &str)
{
size_t destLen = str.length();
UChar *dest = NULL;
while(!dest)
{
dest = new UChar[destLen];
size_t w = usprep_prepare(profile,
*str, str.length(),
dest, destLen,
USPREP_DEFAULT, NULL, &error);
if (error == U_BUFFER_OVERFLOW_ERROR)
{
// retry with a dest buffer twice as large
destLen *= 2;
delete[] dest;
dest = NULL;
}
else if (!good())
{
// other error, just bail out
delete[] dest;
return ThrowException(makeException());
}
else
destLen = w;
}
Local<String> result = String::New(dest, destLen);
delete[] dest;
return result;
}
private:
UStringPrepProfile *profile;
UErrorCode error;
static enum UStringPrepProfileType parseProfileType(String::Utf8Value &profile)
throw(UnknownProfileException)
{
if (strcasecmp(*profile, "nameprep") == 0)
return USPREP_RFC3491_NAMEPREP;
if (strcasecmp(*profile, "nfs4_cs_prep") == 0)
return USPREP_RFC3530_NFS4_CS_PREP;
if (strcasecmp(*profile, "nfs4_cs_prep") == 0)
return USPREP_RFC3530_NFS4_CS_PREP_CI;
if (strcasecmp(*profile, "nfs4_cis_prep") == 0)
return USPREP_RFC3530_NFS4_CIS_PREP;
if (strcasecmp(*profile, "nfs4_mixed_prep prefix") == 0)
return USPREP_RFC3530_NFS4_MIXED_PREP_PREFIX;
if (strcasecmp(*profile, "nfs4_mixed_prep suffix") == 0)
return USPREP_RFC3530_NFS4_MIXED_PREP_SUFFIX;
if (strcasecmp(*profile, "iscsi") == 0)
return USPREP_RFC3722_ISCSI;
if (strcasecmp(*profile, "nodeprep") == 0)
return USPREP_RFC3920_NODEPREP;
if (strcasecmp(*profile, "resourceprep") == 0)
return USPREP_RFC3920_RESOURCEPREP;
if (strcasecmp(*profile, "mib") == 0)
return USPREP_RFC4011_MIB;
if (strcasecmp(*profile, "saslprep") == 0)
return USPREP_RFC4013_SASLPREP;
if (strcasecmp(*profile, "trace") == 0)
return USPREP_RFC4505_TRACE;
if (strcasecmp(*profile, "ldap") == 0)
return USPREP_RFC4518_LDAP;
if (strcasecmp(*profile, "ldapci") == 0)
return USPREP_RFC4518_LDAP_CI;
throw UnknownProfileException();
}
};
/*** Initialization ***/
extern "C" void init(Handle<Object> target)
{
HandleScope scope;
StringPrep::Initialize(target);
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Lock Test Functions
///
/// @author Nick LeRoy <nleroy@qualys.com>
//////////////////////////////////////////////////////////////////////////////
#include "ironbee_config_auto.h"
#include <ironbee/types.h>
#include <ironbee/mpool.h>
#include <ironbee/util.h>
#include <ironbee/lock.h>
#include "gtest/gtest.h"
#include "simple_fixture.hpp"
#include <stdexcept>
#include <math.h>
#include <pthread.h>
/* -- Tests -- */
typedef void *(* thread_start_fn)(void *thread_data);
class Thread
{
public:
Thread(int num) :
m_handle(0),
m_num(num),
m_started(false),
m_running(false),
m_errors(0)
{
}
Thread() :
m_handle(0),
m_num(-1),
m_started(false),
m_running(false),
m_errors(0)
{
}
void ThreadNum(int num) { m_num = num; };
bool IsRunning() const { return m_running; };
int ThreadNum() const { return m_num; };
uint64_t ThreadId() const { return (uint64_t)m_handle; };
uint64_t Errors() const { return m_errors; };
void Error() { ++m_errors; };
ib_status_t Create(thread_start_fn fn)
{
pthread_t handle;
pthread_attr_t attr;
int status;
if (m_num < 0) {
return IB_EINVAL;
}
if (m_started || m_running) {
return IB_EINVAL;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
m_started = true;
status = pthread_create(&handle, &attr, fn, this);
if (status) {
m_started = false;
return IB_EUNKNOWN;
}
m_handle = handle;
return IB_OK;
}
ib_status_t Join(void)
{
int status;
if (! m_started) {
return IB_OK;
}
status = pthread_join(m_handle, NULL);
if (status != 0) {
return IB_EUNKNOWN;
}
m_running = false;
m_started = false;
return IB_OK;
}
ib_status_t Running(bool run)
{
if (!m_started) {
return IB_EINVAL;
}
if (run == m_running) {
return IB_EINVAL;
}
m_running = run;
return IB_OK;
}
private:
pthread_t m_handle;
int m_num;
bool m_started;
bool m_running;
uint64_t m_errors;
};
class TestIBUtilLock : public SimpleFixture
{
public:
TestIBUtilLock(void) :
m_max_threads(0),
m_threads(NULL),
m_lock_enabled(true),
m_shared(0)
{
TestIBUtilLock::m_self = this;
TestParams(100, 0.0005, true);
}
~TestIBUtilLock(void)
{
if (m_threads != NULL) {
delete []m_threads;
}
}
virtual void SetUp(void)
{
SimpleFixture::SetUp();
}
virtual void TearDown()
{
SimpleFixture::TearDown();
DestroyLock( );
}
ib_status_t CreateLock( void )
{
return ib_lock_init(&m_lock);
}
ib_status_t DestroyLock( void )
{
return ib_lock_destroy(&m_lock);
}
ib_status_t LockLock( void )
{
return ib_lock_lock(&m_lock);
}
ib_status_t UnlockLock( void )
{
return ib_lock_unlock(&m_lock);
}
void InitThreads(size_t max_threads)
{
m_max_threads = max_threads;
m_threads = new Thread[max_threads];
for (int num = 0; num < (int)max_threads; ++num) {
m_threads[num].ThreadNum(num);
}
}
void TestParams(size_t loops, double seconds, bool lock)
{
Loops(loops);
SleepTime(seconds);
m_lock_enabled = lock;
}
void Loops(size_t loops) { m_loops = loops; };
void SleepTime(double sec) { m_sleeptime = sec; };
ib_status_t CreateThread(size_t num)
{
if(m_threads == NULL) {
throw std::runtime_error("Thread handles not initialized.");
}
if (num >= m_max_threads) {
throw std::runtime_error("Thread number greater than max.");
}
Thread *thread = &m_threads[num];
if (thread->IsRunning()) {
throw std::runtime_error("Thread already running.");
}
return thread->Create(TestIBUtilLock::StartThread);
}
ib_status_t CreateAllThreads( void )
{
if(m_threads == NULL) {
throw std::runtime_error("Thread handles not initialized.");
}
size_t num;
for (num = 0; num < m_max_threads; ++num) {
ib_status_t rc = CreateThread(num);
if (rc != IB_OK) {
return rc;
}
}
return IB_OK;
}
ib_status_t StartTest(size_t threads,
size_t loops,
double seconds,
bool lock)
{
InitThreads(threads);
TestParams(loops, seconds, lock);
printf("Starting: %zd threads, %d loops, %.8fs sleep, locks %s\n",
m_max_threads, m_loops, m_sleeptime,
m_lock_enabled ? "enabled" : "disabled");
return CreateAllThreads( );
}
static void *StartThread(void *data)
{
Thread *thread = (Thread *)data;
m_self->RunThread(thread);
return NULL;
}
void RunThread(Thread *thread)
{
ib_status_t rc;
int n;
struct timespec ts;
ts.tv_sec = (time_t)trunc(m_sleeptime);
ts.tv_nsec = (long)(round((m_sleeptime - ts.tv_sec) * 1e9));
thread->Running(true);
for (n = 0; n < m_loops; ++n) {
if (m_lock_enabled) {
rc = LockLock( );
if (rc != IB_OK) {
thread->Error();
break;
}
}
if (++m_shared != 1) {
thread->Error();
}
nanosleep(&ts, NULL);
if (--m_shared != 0) {
thread->Error();
}
if (m_lock_enabled) {
rc = UnlockLock( );
if (rc != IB_OK) {
thread->Error();
break;
}
}
}
thread->Running(false);
}
ib_status_t WaitForThreads(uint64_t *errors)
{
ib_status_t rc = IB_OK;
size_t num;
*errors = 0;
for (num = 0; num < m_max_threads; ++num) {
Thread *thread = &m_threads[num];
ib_status_t irc = thread->Join();
if (irc != IB_OK) {
rc = irc;
}
*errors += thread->Errors();
}
return rc;
}
private:
static TestIBUtilLock *m_self;
size_t m_max_threads;
Thread *m_threads;
ib_lock_t m_lock;
bool m_lock_enabled;
int m_loops;
double m_sleeptime;
volatile int m_shared;
};
TestIBUtilLock *TestIBUtilLock::m_self = NULL;
TEST(test_util_lock, misc)
{
int test = 0;
for (int n=0; n<100; ++n) {
int t;
t = ++test;
ASSERT_EQ(1, t);
t = --test;
ASSERT_EQ(0, t);
}
}
TEST_F(TestIBUtilLock, test_create)
{
ib_status_t rc;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = LockLock( );
ASSERT_EQ(IB_OK, rc);
rc = UnlockLock( );
ASSERT_EQ(IB_OK, rc);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
TEST_F(TestIBUtilLock, test_lock_disabled)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(5, 100, 0.0000005, false);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_NE(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
TEST_F(TestIBUtilLock, test_short)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(5, 100, 0.0000005, true);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_EQ(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
TEST_F(TestIBUtilLock, test_long)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(20, 1000, 0.00005, true);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_EQ(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
<commit_msg>test/test_util_lock: Cleanup and disable a couple tests when thread sanitizer is being used (see in file comments).<commit_after>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee --- Lock Test Functions
///
/// @author Nick LeRoy <nleroy@qualys.com>
//////////////////////////////////////////////////////////////////////////////
#include "ironbee_config_auto.h"
#include <ironbee/types.h>
#include <ironbee/mpool.h>
#include <ironbee/util.h>
#include <ironbee/lock.h>
#include "gtest/gtest.h"
#include "simple_fixture.hpp"
#include <stdexcept>
#include <math.h>
#include <pthread.h>
#if defined(__has_feature)
#if __has_feature(thread_sanitizer)
#define THREAD_SANITIZER
#endif
#endif
/* -- Tests -- */
typedef void *(* thread_start_fn)(void *thread_data);
class Thread
{
public:
explicit
Thread(int num) :
m_handle(0),
m_num(num),
m_started(false),
m_running(false),
m_errors(0)
{
}
Thread() :
m_handle(0),
m_num(-1),
m_started(false),
m_running(false),
m_errors(0)
{
}
void ThreadNum(int num) { m_num = num; };
bool IsRunning() const { return m_running; };
int ThreadNum() const { return m_num; };
uint64_t ThreadId() const { return (uint64_t)m_handle; };
uint64_t Errors() const { return m_errors; };
void Error() { ++m_errors; };
ib_status_t Create(thread_start_fn fn)
{
pthread_t handle;
pthread_attr_t attr;
int status;
if (m_num < 0) {
return IB_EINVAL;
}
if (m_started || m_running) {
return IB_EINVAL;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
m_started = true;
status = pthread_create(&handle, &attr, fn, this);
if (status) {
m_started = false;
return IB_EUNKNOWN;
}
m_handle = handle;
return IB_OK;
}
ib_status_t Join(void)
{
int status;
if (! m_started) {
return IB_OK;
}
status = pthread_join(m_handle, NULL);
if (status != 0) {
return IB_EUNKNOWN;
}
m_running = false;
m_started = false;
return IB_OK;
}
ib_status_t Running(bool run)
{
if (!m_started) {
return IB_EINVAL;
}
if (run == m_running) {
return IB_EINVAL;
}
m_running = run;
return IB_OK;
}
private:
pthread_t m_handle;
int m_num;
bool m_started;
bool m_running;
uint64_t m_errors;
};
class TestIBUtilLock : public SimpleFixture
{
public:
TestIBUtilLock(void) :
m_max_threads(0),
m_threads(NULL),
m_lock_enabled(true),
m_shared(0)
{
TestIBUtilLock::m_self = this;
TestParams(100, 0.0005, true);
}
~TestIBUtilLock(void)
{
if (m_threads != NULL) {
delete []m_threads;
}
}
virtual void SetUp(void)
{
SimpleFixture::SetUp();
}
virtual void TearDown()
{
SimpleFixture::TearDown();
DestroyLock( );
}
ib_status_t CreateLock( void )
{
return ib_lock_init(&m_lock);
}
ib_status_t DestroyLock( void )
{
return ib_lock_destroy(&m_lock);
}
ib_status_t LockLock( void )
{
return ib_lock_lock(&m_lock);
}
ib_status_t UnlockLock( void )
{
return ib_lock_unlock(&m_lock);
}
void InitThreads(size_t max_threads)
{
m_max_threads = max_threads;
m_threads = new Thread[max_threads];
for (int num = 0; num < (int)max_threads; ++num) {
m_threads[num].ThreadNum(num);
}
}
void TestParams(size_t loops, double seconds, bool lock)
{
Loops(loops);
SleepTime(seconds);
m_lock_enabled = lock;
}
void Loops(size_t loops) { m_loops = loops; };
void SleepTime(double sec) { m_sleeptime = sec; };
ib_status_t CreateThread(size_t num)
{
if(m_threads == NULL) {
throw std::runtime_error("Thread handles not initialized.");
}
if (num >= m_max_threads) {
throw std::runtime_error("Thread number greater than max.");
}
Thread *thread = &m_threads[num];
if (thread->IsRunning()) {
throw std::runtime_error("Thread already running.");
}
return thread->Create(TestIBUtilLock::StartThread);
}
ib_status_t CreateAllThreads( void )
{
if(m_threads == NULL) {
throw std::runtime_error("Thread handles not initialized.");
}
size_t num;
for (num = 0; num < m_max_threads; ++num) {
ib_status_t rc = CreateThread(num);
if (rc != IB_OK) {
return rc;
}
}
return IB_OK;
}
ib_status_t StartTest(size_t threads,
size_t loops,
double seconds,
bool lock)
{
InitThreads(threads);
TestParams(loops, seconds, lock);
printf("Starting: %zd threads, %d loops, %.8fs sleep, locks %s\n",
m_max_threads, m_loops, m_sleeptime,
m_lock_enabled ? "enabled" : "disabled");
return CreateAllThreads( );
}
static void *StartThread(void *data)
{
Thread *thread = (Thread *)data;
m_self->RunThread(thread);
return NULL;
}
void RunThread(Thread *thread)
{
ib_status_t rc;
int n;
struct timespec ts;
ts.tv_sec = (time_t)trunc(m_sleeptime);
ts.tv_nsec = (long)(round((m_sleeptime - ts.tv_sec) * 1e9));
thread->Running(true);
for (n = 0; n < m_loops; ++n) {
if (m_lock_enabled) {
rc = LockLock( );
if (rc != IB_OK) {
thread->Error();
break;
}
}
// This code is an intentional race condition if m_lock_enabled is
// false. It is possible for it to fail to cause errors, but, at
// least in common environments, that is very unlikely.
if (++m_shared != 1) {
thread->Error();
}
nanosleep(&ts, NULL);
if (--m_shared != 0) {
thread->Error();
}
if (m_lock_enabled) {
rc = UnlockLock( );
if (rc != IB_OK) {
thread->Error();
break;
}
}
}
thread->Running(false);
}
ib_status_t WaitForThreads(uint64_t *errors)
{
ib_status_t rc = IB_OK;
size_t num;
*errors = 0;
for (num = 0; num < m_max_threads; ++num) {
Thread *thread = &m_threads[num];
ib_status_t irc = thread->Join();
if (irc != IB_OK) {
rc = irc;
}
*errors += thread->Errors();
}
return rc;
}
private:
static TestIBUtilLock *m_self;
size_t m_max_threads;
Thread *m_threads;
ib_lock_t m_lock;
bool m_lock_enabled;
int m_loops;
double m_sleeptime;
volatile int m_shared;
};
TestIBUtilLock *TestIBUtilLock::m_self = NULL;
TEST(test_util_lock, misc)
{
int test = 0;
for (int n=0; n<100; ++n) {
int t;
t = ++test;
ASSERT_EQ(1, t);
t = --test;
ASSERT_EQ(0, t);
}
}
TEST_F(TestIBUtilLock, test_create)
{
ib_status_t rc;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = LockLock( );
ASSERT_EQ(IB_OK, rc);
rc = UnlockLock( );
ASSERT_EQ(IB_OK, rc);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
// The following test is a true positive for a thread race condition.
// Disable it for thread sanitizer.
#ifndef THREAD_SANITIZER
TEST_F(TestIBUtilLock, test_lock_disabled)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(5, 100, 0.0000005, false);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_NE(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
#endif
TEST_F(TestIBUtilLock, test_short)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(5, 100, 0.0000005, true);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_EQ(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
// This test is too intense for the thread sanitizer.
#ifndef THREAD_SANITIZER
TEST_F(TestIBUtilLock, test_long)
{
ib_status_t rc;
uint64_t errors;
rc = CreateLock( );
ASSERT_EQ(IB_OK, rc);
rc = StartTest(20, 1000, 0.00005, true);
ASSERT_EQ(IB_OK, rc);
rc = WaitForThreads( &errors );
ASSERT_EQ(IB_OK, rc);
ASSERT_EQ(0LU, errors);
rc = DestroyLock( );
ASSERT_EQ(IB_OK, rc);
}
#endif
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP
#define VIENNAGRID_STORAGE_INSERTER_HPP
//#include "viennagrid/storage/reference.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/container_collection_element.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_collection_type>
class inserter_base_t
{
public:
inserter_base_t(container_collection_type & _collection) : collection(_collection) {}
protected:
container_collection_type & collection;
};
template<typename container_collection_type, typename id_generator_type_>
class physical_inserter_t
{
public:
typedef container_collection_type physical_container_collection_type;
typedef id_generator_type_ id_generator_type;
physical_inserter_t() : collection(0) {}
physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator_) : collection(&_collection), id_generator(id_generator_) {}
void set_container_collection(container_collection_type & _collection) { collection = &_collection; }
template<bool generate_id, typename value_type, typename inserter_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
physical_insert( value_type element, inserter_type & inserter )
{
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type;
container_type & container = viennagrid::storage::collection::get< value_type >( *collection );
if ( generate_id && !container.is_present( element ) )
viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) );
std::pair<hook_type, bool> ret = container.insert( element );
//container.dereference_hook(ret.first).set_container(collection);
viennagrid::storage::container_collection_element::insert_callback(
container.dereference_hook(ret.first),
ret.second,
inserter);
//viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter);
inserter.hook_insert( ret.first, viennameta::tag<value_type>() );
return ret;
}
template<typename hook_type, typename value_type>
void hook_insert( hook_type ref, viennameta::tag<value_type> )
{}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
operator()( const value_type & element )
{
return physical_insert<true>( element, *this );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
insert_noid( const value_type & element )
{
return physical_insert<true>( element, *this );
}
container_collection_type & get_physical_container_collection() { return *collection; }
id_generator_type & get_id_generator() { return id_generator; }
private:
container_collection_type * collection;
id_generator_type id_generator;
};
template<typename view_collection_type, typename dependend_inserter_type>
class recursive_inserter_t
{
public:
recursive_inserter_t() : view_collection(0), dependend_inserter(0) {}
recursive_inserter_t(view_collection_type & collection_, dependend_inserter_type & dependend_inserter_) :
view_collection(&collection_), dependend_inserter(&dependend_inserter_) {}
void set_container_collection(view_collection_type & _collection) { view_collection = &_collection; }
template<typename hook_type, typename value_type>
void hook_insert( hook_type ref, viennameta::tag<value_type> )
{
viennagrid::storage::container_collection::hook_or_ignore( *view_collection, ref, viennameta::tag<value_type>() );
dependend_inserter->hook_insert( ref, viennameta::tag<value_type>() );
}
typedef typename dependend_inserter_type::physical_container_collection_type physical_container_collection_type;
template<bool generate_id, typename value_type, typename inserter_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
physical_insert( const value_type & element, inserter_type & inserter )
{
return dependend_inserter->physical_insert<generate_id>( element, inserter );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
operator()( const value_type & element )
{
return physical_insert<true>( element, *this );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
insert_noid( const value_type & element )
{
return physical_insert<false>( element, *this );
}
physical_container_collection_type & get_physical_container_collection() { return dependend_inserter->get_physical_container_collection(); }
private:
view_collection_type * view_collection;
dependend_inserter_type * dependend_inserter;
};
namespace inserter
{
//typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config;
//typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config;
template<typename dependend_inserter_type, typename container_collection_type>
recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection )
{
return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection);
}
}
namespace result_of
{
template<typename container_collection_type, typename dependend_inserter_type>
struct recursive_inserter
{
typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type;
};
template<typename container_collection_type, typename id_generator_type>
struct physical_inserter
{
typedef physical_inserter_t<container_collection_type, id_generator_type> type;
};
}
}
}
#endif
<commit_msg>fixed bug with no-id insert<commit_after>#ifndef VIENNAGRID_STORAGE_INSERTER_HPP
#define VIENNAGRID_STORAGE_INSERTER_HPP
//#include "viennagrid/storage/reference.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/container_collection_element.hpp"
namespace viennagrid
{
namespace storage
{
template<typename container_collection_type>
class inserter_base_t
{
public:
inserter_base_t(container_collection_type & _collection) : collection(_collection) {}
protected:
container_collection_type & collection;
};
template<typename container_collection_type, typename id_generator_type_>
class physical_inserter_t
{
public:
typedef container_collection_type physical_container_collection_type;
typedef id_generator_type_ id_generator_type;
physical_inserter_t() : collection(0) {}
physical_inserter_t(container_collection_type & _collection, id_generator_type id_generator_) : collection(&_collection), id_generator(id_generator_) {}
void set_container_collection(container_collection_type & _collection) { collection = &_collection; }
template<bool generate_id, typename value_type, typename inserter_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
physical_insert( value_type element, inserter_type & inserter )
{
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::iterator iterator;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type container_type;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_tag hook_tag;
typedef typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type hook_type;
container_type & container = viennagrid::storage::collection::get< value_type >( *collection );
if ( generate_id && !container.is_present( element ) )
viennagrid::storage::id::set_id(element, id_generator( viennameta::tag<value_type>() ) );
std::pair<hook_type, bool> ret = container.insert( element );
//container.dereference_hook(ret.first).set_container(collection);
viennagrid::storage::container_collection_element::insert_callback(
container.dereference_hook(ret.first),
ret.second,
inserter);
//viennagrid::storage::container_collection_element::insert_callback(*ret.first, ret.second, inserter);
inserter.hook_insert( ret.first, viennameta::tag<value_type>() );
return ret;
}
template<typename hook_type, typename value_type>
void hook_insert( hook_type ref, viennameta::tag<value_type> )
{}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
operator()( const value_type & element )
{
return physical_insert<true>( element, *this );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<container_collection_type, value_type>::type::hook_type,
bool
>
insert_noid( const value_type & element )
{
return physical_insert<false>( element, *this );
}
container_collection_type & get_physical_container_collection() { return *collection; }
id_generator_type & get_id_generator() { return id_generator; }
private:
container_collection_type * collection;
id_generator_type id_generator;
};
template<typename view_collection_type, typename dependend_inserter_type>
class recursive_inserter_t
{
public:
recursive_inserter_t() : view_collection(0), dependend_inserter(0) {}
recursive_inserter_t(view_collection_type & collection_, dependend_inserter_type & dependend_inserter_) :
view_collection(&collection_), dependend_inserter(&dependend_inserter_) {}
void set_container_collection(view_collection_type & _collection) { view_collection = &_collection; }
template<typename hook_type, typename value_type>
void hook_insert( hook_type ref, viennameta::tag<value_type> )
{
viennagrid::storage::container_collection::hook_or_ignore( *view_collection, ref, viennameta::tag<value_type>() );
dependend_inserter->hook_insert( ref, viennameta::tag<value_type>() );
}
typedef typename dependend_inserter_type::physical_container_collection_type physical_container_collection_type;
template<bool generate_id, typename value_type, typename inserter_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
physical_insert( const value_type & element, inserter_type & inserter )
{
return dependend_inserter->physical_insert<generate_id>( element, inserter );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
operator()( const value_type & element )
{
return physical_insert<true>( element, *this );
}
template<typename value_type>
std::pair<
typename viennagrid::storage::result_of::container_of<physical_container_collection_type, value_type>::type::hook_type,
bool
>
insert_noid( const value_type & element )
{
return physical_insert<false>( element, *this );
}
physical_container_collection_type & get_physical_container_collection() { return dependend_inserter->get_physical_container_collection(); }
private:
view_collection_type * view_collection;
dependend_inserter_type * dependend_inserter;
};
namespace inserter
{
//typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::pointer_reference_tag ) pointer_reference_config;
//typedef VIENNAMETA_MAKE_TYPEMAP_1( viennagrid::storage::default_tag, viennagrid::storage::iterator_reference_tag ) iterator_reference_config;
template<typename dependend_inserter_type, typename container_collection_type>
recursive_inserter_t<container_collection_type, dependend_inserter_type> get_recursive( const dependend_inserter_type & inserter, container_collection_type & collection )
{
return recursive_inserter_t<container_collection_type, dependend_inserter_type>(inserter, collection);
}
}
namespace result_of
{
template<typename container_collection_type, typename dependend_inserter_type>
struct recursive_inserter
{
typedef recursive_inserter_t<container_collection_type, dependend_inserter_type> type;
};
template<typename container_collection_type, typename id_generator_type>
struct physical_inserter
{
typedef physical_inserter_t<container_collection_type, id_generator_type> type;
};
}
}
}
#endif
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
#ifndef DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
#define DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
#include <dune/geometry/referenceelements.hh>
#include <dune/geometry/type.hh>
#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange/p0.hh>
#include <dune/localfunctions/lagrange.hh>
#include <dune/gdt/exceptions.hh>
#include "interfaces.hh"
#include "wrapper.hh"
namespace Dune {
namespace GDT {
/**
* This is the P0LocalFiniteElement from dune-localfunctions with suitable Lagrange points (which is also all that
* differs in the implementation with respect to LocalFiniteElementWrapper).
*/
template <class D, size_t d, class R>
class P0LagrangeFiniteElement : public LocalFiniteElementInterface<D, d, R, 1, 1>
{
using ThisType = P0LagrangeFiniteElement<D, d, R>;
using BaseType = LocalFiniteElementInterface<D, d, R, 1, 1>;
using Implementation = P0LocalFiniteElement<D, R, d>;
using BasisWrapperType =
LocalFiniteElementBasisWrapper<typename Implementation::Traits::LocalBasisType, D, d, R, 1, 1>;
using CoefficientsWrapperType =
LocalFiniteElementCoefficientsWrapper<typename Implementation::Traits::LocalCoefficientsType, D, d>;
using InterpolationWrapperType =
LocalFiniteElementInterpolationWrapper<typename Implementation::Traits::LocalInterpolationType, D, d, R, 1, 1>;
public:
using typename BaseType::DomainType;
using typename BaseType::BasisType;
using typename BaseType::CoefficientsType;
using typename BaseType::InterpolationType;
P0LagrangeFiniteElement(Implementation*&& imp_ptr)
: imp_(std::move(imp_ptr))
, basis_(imp_.access().type(), imp_.access().localBasis())
, coefficients_(imp_.access().type(), imp_.access().localCoefficients())
, interpolation_(imp_.access().type(), imp_.access().localInterpolation())
, lagrange_points_({ReferenceElements<D, d>::general(imp_.access().type()).position(0, 0)})
{
}
P0LagrangeFiniteElement(const Implementation& imp)
: imp_(imp)
, basis_(imp_.access().type(), imp_.access().localBasis())
, coefficients_(imp_.access().type(), imp_.access().localCoefficients())
, interpolation_(imp_.access().type(), imp_.access().localInterpolation())
, lagrange_points_({ReferenceElements<D, d>::general(imp_.access().type()).position(0, 0)})
{
}
template <class... Args>
explicit P0LagrangeFiniteElement(Args&&... args)
: imp_(new Implementation(std::forward<Args>(args)...))
, basis_(imp_.access().type(), imp_.access().localBasis())
, coefficients_(imp_.access().type(), imp_.access().localCoefficients())
, interpolation_(imp_.access().type(), imp_.access().localInterpolation())
, lagrange_points_({ReferenceElements<D, d>::general(imp_.access().type()).position(0, 0)})
{
}
const GeometryType& geometry_type() const
{
return basis_.geometry_type();
}
size_t size() const override final
{
return XT::Common::numeric_cast<size_t>(imp_.access().size());
}
const BasisType& basis() const override final
{
return basis_;
}
const CoefficientsType& coefficients() const override final
{
return coefficients_;
}
const InterpolationType& interpolation() const override final
{
return interpolation_;
}
bool is_lagrangian() const override final
{
return true;
}
const std::vector<DomainType>& lagrange_points() const override final
{
return lagrange_points_;
}
private:
const XT::Common::ConstStorageProvider<Implementation> imp_;
const BasisWrapperType basis_;
const CoefficientsWrapperType coefficients_;
const InterpolationWrapperType interpolation_;
const std::vector<DomainType> lagrange_points_;
}; // class P0LagrangeFiniteElement
template <class D, size_t d, class R>
std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1, 1>>
make_lagrange_local_finite_element(const GeometryType& geometry_type, const int& polorder)
{
// special case
if (polorder == 0)
return std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1, 1>>(
new P0LagrangeFiniteElement<D, d, R>(geometry_type));
// checks
if (d == 1) {
if (polorder > 18)
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 1d "
"for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else if (d == 2) {
if (geometry_type == GeometryType(GeometryType::simplex, 2)) {
if (polorder > 15)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 2d "
"on simplices for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::cube, 2)) {
if (polorder > 10)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 2d "
"on cubes for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< polorder);
} else if (d == 3) {
if (geometry_type == GeometryType(GeometryType::simplex, 3)) {
if (polorder > 14)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on simplices for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::cube, 3)) {
if (polorder > 7)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on cubes for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::prism, 3)) {
if (polorder > 9)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on prisms for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::pyramid, 3)) {
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on pyramids for polorder "
<< polorder
<< " (if you think it is working, update this check)!");
} else
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< polorder);
} else
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< polorder);
// the actual finite element
return std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1, 1>>(
new LocalFiniteElementWrapper<LagrangeLocalFiniteElement<EquidistantPointSet, d, D, R>, D, d, R, 1>(geometry_type,
polorder));
} // ... make_lagrange_local_finite_element(...)
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
<commit_msg>[local.finite-elements.lagrange] update implementation<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
#ifndef DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
#define DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
#include <memory>
#include <dune/geometry/referenceelements.hh>
#include <dune/geometry/type.hh>
#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange/p0.hh>
#include <dune/localfunctions/lagrange.hh>
#include <dune/gdt/exceptions.hh>
#include "interfaces.hh"
#include "default.hh"
#include "wrapper.hh"
#include "0d.hh"
namespace Dune {
namespace GDT {
/**
* Wraps the P0LocalFiniteElement from dune-localfunctions and adds Lagrange points.
*/
template <class D, size_t d, class R>
class LocalZeroOrderLagrangeFiniteElement
: XT::Common::ConstStorageProvider<LocalFiniteElementWrapper<P0LocalFiniteElement<D, R, d>, D, d, R, 1>>,
public LocalFiniteElementDefault<D, d, R, 1>
{
using ThisType = LocalZeroOrderLagrangeFiniteElement<D, d, R>;
using Implementation = P0LocalFiniteElement<D, R, d>;
using Wrapper = LocalFiniteElementWrapper<Implementation, D, d, R, 1>;
using Storage = XT::Common::ConstStorageProvider<Wrapper>;
using BaseType = LocalFiniteElementDefault<D, d, R, 1>;
public:
LocalZeroOrderLagrangeFiniteElement(Implementation*&& imp_ptr)
: XT::Common::ConstStorageProvider<Wrapper>(new Wrapper(0, std::move(imp_ptr)))
, BaseType(0,
Storage::access().basis().copy(),
Storage::access().coefficients().copy(),
Storage::access().interpolation().copy(),
{ReferenceElements<D, d>::general(Storage::access().geometry_type()).position(0, 0)})
{
}
LocalZeroOrderLagrangeFiniteElement(const Implementation& imp)
: LocalZeroOrderLagrangeFiniteElement(new Implementation(imp))
{
}
template <class... Args>
explicit LocalZeroOrderLagrangeFiniteElement(Args&&... args)
: LocalZeroOrderLagrangeFiniteElement(new Implementation(std::forward<Args>(args)...))
{
}
}; // class LocalZeroOrderLagrangeFiniteElement
/**
* \note Update this class if anything changes in dune-localfunctions.
*/
template <class D, size_t d, class R>
class LocalLagrangeFiniteElementFactory
{
using LocalFiniteElementType = LocalFiniteElementInterface<D, d, R, 1>;
template <size_t d_ = d, bool anything = true>
struct helper
{
static std::unique_ptr<LocalFiniteElementType> create(const GeometryType& geometry_type, const int& order)
{
// special case
if (order == 0)
return std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1>>(
new LocalZeroOrderLagrangeFiniteElement<D, d, R>(geometry_type));
// checks
if (d == 1) {
if (order > 18)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 1d "
"for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else if (d == 2) {
if (geometry_type == GeometryType(GeometryType::simplex, 2)) {
if (order > 15)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 2d "
"on simplices for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::cube, 2)) {
if (order > 10)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 2d "
"on cubes for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< order);
} else if (d == 3) {
if (geometry_type == GeometryType(GeometryType::simplex, 3)) {
if (order > 14)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on simplices for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::cube, 3)) {
if (order > 7)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on cubes for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::prism, 3)) {
if (order > 9)
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on prisms for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else if (geometry_type == GeometryType(GeometryType::pyramid, 3)) {
DUNE_THROW(
Exceptions::finite_element_error,
"when creating a local Lagrange finite element: the LagrangeLocalFiniteElement is known to fail in 3d "
"on pyramids for polorder "
<< order
<< " (if you think it is working, update this check)!");
} else
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< order);
} else {
// If these are available (a.k.a, this compiles for d > 3), they should most likely work for lower orders.
DUNE_THROW(Exceptions::finite_element_error,
"when creating a local Lagrange finite element: this is untested!\n"
<< "Please update this check if you believe that a suitable finite element is available for\n"
<< "- dimension: "
<< d
<< "\n"
<< "-n geometry_type: "
<< geometry_type
<< "\n"
<< "- polorder: "
<< order);
}
// the actual finite element
return std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1>>(
new LocalFiniteElementWrapper<LagrangeLocalFiniteElement<EquidistantPointSet, d, D, R>, D, d, R, 1>(
order, geometry_type, order));
}
}; // helper<...>
template <bool anything>
struct helper<0, anything>
{
static std::unique_ptr<LocalFiniteElementType> create(const GeometryType& geometry_type, const int& /*order*/)
{
// If we need this, and geometry_type.dim() == 0, we must simply implement the corresponding ctors of the 0d FE!
DUNE_THROW_IF(
geometry_type.dim() != 0 || !geometry_type.isSimplex(),
Exceptions::finite_element_error,
"when creating a local 0d orthonomal finite element: not available for geometry_type = " << geometry_type);
return std::make_unique<Local0dFiniteElement<D, R>>();
}
}; // helper<...>
public:
static std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1>> create(const GeometryType& geometry_type,
const int& order)
{
return helper<>::create(geometry_type, order);
}
}; // class LocalLagrangeFiniteElementFactory
template <class D, size_t d, class R>
std::unique_ptr<LocalFiniteElementInterface<D, d, R, 1>>
make_local_lagrange_finite_element(const GeometryType& geometry_type, const int order)
{
return LocalLagrangeFiniteElementFactory<D, d, R>::create(geometry_type, order);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_LOCAL_FINITE_ELEMENTS_LAGRANGE_HH
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/geometry/genericreferenceelements.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
typedef SpaceInterface<ImpTraits> BaseType;
typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase()
{
}
using BaseType::compute_pattern;
template <class G, class S>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (Stuff::Common::FloatCmp::eq(this->tmp_basis_values_[jj][0], RangeFieldType(1))) {
local_vertices[jj] = local_vertex;
++ones;
} else if (Stuff::Common::FloatCmp::eq(1.0 + this->tmp_basis_values_[jj][0], RangeFieldType(1)))
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set<size_t> localDirichletDofs;
std::vector<DomainType> dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
if (boundaryInfo.dirichlet(intersection)) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (Stuff::Common::FloatCmp::eq(this->tmp_basis_values_[jj][0], RangeFieldType(1))) {
localDirichletDofs.insert(jj);
++ones;
} else if (Stuff::Common::FloatCmp::eq(1.0 + this->tmp_basis_values_[jj][0], RangeFieldType(1)))
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template <class C, bool set_row>
struct DirichletConstraints;
template <class C>
struct DirichletConstraints<C, true>
{
static RangeFieldType value()
{
return RangeFieldType(1);
}
};
template <class C>
struct DirichletConstraints<C, false>
{
static RangeFieldType value()
{
return RangeFieldType(0);
}
};
template <class T, bool set_row>
void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
typedef DirichletConstraints<Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>, set_row> SetRow;
const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.setSize(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (auto localDirichletDofIt = localDirichletDofs.begin(); localDirichletDofIt != localDirichletDofs.end();
++localDirichletDofIt) {
const size_t& localDirichletDofIndex = *localDirichletDofIt;
ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.globalCol(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = SetRow::value();
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.setSize(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
template <bool set>
void local_constraints(const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const
{
local_constraints(*this, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector<size_t> tmpMappedRows_;
mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_HH
<commit_msg>[spaces.cg.base] fixed header guard<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#include <type_traits>
#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>
#include <dune/geometry/genericreferenceelements.hh>
#include <dune/stuff/common/exceptions.hh>
#include "../interface.hh"
namespace Dune {
namespace GDT {
namespace Spaces {
// forward, to allow for specialization
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class ContinuousLagrangeBase
{
static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!");
};
template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim>
class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits>
{
typedef SpaceInterface<ImpTraits> BaseType;
typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType;
public:
typedef ImpTraits Traits;
using BaseType::polOrder;
using typename BaseType::DomainFieldType;
using BaseType::dimDomain;
using typename BaseType::DomainType;
typedef typename Traits::RangeFieldType RangeFieldType;
using BaseType::dimRange;
using BaseType::dimRangeCols;
using typename BaseType::EntityType;
using typename BaseType::IntersectionType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::PatternType;
virtual ~ContinuousLagrangeBase()
{
}
using BaseType::compute_pattern;
template <class G, class S>
PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const
{
return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
}
virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
// get the basis and reference element
const auto basis = this->base_function_set(entity);
const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
const int num_vertices = reference_element.size(dimDomain);
assert(num_vertices >= 0);
assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
// prepare return vector
std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
// loop over all vertices
for (int ii = 0; ii < num_vertices; ++ii) {
// get the local coordinate of the iith vertex
const auto local_vertex = reference_element.position(ii, dimDomain);
// evaluate the basefunctionset
basis.evaluate(local_vertex, this->tmp_basis_values_);
// find the basis function that evaluates to one here (has to be only one!)
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (Stuff::Common::FloatCmp::eq(this->tmp_basis_values_[jj][0], RangeFieldType(1))) {
local_vertices[jj] = local_vertex;
++ones;
} else if (Stuff::Common::FloatCmp::eq(1.0 + this->tmp_basis_values_[jj][0], RangeFieldType(1)))
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return local_vertices;
} // ... lagrange_points(...)
virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
{
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
// check
assert(this->grid_view()->indexSet().contains(entity));
// prepare
std::set<size_t> localDirichletDofs;
std::vector<DomainType> dirichlet_vertices;
// get all dirichlet vertices of this entity, therefore
// * loop over all intersections
const auto intersection_it_end = this->grid_view()->iend(entity);
for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end;
++intersection_it) {
// only work on dirichlet ones
const auto& intersection = *intersection_it;
if (boundaryInfo.dirichlet(intersection)) {
// and get the vertices of the intersection
const auto geometry = intersection.geometry();
for (int cc = 0; cc < geometry.corners(); ++cc)
dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
} // only work on dirichlet ones
} // loop over all intersections
// find the corresponding basis functions
const auto basis = this->base_function_set(entity);
if (this->tmp_basis_values_.size() < basis.size())
this->tmp_basis_values_.resize(basis.size());
for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
// find the basis function that evaluates to one here (has to be only one!)
basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
size_t ones = 0;
size_t zeros = 0;
size_t failures = 0;
for (size_t jj = 0; jj < basis.size(); ++jj) {
if (Stuff::Common::FloatCmp::eq(this->tmp_basis_values_[jj][0], RangeFieldType(1))) {
localDirichletDofs.insert(jj);
++ones;
} else if (Stuff::Common::FloatCmp::eq(1.0 + this->tmp_basis_values_[jj][0], RangeFieldType(1)))
++zeros;
else
++failures;
}
assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
}
return localDirichletDofs;
} // ... local_dirichlet_DoFs(...)
private:
template <class C, bool set_row>
struct DirichletConstraints;
template <class C>
struct DirichletConstraints<C, true>
{
static RangeFieldType value()
{
return RangeFieldType(1);
}
};
template <class C>
struct DirichletConstraints<C, false>
{
static RangeFieldType value()
{
return RangeFieldType(0);
}
};
template <class T, bool set_row>
void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const
{
// check
static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
if (dimRange != 1)
DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
assert(this->grid_view()->indexSet().contains(entity));
typedef DirichletConstraints<Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>, set_row> SetRow;
const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
const size_t numRows = localDirichletDofs.size();
if (numRows > 0) {
const size_t numCols = this->mapper().numDofs(entity);
ret.setSize(numRows, numCols);
this->mapper().globalIndices(entity, tmpMappedRows_);
other.mapper().globalIndices(entity, tmpMappedCols_);
size_t localRow = 0;
const RangeFieldType zero(0);
for (auto localDirichletDofIt = localDirichletDofs.begin(); localDirichletDofIt != localDirichletDofs.end();
++localDirichletDofIt) {
const size_t& localDirichletDofIndex = *localDirichletDofIt;
ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
for (size_t jj = 0; jj < ret.cols(); ++jj) {
ret.globalCol(jj) = tmpMappedCols_[jj];
if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
ret.value(localRow, jj) = SetRow::value();
else
ret.value(localRow, jj) = zero;
}
++localRow;
}
} else {
ret.setSize(0, 0);
}
} // ... compute_local_constraints(..., Dirichlet< ..., true >)
public:
template <bool set>
void local_constraints(const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const
{
local_constraints(*this, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const
{
compute_local_constraints(other, entity, ret);
}
virtual void local_constraints(const ThisType& other, const EntityType& entity,
Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const
{
compute_local_constraints(other, entity, ret);
}
protected:
mutable Dune::DynamicVector<size_t> tmpMappedRows_;
mutable Dune::DynamicVector<size_t> tmpMappedCols_;
}; // class ContinuousLagrangeBase
} // namespace Spaces
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// File: oapiimpl.hpp
//
// Desc: OpenCVR API - OpenCVR API.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __VSC_OAPIS_IMPL_H_
#define __VSC_OAPIS_IMPL_H_
BOOL OAPIConverter::Converter(VSCDeviceData__ &from, oapi::Device &to)
{
to.nId = from.nId;
to.nType = from.nType;
to.nSubType = from.nSubType;
to.Name = from.Name;
to.Param = from.Param;
to.IP = from.IP;
to.Port = from.Port;
to.User = from.User;
to.Password = from.Password;
to.RtspLocation = from.RtspLocation;
to.FileLocation = from.FileLocation;
to.OnvifAddress = from.OnvifAddress;
to.CameraIndex = from.CameraIndex;
to.UseProfileToken = from.UseProfileToken;
to.OnvifProfileToken = from.OnvifProfileToken;
to.Recording = from.Recording;
to.GroupId = from.GroupId;
to.HdfsRecording = from.HdfsRecording;
to.OnvifProfileToken2 = from.OnvifProfileToken2;
to.ConnectType = from.ConnectType;
to.Mining = from.Mining;
to.HWAccel = from.HWAccel;
to.IPV6 = from.IPV6;
return TRUE;
}
BOOL OAPIConverter::Converter(oapi::Device &from, VSCDeviceData__ &to)
{
return TRUE;
}
OAPIServer::OAPIServer(XRef<XSocket> pSocket, Factory &pFactory)
:m_pFactory(pFactory), m_pSocket(pSocket)
{
}
OAPIServer::~OAPIServer()
{
}
BOOL OAPIServer::ProcessGetDevice(s32 len)
{
if (len != 0)
{
return FALSE;
}
oapi::DeviceList dataList;
dataList.Num = 0;
DeviceParamMap pDeviceMap;
m_pFactory.GetDeviceParamMap(pDeviceMap);
DeviceParamMap::iterator it = pDeviceMap.begin();
for(; it!=pDeviceMap.end(); ++it)
{
oapi::Device data;
OAPIConverter::Converter(((*it).second).m_Conf.data.conf, data);
dataList.list.push_back(data);
dataList.Num ++;
}
//autojsoncxx::to_json_string
std::string strJson = autojsoncxx::to_pretty_json_string(dataList);
s32 nJsonLen = strJson.length();
if (nJsonLen <= 0)
{
return FALSE;
}
OAPIHeader header;
header.cmd = htonl(OAPI_CMD_GET_DEVICE_RSP);
header.length = htonl(nJsonLen + 1);
m_pSocket->Send((void *)&header, sizeof(header));
m_pSocket->Send((void *)strJson.c_str(), nJsonLen + 1);
return TRUE;
}
BOOL OAPIServer::Process(OAPIHeader &header)
{
header.version = ntohl(header.version);
header.cmd = ntohl(header.cmd);
header.length = ntohl(header.length);
switch(header.cmd)
{
case OAPI_CMD_KEEPALIVE_REQ:
break;
case OAPI_CMD_GET_DEVICE_REQ:
return ProcessGetDevice(header.length);
break;
default:
break;
}
return TRUE;
}
#endif<commit_msg>add get device online<commit_after>//------------------------------------------------------------------------------
// File: oapiimpl.hpp
//
// Desc: OpenCVR API - OpenCVR API.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------
#ifndef __VSC_OAPIS_IMPL_H_
#define __VSC_OAPIS_IMPL_H_
BOOL OAPIConverter::Converter(VSCDeviceData__ &from, oapi::Device &to)
{
to.nId = from.nId;
to.nType = from.nType;
to.nSubType = from.nSubType;
to.Name = from.Name;
to.Param = from.Param;
to.IP = from.IP;
to.Port = from.Port;
to.User = from.User;
to.Password = from.Password;
to.RtspLocation = from.RtspLocation;
to.FileLocation = from.FileLocation;
to.OnvifAddress = from.OnvifAddress;
to.CameraIndex = from.CameraIndex;
to.UseProfileToken = from.UseProfileToken;
to.OnvifProfileToken = from.OnvifProfileToken;
to.Recording = from.Recording;
to.GroupId = from.GroupId;
to.HdfsRecording = from.HdfsRecording;
to.OnvifProfileToken2 = from.OnvifProfileToken2;
to.ConnectType = from.ConnectType;
to.Mining = from.Mining;
to.HWAccel = from.HWAccel;
to.IPV6 = from.IPV6;
return TRUE;
}
BOOL OAPIConverter::Converter(oapi::Device &from, VSCDeviceData__ &to)
{
return TRUE;
}
OAPIServer::OAPIServer(XRef<XSocket> pSocket, Factory &pFactory)
:m_pFactory(pFactory), m_pSocket(pSocket)
{
}
OAPIServer::~OAPIServer()
{
}
BOOL OAPIServer::ProcessGetDevice(s32 len)
{
if (len != 0)
{
return FALSE;
}
oapi::DeviceList dataList;
dataList.Num = 0;
DeviceParamMap pDeviceMap;
DeviceOnlineMap pDeviceOnlineMap;
m_pFactory.GetDeviceParamMap(pDeviceMap);
m_pFactory.GetDeviceOnlineMap(pDeviceOnlineMap);
DeviceParamMap::iterator it = pDeviceMap.begin();
for(; it!=pDeviceMap.end(); ++it)
{
oapi::Device data;
OAPIConverter::Converter(((*it).second).m_Conf.data.conf, data);
data.Online = pDeviceOnlineMap[(*it).first];
dataList.list.push_back(data);
dataList.Num ++;
}
//autojsoncxx::to_json_string
std::string strJson = autojsoncxx::to_pretty_json_string(dataList);
s32 nJsonLen = strJson.length();
if (nJsonLen <= 0)
{
return FALSE;
}
OAPIHeader header;
header.cmd = htonl(OAPI_CMD_KEEPALIVE_RSQ);
header.length = htonl(nJsonLen + 1);
m_pSocket->Send((void *)&header, sizeof(header));
m_pSocket->Send((void *)strJson.c_str(), nJsonLen + 1);
return TRUE;
}
BOOL OAPIServer::Process(OAPIHeader &header)
{
header.version = ntohl(header.version);
header.cmd = ntohl(header.cmd);
header.length = ntohl(header.length);
switch(header.cmd)
{
case OAPI_CMD_KEEPALIVE_REQ:
break;
case OAPI_CMD_DEVICE_LIST_REQ:
return ProcessGetDevice(header.length);
break;
default:
break;
}
return TRUE;
}
#endif<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH
#define DUNE_GDT_OPERATOR_PRODUCTS_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>
#include "../basefunctionset/wrapper.hh"
#include "../localfunctional/codim0.hh"
#include "../localevaluation/product.hh"
namespace Dune {
namespace GDT {
namespace ProductOperator {
template< class GridPartType >
class L2
{
public:
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RangeType, class SourceType >
typename RangeType::template LocalFunction< typename GridPartType::template Codim< 0 >::EntityType >::Type::RangeFieldType
apply2(const RangeType& range, const SourceType& source) const
{
// checks
static_assert(std::is_base_of< Stuff::LocalizableFunction, SourceType >::value,
"SourceType has to be derived from Stuff::LocalizableFunction!");
static_assert(std::is_base_of< Stuff::LocalizableFunction, RangeType >::value,
"RangeType has to be derived from Stuff::LocalizableFunction!");
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename SourceType::template LocalFunction< EntityType >::Type SourceLocalFunctionType;
typedef typename RangeType::template LocalFunction< EntityType >::Type RangeLocalFunctionType;
typedef typename SourceLocalFunctionType::DomainFieldType DomainFieldType;
static_assert(std::is_same< DomainFieldType, typename RangeLocalFunctionType::DomainFieldType >::value,
"DomainFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimDomain = SourceLocalFunctionType::dimDomain;
static_assert(dimDomain == RangeLocalFunctionType::dimDomain,
"dimDomain of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
typedef typename SourceLocalFunctionType::RangeFieldType RangeFieldType;
static_assert(std::is_same< RangeFieldType, typename RangeLocalFunctionType::RangeFieldType >::value,
"RangeFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeRows = SourceLocalFunctionType::dimRangeRows;
static_assert(dimRangeRows == RangeLocalFunctionType::dimRangeRows,
"dimRangeRows of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeCols = SourceLocalFunctionType::dimRangeCols;
static_assert(dimRangeCols == RangeLocalFunctionType::dimRangeCols,
"dimRangeCols of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
// some preparations
typedef LocalFunctional::Codim0Integral< LocalEvaluation::Product< RangeType > > LocalFunctionalType;
const LocalFunctionalType local_functional(range);
RangeFieldType ret = 0;
DynamicVector< RangeFieldType > local_functional_result(1, 0);
std::vector< DynamicVector< RangeFieldType > > tmp_vectors(local_functional.numTmpObjectsRequired(),
DynamicVector< RangeFieldType >(1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local function
const auto source_local_function = source.localFunction(entity);
typedef BaseFunctionSet::LocalFunctionWrapper< SourceLocalFunctionType, DomainFieldType, dimDomain,
RangeFieldType, dimRangeRows, dimRangeCols > LocalSourceWrapperType;
const LocalSourceWrapperType local_source_wrapper(source_local_function);
// apply local functional
local_functional.apply(local_source_wrapper, local_functional_result, tmp_vectors);
assert(local_functional_result.size() == 1);
ret += local_functional_result[0];
} // walk the grid
return ret;
}
private:
const GridPartType& grid_part_;
}; // class L2
} // namespace ProductOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PRODUCTS_HH
<commit_msg>[operator.products] added H1<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH
#define DUNE_GDT_OPERATOR_PRODUCTS_HH
#include <type_traits>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/functions/constant.hh>
#include "../basefunctionset/wrapper.hh"
#include "../localfunctional/codim0.hh"
#include "../localevaluation/product.hh"
#include "../localoperator/codim0.hh"
#include "../localevaluation/elliptic.hh"
namespace Dune {
namespace GDT {
namespace ProductOperator {
template< class GridPartType >
class L2
{
public:
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RangeType, class SourceType >
typename RangeType::template LocalFunction< typename GridPartType::template Codim< 0 >::EntityType >::Type::RangeFieldType
apply2(const RangeType& range, const SourceType& source) const
{
// checks
static_assert(std::is_base_of< Stuff::LocalizableFunction, SourceType >::value,
"SourceType has to be derived from Stuff::LocalizableFunction!");
static_assert(std::is_base_of< Stuff::LocalizableFunction, RangeType >::value,
"RangeType has to be derived from Stuff::LocalizableFunction!");
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename SourceType::template LocalFunction< EntityType >::Type SourceLocalFunctionType;
typedef typename RangeType::template LocalFunction< EntityType >::Type RangeLocalFunctionType;
typedef typename SourceLocalFunctionType::DomainFieldType DomainFieldType;
static_assert(std::is_same< DomainFieldType, typename RangeLocalFunctionType::DomainFieldType >::value,
"DomainFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimDomain = SourceLocalFunctionType::dimDomain;
static_assert(dimDomain == RangeLocalFunctionType::dimDomain,
"dimDomain of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
typedef typename SourceLocalFunctionType::RangeFieldType RangeFieldType;
static_assert(std::is_same< RangeFieldType, typename RangeLocalFunctionType::RangeFieldType >::value,
"RangeFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeRows = SourceLocalFunctionType::dimRangeRows;
static_assert(dimRangeRows == RangeLocalFunctionType::dimRangeRows,
"dimRangeRows of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeCols = SourceLocalFunctionType::dimRangeCols;
static_assert(dimRangeCols == RangeLocalFunctionType::dimRangeCols,
"dimRangeCols of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
// some preparations
typedef LocalFunctional::Codim0Integral< LocalEvaluation::Product< RangeType > > LocalFunctionalType;
const LocalFunctionalType local_functional(range);
RangeFieldType ret = 0;
DynamicVector< RangeFieldType > local_functional_result(1, 0);
std::vector< DynamicVector< RangeFieldType > > tmp_vectors(local_functional.numTmpObjectsRequired(),
DynamicVector< RangeFieldType >(1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local function
const auto source_local_function = source.localFunction(entity);
typedef BaseFunctionSet::LocalFunctionWrapper< SourceLocalFunctionType, DomainFieldType, dimDomain,
RangeFieldType, dimRangeRows, dimRangeCols > LocalSourceWrapperType;
const LocalSourceWrapperType local_source_wrapper(source_local_function);
// apply local functional
local_functional.apply(local_source_wrapper, local_functional_result, tmp_vectors);
assert(local_functional_result.size() == 1);
ret += local_functional_result[0];
} // walk the grid
return ret;
}
private:
const GridPartType& grid_part_;
}; // class L2
template< class GridPartType >
class H1
{
public:
H1(const GridPartType& grid_part)
: grid_part_(grid_part)
{}
template< class RangeType, class SourceType >
typename RangeType::template LocalFunction< typename GridPartType::template Codim< 0 >::EntityType >::Type::RangeFieldType
apply2(const RangeType& range, const SourceType& source) const
{
// checks
static_assert(std::is_base_of< Stuff::LocalizableFunction, SourceType >::value,
"SourceType has to be derived from Stuff::LocalizableFunction!");
static_assert(std::is_base_of< Stuff::LocalizableFunction, RangeType >::value,
"RangeType has to be derived from Stuff::LocalizableFunction!");
typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
typedef typename SourceType::template LocalFunction< EntityType >::Type SourceLocalFunctionType;
typedef typename RangeType::template LocalFunction< EntityType >::Type RangeLocalFunctionType;
typedef typename SourceLocalFunctionType::DomainFieldType DomainFieldType;
static_assert(std::is_same< DomainFieldType, typename RangeLocalFunctionType::DomainFieldType >::value,
"DomainFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimDomain = SourceLocalFunctionType::dimDomain;
static_assert(dimDomain == RangeLocalFunctionType::dimDomain,
"dimDomain of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
typedef typename SourceLocalFunctionType::RangeFieldType RangeFieldType;
static_assert(std::is_same< RangeFieldType, typename RangeLocalFunctionType::RangeFieldType >::value,
"RangeFieldType of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeRows = SourceLocalFunctionType::dimRangeRows;
static_assert(dimRangeRows == RangeLocalFunctionType::dimRangeRows,
"dimRangeRows of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
static const unsigned int dimRangeCols = SourceLocalFunctionType::dimRangeCols;
static_assert(dimRangeCols == RangeLocalFunctionType::dimRangeCols,
"dimRangeCols of SourceLocalFunctionType and RangeLocalFunctionType do not match!");
// some preparations
typedef Stuff::FunctionConstant< DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >
ConstantFunctionType;
const ConstantFunctionType one(1);
typedef LocalOperator::Codim0Integral< LocalEvaluation::Elliptic< ConstantFunctionType > > LocalOperatorType;
const LocalOperatorType local_operator(one);
RangeFieldType ret = 0;
DynamicMatrix< RangeFieldType > local_operator_result(1, 1, 0);
std::vector< DynamicMatrix< RangeFieldType > > tmp_matrices(local_operator.numTmpObjectsRequired(),
DynamicMatrix< RangeFieldType >(1, 1, 0));
// walk the grid
const auto entity_it_end = grid_part_.template end< 0 >();
for (auto entity_it = grid_part_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get the local functions
const auto source_local_function = source.localFunction(entity);
typedef BaseFunctionSet::LocalFunctionWrapper< SourceLocalFunctionType, DomainFieldType, dimDomain,
RangeFieldType, dimRangeRows, dimRangeCols > LocalSourceWrapperType;
const LocalSourceWrapperType local_source_wrapper(source_local_function);
const auto range_local_function = range.localFunction(entity);
typedef BaseFunctionSet::LocalFunctionWrapper< RangeLocalFunctionType, DomainFieldType, dimDomain,
RangeFieldType, dimRangeRows, dimRangeCols > LocalRangeWrapperType;
const LocalRangeWrapperType local_range_wrapper(range_local_function);
// apply local operator
local_operator.apply(local_source_wrapper, local_range_wrapper, local_operator_result, tmp_matrices);
assert(local_operator_result.rows() == 1);
assert(local_operator_result.cols() == 1);
ret += local_operator_result[0][0];
} // walk the grid
return ret;
}
private:
const GridPartType& grid_part_;
}; // class H1
} // namespace ProductOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PRODUCTS_HH
<|endoftext|> |
<commit_before>/*
To run, compile and execute a C++ program on Linux Mint /Ubuntu.
First install the g++ compiler...
sudo apt-get install g++
...and then follow the steps:
Open terminal ( Ctrl+Alt+t)
Locate the program file on terminal
g++ programname -o outputfilename
g++ helloworld.cpp -o hello
./hello
*/
//helloworld.cpp
//2014.02.19 Gustaf - CTG.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Hello world - Linux Mint." << endl;
cout << endl;
return 0;
}
<commit_msg>Updated the mini template.<commit_after>/*
To run, compile and execute a C++ program on Linux Mint /Ubuntu.
First install the g++ compiler...
sudo apt-get install g++
...and then follow the steps:
Open terminal ( Ctrl+Alt+t)
Locate the program file on terminal
g++ programname -o outputfilename
g++ helloworld.cpp -o hello
./hello
*/
//helloworld.cpp
//2014.02.24 Gustaf - CTG.
/* EXERCISE / PROBLEM / OBJECTIVE :
=== PLAN ===
-
-
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Hello world - Linux Mint." << endl;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * 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.
*
* $Id$
*
*/
#ifndef PCL_FEATURES_IMPL_RSD_H_
#define PCL_FEATURES_IMPL_RSD_H_
#include <cfloat>
#include "pcl/features/rsd.h"
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> Eigen::MatrixXf
pcl::computeRSD (boost::shared_ptr<const pcl::PointCloud<PointInT> > &surface, boost::shared_ptr<const pcl::PointCloud<PointNT> > &normals,
const std::vector<int> &indices, double max_dist,
int nr_subdiv, double plane_radius, PointOutT &radii, bool compute_histogram)
{
Eigen::MatrixXf histogram;
// Check if the full histogram has to be saved or not
if (compute_histogram)
histogram = Eigen::MatrixXf::Zero (nr_subdiv, nr_subdiv);
// Initialize minimum and maximum angle values in each distance bin
std::vector<std::vector<double> > min_max_angle_by_dist (nr_subdiv);
min_max_angle_by_dist[0].resize (2);
min_max_angle_by_dist[0][0] = min_max_angle_by_dist[0][1] = 0.0;
for (int di=1; di<nr_subdiv; di++)
{
min_max_angle_by_dist[di].resize (2);
min_max_angle_by_dist[di][0] = +DBL_MAX;
min_max_angle_by_dist[di][1] = -DBL_MAX;
}
// Compute distance by normal angle distribution for points
std::vector<int>::const_iterator i, begin (indices.begin()), end (indices.end());
for(i = begin+1; i != end; ++i)
{
// compute angle between the two lines going through normals (disregard orientation!)
double cosine = normals->points[*i].normal[0] * normals->points[*begin].normal[0] +
normals->points[*i].normal[1] * normals->points[*begin].normal[1] +
normals->points[*i].normal[2] * normals->points[*begin].normal[2];
if (cosine > 1) cosine = 1;
if (cosine < -1) cosine = -1;
double angle = acos (cosine);
if (angle > M_PI/2) angle = M_PI - angle; /// \note: orientation is neglected!
// Compute point to point distance
double dist = sqrt ((surface->points[*i].x - surface->points[*begin].x) * (surface->points[*i].x - surface->points[*begin].x) +
(surface->points[*i].y - surface->points[*begin].y) * (surface->points[*i].y - surface->points[*begin].y) +
(surface->points[*i].z - surface->points[*begin].z) * (surface->points[*i].z - surface->points[*begin].z));
if (dist > max_dist)
continue; /// \note: we neglect points that are outside the specified interval!
// compute bins and increase
int bin_d = (int) floor (nr_subdiv * dist / max_dist);
if (compute_histogram)
{
int bin_a = (int) floor (nr_subdiv * angle / (M_PI/2));
histogram(bin_a, bin_d)++;
}
// update min-max values for distance bins
if (min_max_angle_by_dist[bin_d][0] > angle) min_max_angle_by_dist[bin_d][0] = angle;
if (min_max_angle_by_dist[bin_d][1] < angle) min_max_angle_by_dist[bin_d][1] = angle;
}
// Estimate radius from min and max lines
double Amint_Amin = 0, Amint_d = 0;
double Amaxt_Amax = 0, Amaxt_d = 0;
for (int di=0; di<nr_subdiv; di++)
{
// combute the members of A'*A*r = A'*D
if (min_max_angle_by_dist[di][1] >= 0)
{
double p_min = min_max_angle_by_dist[di][0];
double p_max = min_max_angle_by_dist[di][1];
double f = (di+0.5)*max_dist/nr_subdiv;
Amint_Amin += p_min * p_min;
Amint_d += p_min * f;
Amaxt_Amax += p_max * p_max;
Amaxt_d += p_max * f;
}
}
float min_radius = Amint_Amin == 0 ? plane_radius : std::min (Amint_d/Amint_Amin, plane_radius);
float max_radius = Amaxt_Amax == 0 ? plane_radius : std::min (Amaxt_d/Amaxt_Amax, plane_radius);
// Small correction of the systematic error of the estimation (based on analysis with nr_subdiv_ = 5)
min_radius *= 1.1;
max_radius *= 0.9;
if (min_radius < max_radius)
{
radii.r_min = min_radius;
radii.r_max = max_radius;
}
else
{
radii.r_max = min_radius;
radii.r_min = max_radius;
}
return histogram;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT, typename PointOutT> Eigen::MatrixXf
pcl::computeRSD (boost::shared_ptr<const pcl::PointCloud<PointNT> > &normals,
const std::vector<int> &indices, const std::vector<float> &sqr_dists, double max_dist,
int nr_subdiv, double plane_radius, PointOutT &radii, bool compute_histogram)
{
Eigen::MatrixXf histogram;
// Check if the full histogram has to be saved or not
if (compute_histogram)
histogram = Eigen::MatrixXf::Zero (nr_subdiv, nr_subdiv);
// Initialize minimum and maximum angle values in each distance bin
std::vector<std::vector<double> > min_max_angle_by_dist (nr_subdiv);
min_max_angle_by_dist[0].resize (2);
min_max_angle_by_dist[0][0] = min_max_angle_by_dist[0][1] = 0.0;
for (int di=1; di<nr_subdiv; di++)
{
min_max_angle_by_dist[di].resize (2);
min_max_angle_by_dist[di][0] = +DBL_MAX;
min_max_angle_by_dist[di][1] = -DBL_MAX;
}
// Compute distance by normal angle distribution for points
std::vector<int>::const_iterator i, begin (indices.begin()), end (indices.end());
for(i = begin+1; i != end; ++i)
{
// compute angle between the two lines going through normals (disregard orientation!)
double cosine = normals->points[*i].normal[0] * normals->points[*begin].normal[0] +
normals->points[*i].normal[1] * normals->points[*begin].normal[1] +
normals->points[*i].normal[2] * normals->points[*begin].normal[2];
if (cosine > 1) cosine = 1;
if (cosine < -1) cosine = -1;
double angle = acos (cosine);
if (angle > M_PI/2) angle = M_PI - angle; /// \note: orientation is neglected!
// Compute point to point distance
double dist = sqrt (sqr_dists[i-begin]);
if (dist > max_dist)
continue; /// \note: we neglect points that are outside the specified interval!
// compute bins and increase
int bin_d = (int) floor (nr_subdiv * dist / max_dist);
if (compute_histogram)
{
int bin_a = (int) floor (nr_subdiv * angle / (M_PI/2));
histogram(bin_a, bin_d)++;
}
// update min-max values for distance bins
if (min_max_angle_by_dist[bin_d][0] > angle) min_max_angle_by_dist[bin_d][0] = angle;
if (min_max_angle_by_dist[bin_d][1] < angle) min_max_angle_by_dist[bin_d][1] = angle;
}
// Estimate radius from min and max lines
double Amint_Amin = 0, Amint_d = 0;
double Amaxt_Amax = 0, Amaxt_d = 0;
for (int di=0; di<nr_subdiv; di++)
{
// combute the members of A'*A*r = A'*D
if (min_max_angle_by_dist[di][1] >= 0)
{
double p_min = min_max_angle_by_dist[di][0];
double p_max = min_max_angle_by_dist[di][1];
double f = (di+0.5)*max_dist/nr_subdiv;
Amint_Amin += p_min * p_min;
Amint_d += p_min * f;
Amaxt_Amax += p_max * p_max;
Amaxt_d += p_max * f;
}
}
float min_radius = Amint_Amin == 0 ? plane_radius : std::min (Amint_d/Amint_Amin, plane_radius);
float max_radius = Amaxt_Amax == 0 ? plane_radius : std::min (Amaxt_d/Amaxt_Amax, plane_radius);
// Small correction of the systematic error of the estimation (based on analysis with nr_subdiv_ = 5)
min_radius *= 1.1;
max_radius *= 0.9;
if (min_radius < max_radius)
{
radii.r_min = min_radius;
radii.r_max = max_radius;
}
else
{
radii.r_max = min_radius;
radii.r_min = max_radius;
}
return histogram;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::RSDEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
// Check if search_radius_ was set
if (search_radius_ < 0)
{
PCL_ERROR ("[pcl::%s::computeFeature] A search radius needs to be set!\n", getClassName ().c_str ());
output.width = output.height = 0;
output.points.clear ();
return;
}
// List of indices and corresponding squared distances for a neighborhood
// \note resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices;
std::vector<float> nn_sqr_dists;
// Check if the full histogram has to be saved or not
if (save_histograms_)
{
// Reserve space for the output histogram dataset
histograms_.reset (new std::vector<Eigen::MatrixXf>);
histograms_->reserve (output.points.size ());
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
// Compute and store r_min and r_max in the output cloud
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_sqr_dists);
//histograms_->push_back (computeRSD (surface_, normals_, nn_indices, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], true));
histograms_->push_back (computeRSD (normals_, nn_indices, nn_sqr_dists, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], true));
}
}
else
{
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
// Compute and store r_min and r_max in the output cloud
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_sqr_dists);
//computeRSD (surface_, normals_, nn_indices, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], false);
computeRSD (normals_, nn_indices, nn_sqr_dists, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], false);
}
}
}
#define PCL_INSTANTIATE_RSDEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::RSDEstimation<T,NT,OutT>;
#endif // PCL_FEATURES_IMPL_VFH_H_
<commit_msg>Added check for RSD computation<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * 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.
*
* $Id$
*
*/
#ifndef PCL_FEATURES_IMPL_RSD_H_
#define PCL_FEATURES_IMPL_RSD_H_
#include <cfloat>
#include "pcl/features/rsd.h"
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> Eigen::MatrixXf
pcl::computeRSD (boost::shared_ptr<const pcl::PointCloud<PointInT> > &surface, boost::shared_ptr<const pcl::PointCloud<PointNT> > &normals,
const std::vector<int> &indices, double max_dist,
int nr_subdiv, double plane_radius, PointOutT &radii, bool compute_histogram)
{
// Check if the full histogram has to be saved or not
Eigen::MatrixXf histogram;
if (compute_histogram)
histogram = Eigen::MatrixXf::Zero (nr_subdiv, nr_subdiv);
// Check if enough points are provided or not
if (indices.size () < 2)
{
radii.r_max = 0;
radii.r_min = 0;
return histogram;
}
// Initialize minimum and maximum angle values in each distance bin
std::vector<std::vector<double> > min_max_angle_by_dist (nr_subdiv);
min_max_angle_by_dist[0].resize (2);
min_max_angle_by_dist[0][0] = min_max_angle_by_dist[0][1] = 0.0;
for (int di=1; di<nr_subdiv; di++)
{
min_max_angle_by_dist[di].resize (2);
min_max_angle_by_dist[di][0] = +DBL_MAX;
min_max_angle_by_dist[di][1] = -DBL_MAX;
}
// Compute distance by normal angle distribution for points
std::vector<int>::const_iterator i, begin (indices.begin()), end (indices.end());
for(i = begin+1; i != end; ++i)
{
// compute angle between the two lines going through normals (disregard orientation!)
double cosine = normals->points[*i].normal[0] * normals->points[*begin].normal[0] +
normals->points[*i].normal[1] * normals->points[*begin].normal[1] +
normals->points[*i].normal[2] * normals->points[*begin].normal[2];
if (cosine > 1) cosine = 1;
if (cosine < -1) cosine = -1;
double angle = acos (cosine);
if (angle > M_PI/2) angle = M_PI - angle; /// \note: orientation is neglected!
// Compute point to point distance
double dist = sqrt ((surface->points[*i].x - surface->points[*begin].x) * (surface->points[*i].x - surface->points[*begin].x) +
(surface->points[*i].y - surface->points[*begin].y) * (surface->points[*i].y - surface->points[*begin].y) +
(surface->points[*i].z - surface->points[*begin].z) * (surface->points[*i].z - surface->points[*begin].z));
if (dist > max_dist)
continue; /// \note: we neglect points that are outside the specified interval!
// compute bins and increase
int bin_d = (int) floor (nr_subdiv * dist / max_dist);
if (compute_histogram)
{
int bin_a = std::min (nr_subdiv-1, (int) floor (nr_subdiv * angle / (M_PI/2)));
histogram(bin_a, bin_d)++;
}
// update min-max values for distance bins
if (min_max_angle_by_dist[bin_d][0] > angle) min_max_angle_by_dist[bin_d][0] = angle;
if (min_max_angle_by_dist[bin_d][1] < angle) min_max_angle_by_dist[bin_d][1] = angle;
}
// Estimate radius from min and max lines
double Amint_Amin = 0, Amint_d = 0;
double Amaxt_Amax = 0, Amaxt_d = 0;
for (int di=0; di<nr_subdiv; di++)
{
// combute the members of A'*A*r = A'*D
if (min_max_angle_by_dist[di][1] >= 0)
{
double p_min = min_max_angle_by_dist[di][0];
double p_max = min_max_angle_by_dist[di][1];
double f = (di+0.5)*max_dist/nr_subdiv;
Amint_Amin += p_min * p_min;
Amint_d += p_min * f;
Amaxt_Amax += p_max * p_max;
Amaxt_d += p_max * f;
}
}
float min_radius = Amint_Amin == 0 ? plane_radius : std::min (Amint_d/Amint_Amin, plane_radius);
float max_radius = Amaxt_Amax == 0 ? plane_radius : std::min (Amaxt_d/Amaxt_Amax, plane_radius);
// Small correction of the systematic error of the estimation (based on analysis with nr_subdiv_ = 5)
min_radius *= 1.1;
max_radius *= 0.9;
if (min_radius < max_radius)
{
radii.r_min = min_radius;
radii.r_max = max_radius;
}
else
{
radii.r_max = min_radius;
radii.r_min = max_radius;
}
return histogram;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointNT, typename PointOutT> Eigen::MatrixXf
pcl::computeRSD (boost::shared_ptr<const pcl::PointCloud<PointNT> > &normals,
const std::vector<int> &indices, const std::vector<float> &sqr_dists, double max_dist,
int nr_subdiv, double plane_radius, PointOutT &radii, bool compute_histogram)
{
// Check if the full histogram has to be saved or not
Eigen::MatrixXf histogram;
if (compute_histogram)
histogram = Eigen::MatrixXf::Zero (nr_subdiv, nr_subdiv);
// Check if enough points are provided or not
if (indices.size () < 2)
{
radii.r_max = 0;
radii.r_min = 0;
return histogram;
}
// Initialize minimum and maximum angle values in each distance bin
std::vector<std::vector<double> > min_max_angle_by_dist (nr_subdiv);
min_max_angle_by_dist[0].resize (2);
min_max_angle_by_dist[0][0] = min_max_angle_by_dist[0][1] = 0.0;
for (int di=1; di<nr_subdiv; di++)
{
min_max_angle_by_dist[di].resize (2);
min_max_angle_by_dist[di][0] = +DBL_MAX;
min_max_angle_by_dist[di][1] = -DBL_MAX;
}
// Compute distance by normal angle distribution for points
std::vector<int>::const_iterator i, begin (indices.begin()), end (indices.end());
for(i = begin+1; i != end; ++i)
{
// compute angle between the two lines going through normals (disregard orientation!)
double cosine = normals->points[*i].normal[0] * normals->points[*begin].normal[0] +
normals->points[*i].normal[1] * normals->points[*begin].normal[1] +
normals->points[*i].normal[2] * normals->points[*begin].normal[2];
if (cosine > 1) cosine = 1;
if (cosine < -1) cosine = -1;
double angle = acos (cosine);
if (angle > M_PI/2) angle = M_PI - angle; /// \note: orientation is neglected!
// Compute point to point distance
double dist = sqrt (sqr_dists[i-begin]);
if (dist > max_dist)
continue; /// \note: we neglect points that are outside the specified interval!
// compute bins and increase
int bin_d = (int) floor (nr_subdiv * dist / max_dist);
if (compute_histogram)
{
int bin_a = std::min (nr_subdiv-1, (int) floor (nr_subdiv * angle / (M_PI/2)));
histogram(bin_a, bin_d)++;
}
// update min-max values for distance bins
if (min_max_angle_by_dist[bin_d][0] > angle) min_max_angle_by_dist[bin_d][0] = angle;
if (min_max_angle_by_dist[bin_d][1] < angle) min_max_angle_by_dist[bin_d][1] = angle;
}
// Estimate radius from min and max lines
double Amint_Amin = 0, Amint_d = 0;
double Amaxt_Amax = 0, Amaxt_d = 0;
for (int di=0; di<nr_subdiv; di++)
{
// combute the members of A'*A*r = A'*D
if (min_max_angle_by_dist[di][1] >= 0)
{
double p_min = min_max_angle_by_dist[di][0];
double p_max = min_max_angle_by_dist[di][1];
double f = (di+0.5)*max_dist/nr_subdiv;
Amint_Amin += p_min * p_min;
Amint_d += p_min * f;
Amaxt_Amax += p_max * p_max;
Amaxt_d += p_max * f;
}
}
float min_radius = Amint_Amin == 0 ? plane_radius : std::min (Amint_d/Amint_Amin, plane_radius);
float max_radius = Amaxt_Amax == 0 ? plane_radius : std::min (Amaxt_d/Amaxt_Amax, plane_radius);
// Small correction of the systematic error of the estimation (based on analysis with nr_subdiv_ = 5)
min_radius *= 1.1;
max_radius *= 0.9;
if (min_radius < max_radius)
{
radii.r_min = min_radius;
radii.r_max = max_radius;
}
else
{
radii.r_max = min_radius;
radii.r_min = max_radius;
}
return histogram;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::RSDEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
// Check if search_radius_ was set
if (search_radius_ < 0)
{
PCL_ERROR ("[pcl::%s::computeFeature] A search radius needs to be set!\n", getClassName ().c_str ());
output.width = output.height = 0;
output.points.clear ();
return;
}
// List of indices and corresponding squared distances for a neighborhood
// \note resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices;
std::vector<float> nn_sqr_dists;
// Check if the full histogram has to be saved or not
if (save_histograms_)
{
// Reserve space for the output histogram dataset
histograms_.reset (new std::vector<Eigen::MatrixXf>);
histograms_->reserve (output.points.size ());
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
// Compute and store r_min and r_max in the output cloud
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_sqr_dists);
//histograms_->push_back (computeRSD (surface_, normals_, nn_indices, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], true));
histograms_->push_back (computeRSD (normals_, nn_indices, nn_sqr_dists, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], true));
}
}
else
{
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
// Compute and store r_min and r_max in the output cloud
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_sqr_dists);
//computeRSD (surface_, normals_, nn_indices, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], false);
computeRSD (normals_, nn_indices, nn_sqr_dists, search_radius_, nr_subdiv_, plane_radius_, output.points[idx], false);
}
}
}
#define PCL_INSTANTIATE_RSDEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::RSDEstimation<T,NT,OutT>;
#endif // PCL_FEATURES_IMPL_VFH_H_
<|endoftext|> |
<commit_before>#pragma once
#include <limits>
#include <cassert>
#include "acmacs-base/vector.hh"
#include "acmacs-base/transformation.hh"
#include "acmacs-base/stream.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
class Coordinates : public Vector
{
public:
using Vector::Vector;
Coordinates transform(const Transformation& aTransformation) const
{
const auto [x, y] = aTransformation.transform(operator[](0), operator[](1));
return {x, y};
}
bool not_nan() const
{
return !empty() && std::all_of(begin(), end(), [](double value) -> bool { return ! std::isnan(value); });
}
}; // class Coordinates
inline std::ostream& operator<<(std::ostream& s, const Coordinates& c)
{
stream_internal::write_to_stream(s, c, "[", "]", ", ");
return s;
}
// ----------------------------------------------------------------------
class LayoutInterface
{
public:
LayoutInterface() = default;
LayoutInterface(const LayoutInterface&) = default;
virtual ~LayoutInterface() = default;
LayoutInterface& operator=(const LayoutInterface&) = default;
virtual size_t number_of_points() const noexcept = 0;
virtual size_t number_of_dimensions() const noexcept = 0;
virtual const Coordinates operator[](size_t aPointNo) const = 0;
const Coordinates get(size_t aPointNo) const { return operator[](aPointNo); }
Coordinates& operator[](size_t) = delete; // use set()!
virtual double coordinate(size_t aPointNo, size_t aDimensionNo) const = 0;
virtual std::vector<double> as_flat_vector_double() const = 0;
virtual std::vector<float> as_flat_vector_float() const = 0;
double distance(size_t p1, size_t p2, double no_distance = std::numeric_limits<double>::quiet_NaN()) const
{
const auto c1 = operator[](p1);
const auto c2 = operator[](p2);
return (c1.not_nan() && c2.not_nan()) ? c1.distance(c2) : no_distance;
}
// returns indexes for min points for each dimension and max points for each dimension
virtual std::pair<std::vector<size_t>, std::vector<size_t>> min_max_point_indexes() const;
// returns boundary coordinates (min and max)
virtual std::pair<Coordinates, Coordinates> boundaries() const;
virtual LayoutInterface* transform(const Transformation& aTransformation) const;
virtual Coordinates centroid() const;
virtual void set(size_t aPointNo, const Coordinates& aCoordinates) = 0;
virtual void set(size_t point_no, size_t dimension_no, double value) = 0;
}; // class LayoutInterface
inline std::ostream& operator<<(std::ostream& s, const LayoutInterface& aLayout)
{
s << "Layout [";
for (size_t no = 0; no < aLayout.number_of_points(); ++no)
s << aLayout[no] << ' ';
s << ']';
return s;
}
// ----------------------------------------------------------------------
class Layout : public virtual LayoutInterface, public std::vector<double>
{
public:
Layout() = default;
Layout(size_t aNumberOfPoints, size_t aNumberOfDimensions)
: std::vector<double>(aNumberOfPoints * aNumberOfDimensions, std::numeric_limits<double>::quiet_NaN()),
number_of_dimensions_{aNumberOfDimensions}
{}
Layout(const Layout&) = default;
Layout(const LayoutInterface& aSource) : std::vector<double>(aSource.as_flat_vector_double()), number_of_dimensions_{aSource.number_of_dimensions()} {}
Layout(const LayoutInterface& aSource, const std::vector<size_t>& aIndexes); // make layout by subsetting source
Layout& operator=(const Layout&) = default;
size_t number_of_points() const noexcept override { return size() / number_of_dimensions_; }
size_t number_of_dimensions() const noexcept override { return number_of_dimensions_; }
void change_number_of_dimensions(size_t num_dim)
{
// assert(num_dim <= number_of_dimensions_);
resize(number_of_points() * num_dim);
number_of_dimensions_ = num_dim;
}
const Coordinates operator[](size_t aPointNo) const override
{
using diff_t = decltype(begin())::difference_type;
return {begin() + static_cast<diff_t>(aPointNo * number_of_dimensions_), begin() + static_cast<diff_t>((aPointNo + 1) * number_of_dimensions_)};
}
double coordinate(size_t aPointNo, size_t aDimensionNo) const override { return at(aPointNo * number_of_dimensions_ + aDimensionNo); }
std::vector<double> as_flat_vector_double() const override { return *this; }
std::vector<float> as_flat_vector_float() const override { return {begin(), end()}; }
void set(size_t aPointNo, const Coordinates& aCoordinates) override
{
std::copy(aCoordinates.begin(), aCoordinates.end(), begin() + static_cast<decltype(begin())::difference_type>(aPointNo * number_of_dimensions()));
}
virtual void set(size_t point_no, size_t dimension_no, double value) override { std::vector<double>::operator[](point_no * number_of_dimensions() + dimension_no) = value; }
private:
size_t number_of_dimensions_;
}; // class Layout
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>allow increasing number of dimensions for layout<commit_after>#pragma once
#include <limits>
#include <cassert>
#include "acmacs-base/vector.hh"
#include "acmacs-base/transformation.hh"
#include "acmacs-base/stream.hh"
// ----------------------------------------------------------------------
namespace acmacs
{
class Coordinates : public Vector
{
public:
using Vector::Vector;
Coordinates transform(const Transformation& aTransformation) const
{
const auto [x, y] = aTransformation.transform(operator[](0), operator[](1));
return {x, y};
}
bool not_nan() const
{
return !empty() && std::all_of(begin(), end(), [](double value) -> bool { return ! std::isnan(value); });
}
}; // class Coordinates
inline std::ostream& operator<<(std::ostream& s, const Coordinates& c)
{
stream_internal::write_to_stream(s, c, "[", "]", ", ");
return s;
}
// ----------------------------------------------------------------------
class LayoutInterface
{
public:
LayoutInterface() = default;
LayoutInterface(const LayoutInterface&) = default;
virtual ~LayoutInterface() = default;
LayoutInterface& operator=(const LayoutInterface&) = default;
virtual size_t number_of_points() const noexcept = 0;
virtual size_t number_of_dimensions() const noexcept = 0;
virtual const Coordinates operator[](size_t aPointNo) const = 0;
const Coordinates get(size_t aPointNo) const { return operator[](aPointNo); }
Coordinates& operator[](size_t) = delete; // use set()!
virtual double coordinate(size_t aPointNo, size_t aDimensionNo) const = 0;
virtual std::vector<double> as_flat_vector_double() const = 0;
virtual std::vector<float> as_flat_vector_float() const = 0;
double distance(size_t p1, size_t p2, double no_distance = std::numeric_limits<double>::quiet_NaN()) const
{
const auto c1 = operator[](p1);
const auto c2 = operator[](p2);
return (c1.not_nan() && c2.not_nan()) ? c1.distance(c2) : no_distance;
}
// returns indexes for min points for each dimension and max points for each dimension
virtual std::pair<std::vector<size_t>, std::vector<size_t>> min_max_point_indexes() const;
// returns boundary coordinates (min and max)
virtual std::pair<Coordinates, Coordinates> boundaries() const;
virtual LayoutInterface* transform(const Transformation& aTransformation) const;
virtual Coordinates centroid() const;
virtual void set(size_t aPointNo, const Coordinates& aCoordinates) = 0;
virtual void set(size_t point_no, size_t dimension_no, double value) = 0;
}; // class LayoutInterface
inline std::ostream& operator<<(std::ostream& s, const LayoutInterface& aLayout)
{
s << "Layout [";
for (size_t no = 0; no < aLayout.number_of_points(); ++no)
s << aLayout[no] << ' ';
s << ']';
return s;
}
// ----------------------------------------------------------------------
class Layout : public virtual LayoutInterface, public std::vector<double>
{
public:
Layout() = default;
Layout(size_t aNumberOfPoints, size_t aNumberOfDimensions)
: std::vector<double>(aNumberOfPoints * aNumberOfDimensions, std::numeric_limits<double>::quiet_NaN()),
number_of_dimensions_{aNumberOfDimensions}
{}
Layout(const Layout&) = default;
Layout(const LayoutInterface& aSource) : std::vector<double>(aSource.as_flat_vector_double()), number_of_dimensions_{aSource.number_of_dimensions()} {}
Layout(const LayoutInterface& aSource, const std::vector<size_t>& aIndexes); // make layout by subsetting source
Layout& operator=(const Layout&) = default;
size_t number_of_points() const noexcept override { return size() / number_of_dimensions_; }
size_t number_of_dimensions() const noexcept override { return number_of_dimensions_; }
void change_number_of_dimensions(size_t num_dim)
{
if (num_dim >= number_of_dimensions_)
std::cerr << "WARNING: Layout::change_number_of_dimensions: " << number_of_dimensions_ << " --> " << num_dim << '\n';
resize(number_of_points() * num_dim);
number_of_dimensions_ = num_dim;
}
const Coordinates operator[](size_t aPointNo) const override
{
using diff_t = decltype(begin())::difference_type;
return {begin() + static_cast<diff_t>(aPointNo * number_of_dimensions_), begin() + static_cast<diff_t>((aPointNo + 1) * number_of_dimensions_)};
}
double coordinate(size_t aPointNo, size_t aDimensionNo) const override { return at(aPointNo * number_of_dimensions_ + aDimensionNo); }
std::vector<double> as_flat_vector_double() const override { return *this; }
std::vector<float> as_flat_vector_float() const override { return {begin(), end()}; }
void set(size_t aPointNo, const Coordinates& aCoordinates) override
{
std::copy(aCoordinates.begin(), aCoordinates.end(), begin() + static_cast<decltype(begin())::difference_type>(aPointNo * number_of_dimensions()));
}
virtual void set(size_t point_no, size_t dimension_no, double value) override { std::vector<double>::operator[](point_no * number_of_dimensions() + dimension_no) = value; }
private:
size_t number_of_dimensions_;
}; // class Layout
} // namespace acmacs
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <TVectorD.h>
#include <TF1.h>
#include "X.h"
using namespace GEFICA;
//______________________________________________________________________________
// Create grid for 1-D field calculation.
// begin_macro
// planar1d.C
// end_macro
ClassImp(X)
X::X(int nx) : TObject(), MaxIterations(100000), Csor(1), Precision(1e-7),
fIsFixed(0), fE1(0), fPotential(0), fC1(0), fDistanceToNext(0), fDistanceToPrevious(0), fImpurity(0)
{
//claim a 1D field with nx grisd
n=nx;
n1=nx;
floaded=false;
if (n<10) { n=11; n1=11; }
fE1=new double[n];
fC1=new double[n];
fPotential=new double[n];
fIsFixed=new bool[n];
fDistanceToNext=new double[n];
fDistanceToPrevious=new double[n];
fImpurity=new double[n];
}
X::~X()
{
if (fE1) delete[] fE1;
if (fPotential) delete[] fPotential;
if (fC1) delete[] fC1;
if (fDistanceToNext) delete[] fDistanceToNext;
if (fDistanceToPrevious) delete[] fDistanceToPrevious;
if (fIsFixed) delete[] fIsFixed;
if (fImpurity) delete[] fImpurity;
}
bool X::Analyic()
{
// Analyic calculation
cout<<"no method can use"<<endl;
return false;
}
void X::SetStepLength(double steplength)
{
//set field step length
for (int i=n;i-->0;) {
fIsFixed[i]=false;
fE1[i]=0;
fC1[i]=i*steplength;
fPotential[i]=0;
fDistanceToNext[i]=steplength;
fDistanceToPrevious[i]=steplength;
fImpurity[i]=0;
}
}
void X::SetVoltage(double anode_voltage, double cathode_voltage)
{
fIsFixed[0]=true;
fIsFixed[n-1]=true;
double slope = (cathode_voltage-anode_voltage)/(n-1);
for (int i=0; i<n; i++) {
fPotential[i]=anode_voltage+slope*i;
}
}
bool X::CalculateField(EMethod method)
{
//do calculate
floaded=true;
if (method==kAnalytic) return Analyic();
int cnt=0;
while (cnt++<MaxIterations) {
double XUpSum=0;
double XDownSum=0;
for (int i=1;i<n-1;i++) {
double old=fPotential[i];
if (method==kSOR4) SOR4(i);
else SOR2(i,0);
if(old>0)XDownSum+=old;
else XDownSum-=old;
if(fPotential[i]-old>0)XUpSum+=(fPotential[i]-old);
else XUpSum+=-(fPotential[i]-old);
}
if(cnt%1000==0)
cout<<cnt<<" "<<XUpSum/XDownSum<<" down: "<<XDownSum<<", up: "<<XUpSum<<endl;
if (XUpSum/XDownSum<Precision){
return true;
}
}
return false;
}
void X::SOR2(int idx,bool elec)
{
// 2nd-order Runge-Kutta Successive Over-Relaxation
if (fIsFixed[idx])return ;
double density=fImpurity[idx]*1.6e-19;
double h2=fDistanceToPrevious[idx];
double h3=fDistanceToNext[idx];
double tmp=-density/epsilon*h2*h3/2+(h3*fPotential[idx-1]+h2*fPotential[idx+1])/(h2+h3);
// over-relaxation if Csor>1
fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
if(elec)fE1[idx]=(fPotential[idx+1]-fPotential[idx-1])/(h2+h3);
}
int X::FindIdx(double tarx,int begin,int end)
{
//search using binary search
if (begin>=end)return begin;
int mid=(begin+end)/2;
if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid);
else return FindIdx(tarx,mid+1,end);
}
double X::GetData(double tarx,int thing)
{
// ask thingwith number: 1:Ex 2:f 0:Impurty
int idx=FindIdx(tarx,0,n-1);
if (idx==n)
{
switch (thing)
{
case 0:return fImpurity[idx];
case 2:return fE1[idx];
case 1:return fPotential[idx];
}
}
double ab=(tarx-fC1[idx])/fDistanceToNext[idx];
double aa=1-ab;
switch(thing)
{
case 2:return fE1[idx]*ab+fE1[idx+1]*aa;
case 1:return fPotential[idx]*ab+fC1[idx+1]*aa;
case 0:return fImpurity[idx]*ab+fImpurity[idx+1]*aa;
}
return -1;
}
void X::SaveField(const char * fout)
{
TFile * file=new TFile(fout,"recreate","data");
TTree * tree=new TTree("t","1D");
TVectorD v(10);
v[7]=(double)n1;
v[8]=1;;
v[9]=1;
v[0]=(double)MaxIterations;
v[1]=(double)n;
v[2]=Csor;
v.Write("v");
bool fIsFixeds;
double E1s,C1s,Ps,StepNexts,StepBefores,impuritys;
tree->Branch("e1",&E1s,"e1/D"); // Electric X in x
tree->Branch("c1",&C1s,"c1/D"); // persition in x
tree->Branch("p",&Ps,"p/D"); // electric potential
tree->Branch("sn",&StepNexts,"StepNext/D"); // Step length to next point in x
tree->Branch("sb",&StepBefores,"Step)Before/D"); // Step length to before point in x
tree->Branch("ib",&fIsFixeds,"fIsFixed/O"); // check is initial point
tree->Branch("im",&impuritys,"impurity/D"); // Impurity
for(int i=0;i<n;i++) {
impuritys=fImpurity[i];
E1s=fE1[i];
C1s=fC1[i];
Ps=fPotential[i];
StepNexts=fDistanceToNext[i];
StepBefores=fDistanceToPrevious[i];
tree->Fill();
}
file->Write();
file->Close();
delete file;
}
void X::LoadField(const char * fin)
{
floaded=true;
TFile *file=new TFile(fin);
TVectorD *v1=(TVectorD*)file->Get("v");
double * v=v1->GetMatrixArray();
n1 =(int) v[7];
MaxIterations =(int) v[0];
n =(int) v[1];
Csor = v[2];
TChain *t =new TChain("t");
t->Add(fin);
bool IsFixed;
double E1,C1,fP,fStepNext,fStepBefore,fimpurity;
t->SetBranchAddress("e1",&E1);
t->SetBranchAddress("c1",&C1);
t->SetBranchAddress("p",&fP);
t->SetBranchAddress("sn",&fStepNext);
t->SetBranchAddress("sb",&fStepBefore);
t->SetBranchAddress("e1",&fE1);
t->SetBranchAddress("if",&IsFixed);
t->SetBranchAddress("im",&fimpurity);
fE1=new double[n];
fC1=new double[n];
fPotential=new double[n];
fIsFixed=new bool[n];
fDistanceToNext=new double[n];
fDistanceToPrevious=new double[n];
fImpurity=new double[n];
for (int i=0;i<n;i++) {
t->GetEntry(i);
fE1[i]=E1;
fC1[i]=C1;
fPotential[i]=fP;
fIsFixed[i]=fIsFixed;
fDistanceToNext[i]=fStepNext;
fDistanceToPrevious[i]=fStepBefore;
fImpurity[i]=fimpurity;
}
file->Close();
delete file;
for(int idx=0;idx-->n;)SOR2(idx,1);
}
void X::SetImpurity(double density)
{
for(int i=n;i-->0;) fImpurity[i]=density;
}
void X::SetImpurity(TF1 * Im)
{
for(int i=n;i-->0;) {
fImpurity[i]=Im->Eval((double)fC1[i]);
}
}
<commit_msg>some common<commit_after>#include <iostream>
using namespace std;
#include <TFile.h>
#include <TTree.h>
#include <TChain.h>
#include <TVectorD.h>
#include <TF1.h>
#include "X.h"
using namespace GEFICA;
//______________________________________________________________________________
// Create grid for 1-D field calculation.
// it is using success Over-Relaxation to calculate the grid. it will have some error compare with actual data but should be close. For 1D field it also have analist method to compare
// begin_macro
// planar1d.C
// end_macro
ClassImp(X)
X::X(int nx) : TObject(), MaxIterations(100000), Csor(1), Precision(1e-7),
fIsFixed(0), fE1(0), fPotential(0), fC1(0), fDistanceToNext(0), fDistanceToPrevious(0), fImpurity(0)
{
//claim a 1D field with nx grisd
n=nx;
n1=nx;
floaded=false;
if (n<10) { n=11; n1=11; }
fE1=new double[n];
fC1=new double[n];
fPotential=new double[n];
fIsFixed=new bool[n];
fDistanceToNext=new double[n];
fDistanceToPrevious=new double[n];
fImpurity=new double[n];
}
X::~X()
{
if (fE1) delete[] fE1;
if (fPotential) delete[] fPotential;
if (fC1) delete[] fC1;
if (fDistanceToNext) delete[] fDistanceToNext;
if (fDistanceToPrevious) delete[] fDistanceToPrevious;
if (fIsFixed) delete[] fIsFixed;
if (fImpurity) delete[] fImpurity;
}
bool X::Analyic()
{
// Analyic calculation
cout<<"no method can use"<<endl;
return false;
}
void X::SetStepLength(double steplength)
{
//set field step length
for (int i=n;i-->0;) {
fIsFixed[i]=false;
fE1[i]=0;
fC1[i]=i*steplength;
fPotential[i]=0;
fDistanceToNext[i]=steplength;
fDistanceToPrevious[i]=steplength;
fImpurity[i]=0;
}
}
void X::SetVoltage(double anode_voltage, double cathode_voltage)
{
fIsFixed[0]=true;
fIsFixed[n-1]=true;
double slope = (cathode_voltage-anode_voltage)/(n-1);
for (int i=0; i<n; i++) {
fPotential[i]=anode_voltage+slope*i;
}
}
bool X::CalculateField(EMethod method)
{
//do calculate
floaded=true;
if (method==kAnalytic) return Analyic();
int cnt=0;
while (cnt++<MaxIterations) {
double XUpSum=0;
double XDownSum=0;
for (int i=1;i<n-1;i++) {
double old=fPotential[i];
if (method==kSOR4) SOR4(i);
else SOR2(i,0);
if(old>0)XDownSum+=old;
else XDownSum-=old;
if(fPotential[i]-old>0)XUpSum+=(fPotential[i]-old);
else XUpSum+=-(fPotential[i]-old);
}
if(cnt%1000==0)
cout<<cnt<<" "<<XUpSum/XDownSum<<" down: "<<XDownSum<<", up: "<<XUpSum<<endl;
if (XUpSum/XDownSum<Precision){
return true;
}
}
return false;
}
void X::SOR2(int idx,bool elec)
{
// 2nd-order Runge-Kutta Successive Over-Relaxation
if (fIsFixed[idx])return ;
double density=fImpurity[idx]*1.6e-19;
double h2=fDistanceToPrevious[idx];
double h3=fDistanceToNext[idx];
double tmp=-density/epsilon*h2*h3/2+(h3*fPotential[idx-1]+h2*fPotential[idx+1])/(h2+h3);
// over-relaxation if Csor>1
fPotential[idx]=Csor*(tmp-fPotential[idx])+fPotential[idx];
if(elec)fE1[idx]=(fPotential[idx+1]-fPotential[idx-1])/(h2+h3);
}
int X::FindIdx(double tarx,int begin,int end)
{
//search using binary search
if (begin>=end)return begin;
int mid=(begin+end)/2;
if(fC1[mid]>=tarx)return FindIdx(tarx,begin,mid);
else return FindIdx(tarx,mid+1,end);
}
double X::GetData(double tarx,int thing)
{
// ask thingwith number: 1:Ex 2:f 0:Impurty
int idx=FindIdx(tarx,0,n-1);
if (idx==n)
{
switch (thing)
{
case 0:return fImpurity[idx];
case 2:return fE1[idx];
case 1:return fPotential[idx];
}
}
double ab=(tarx-fC1[idx])/fDistanceToNext[idx];
double aa=1-ab;
switch(thing)
{
case 2:return fE1[idx]*ab+fE1[idx+1]*aa;
case 1:return fPotential[idx]*ab+fC1[idx+1]*aa;
case 0:return fImpurity[idx]*ab+fImpurity[idx+1]*aa;
}
return -1;
}
void X::SaveField(const char * fout)
{
TFile * file=new TFile(fout,"recreate","data");
TTree * tree=new TTree("t","1D");
TVectorD v(10);
v[7]=(double)n1;
v[8]=1;;
v[9]=1;
v[0]=(double)MaxIterations;
v[1]=(double)n;
v[2]=Csor;
v.Write("v");
bool fIsFixeds;
double E1s,C1s,Ps,StepNexts,StepBefores,impuritys;
tree->Branch("e1",&E1s,"e1/D"); // Electric X in x
tree->Branch("c1",&C1s,"c1/D"); // persition in x
tree->Branch("p",&Ps,"p/D"); // electric potential
tree->Branch("sn",&StepNexts,"StepNext/D"); // Step length to next point in x
tree->Branch("sb",&StepBefores,"Step)Before/D"); // Step length to before point in x
tree->Branch("ib",&fIsFixeds,"fIsFixed/O"); // check is initial point
tree->Branch("im",&impuritys,"impurity/D"); // Impurity
for(int i=0;i<n;i++) {
impuritys=fImpurity[i];
E1s=fE1[i];
C1s=fC1[i];
Ps=fPotential[i];
StepNexts=fDistanceToNext[i];
StepBefores=fDistanceToPrevious[i];
tree->Fill();
}
file->Write();
file->Close();
delete file;
}
void X::LoadField(const char * fin)
{
floaded=true;
TFile *file=new TFile(fin);
TVectorD *v1=(TVectorD*)file->Get("v");
double * v=v1->GetMatrixArray();
n1 =(int) v[7];
MaxIterations =(int) v[0];
n =(int) v[1];
Csor = v[2];
TChain *t =new TChain("t");
t->Add(fin);
bool IsFixed;
double E1,C1,fP,fStepNext,fStepBefore,fimpurity;
t->SetBranchAddress("e1",&E1);
t->SetBranchAddress("c1",&C1);
t->SetBranchAddress("p",&fP);
t->SetBranchAddress("sn",&fStepNext);
t->SetBranchAddress("sb",&fStepBefore);
t->SetBranchAddress("e1",&fE1);
t->SetBranchAddress("if",&IsFixed);
t->SetBranchAddress("im",&fimpurity);
fE1=new double[n];
fC1=new double[n];
fPotential=new double[n];
fIsFixed=new bool[n];
fDistanceToNext=new double[n];
fDistanceToPrevious=new double[n];
fImpurity=new double[n];
for (int i=0;i<n;i++) {
t->GetEntry(i);
fE1[i]=E1;
fC1[i]=C1;
fPotential[i]=fP;
fIsFixed[i]=fIsFixed;
fDistanceToNext[i]=fStepNext;
fDistanceToPrevious[i]=fStepBefore;
fImpurity[i]=fimpurity;
}
file->Close();
delete file;
for(int idx=0;idx-->n;)SOR2(idx,1);
}
void X::SetImpurity(double density)
{
for(int i=n;i-->0;) fImpurity[i]=density;
}
void X::SetImpurity(TF1 * Im)
{
for(int i=n;i-->0;) {
fImpurity[i]=Im->Eval((double)fC1[i]);
}
}
<|endoftext|> |
<commit_before>#include "sync_client.h"
<commit_msg>[sync] Fix pin_sim.cc.<commit_after>// Jonathan Eastep, Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.
//
#include <iostream>
#include <assert.h>
#include <set>
#include "pin.H"
#include "utils.h"
#include "bit_vector.h"
#include "config.h"
#include "chip.h"
#include "cache.h"
#include "ocache.h"
#include "perfmdl.h"
#include "knobs.h"
#include "mcp.h"
#include "sync_client.h"
Chip *g_chip = NULL;
Config *g_config = NULL;
MCP *g_MCP = NULL;
//FIXME
//PIN_LOCK g_lock1;
//PIN_LOCK g_lock2;
INT32 usage()
{
cerr << "This tool implements a multicore simulator." << endl;
cerr << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* For instrumentation / modeling */
/* ===================================================================== */
VOID runModels(ADDRINT dcache_ld_addr, ADDRINT dcache_ld_addr2, UINT32 dcache_ld_size,
ADDRINT dcache_st_addr, UINT32 dcache_st_size,
PerfModelIntervalStat* *stats,
REG *reads, UINT32 num_reads, REG *writes, UINT32 num_writes,
bool do_network_modeling, bool do_icache_modeling,
bool do_dcache_read_modeling, bool is_dual_read,
bool do_dcache_write_modeling, bool do_bpred_modeling, bool do_perf_modeling,
bool check_scoreboard)
{
//cout << "parent = " << stats->parent_routine << endl;
int rank;
chipRank(&rank);
// This must be consistent with the behavior of
// insertInstructionModelingCall.
// Trying to prevent using NULL stats. This happens when
// instrumenting portions of the main thread.
bool skip_modeling = (rank < 0) ||
((check_scoreboard || do_perf_modeling || do_icache_modeling) && stats == NULL);
if (skip_modeling)
return;
assert( rank >= 0 && rank < g_chip->getNumModules() );
assert( !do_network_modeling );
assert( !do_bpred_modeling );
// JME: think this was an error; want some other model on if icache modeling is on
// assert( !(!do_icache_modeling && (do_network_modeling ||
// do_dcache_read_modeling || do_dcache_write_modeling ||
// do_bpred_modeling || do_perf_modeling)) );
// no longer needed since we guarantee icache model will run at basic block boundary
//assert( !do_icache_modeling || (do_network_modeling ||
// do_dcache_read_modeling || do_dcache_write_modeling ||
// do_bpred_modeling || do_perf_modeling) );
if ( do_icache_modeling )
{
for (UINT32 i = 0; i < (stats[rank]->inst_trace.size()); i++)
{
// first = PC, second = size
bool i_hit = icacheRunLoadModel(rank,
stats[rank]->inst_trace[i].first,
stats[rank]->inst_trace[i].second);
if ( do_perf_modeling ) {
perfModelLogICacheLoadAccess(rank, stats[rank], i_hit);
}
}
}
// this check must go before everything but the icache check
assert( !check_scoreboard || do_perf_modeling );
if ( check_scoreboard )
{
// it's not possible to delay the evaluation of the performance impact for these.
// get the cycle counter up to date then account for dependency stalls
perfModelRun(rank, stats[rank], reads, num_reads);
}
if ( do_dcache_read_modeling )
{
// it's not possible to delay the evaluation of the performance impact for these.
// get cycle count up to date so time stamp for when miss is ready is correct
bool d_hit = dcacheRunLoadModel(rank, dcache_ld_addr, dcache_ld_size);
if ( do_perf_modeling ) {
perfModelRun(rank, stats[rank], d_hit, writes, num_writes);
}
if ( is_dual_read ) {
bool d_hit2 = dcacheRunLoadModel(rank, dcache_ld_addr2, dcache_ld_size);
if ( do_perf_modeling ) {
perfModelRun(rank, stats[rank], d_hit2, writes, num_writes);
}
}
}
else
{
assert(dcache_ld_addr == (ADDRINT) NULL);
assert(dcache_ld_addr2 == (ADDRINT) NULL);
assert(dcache_ld_size == 0);
}
if ( do_dcache_write_modeling )
{
bool d_hit = dcacheRunStoreModel(rank, dcache_st_addr, dcache_st_size);
if ( do_perf_modeling )
{
perfModelLogDCacheStoreAccess(rank, stats[rank], d_hit);
}
}
else
{
assert(dcache_st_addr == (ADDRINT) NULL);
assert(dcache_st_size == 0);
}
// this should probably go last
if ( do_perf_modeling )
{
perfModelRun(rank, stats[rank]);
}
}
bool insertInstructionModelingCall(const string& rtn_name, const INS& start_ins,
const INS& ins, bool is_rtn_ins_head, bool is_bbl_ins_head,
bool is_bbl_ins_tail, bool is_potential_load_use)
{
// added constraint that perf model must be on
bool check_scoreboard = g_knob_enable_performance_modeling &&
g_knob_enable_dcache_modeling &&
!g_knob_dcache_ignore_loads &&
is_potential_load_use;
//FIXME: check for API routine
bool do_network_modeling = g_knob_enable_network_modeling && is_rtn_ins_head;
bool do_dcache_read_modeling = g_knob_enable_dcache_modeling && !g_knob_dcache_ignore_loads &&
INS_IsMemoryRead(ins);
bool do_dcache_write_modeling = g_knob_enable_dcache_modeling && !g_knob_dcache_ignore_stores &&
INS_IsMemoryWrite(ins);
bool do_bpred_modeling = g_knob_enable_bpred_modeling && INS_IsBranchOrCall(ins);
//TODO: if we run on multiple machines we need shared memory
//TODO: if we run on multiple machines we need syscall_modeling
// If we are doing any other type of modeling then we need to do icache modeling
bool do_icache_modeling = g_knob_enable_icache_modeling &&
( do_network_modeling || do_dcache_read_modeling ||
do_dcache_write_modeling || do_bpred_modeling || is_bbl_ins_tail ||
check_scoreboard );
bool do_perf_modeling = g_knob_enable_performance_modeling &&
( do_network_modeling || do_dcache_read_modeling ||
do_dcache_write_modeling || do_icache_modeling ||
do_bpred_modeling || is_bbl_ins_tail || check_scoreboard );
// Exit early if we aren't modeling anything
if ( !do_network_modeling && !do_icache_modeling && !do_dcache_read_modeling &&
!do_dcache_write_modeling && !do_bpred_modeling && !do_perf_modeling)
{
return false;
}
assert( !do_network_modeling );
assert( !do_bpred_modeling );
//this flag may or may not get used
bool is_dual_read = INS_HasMemoryRead2(ins);
PerfModelIntervalStat* *stats;
INS end_ins = INS_Next(ins);
// stats also needs to get allocated if icache modeling is turned on
stats = (do_perf_modeling || do_icache_modeling || check_scoreboard) ?
perfModelAnalyzeInterval(rtn_name, start_ins, end_ins) :
NULL;
// Build a list of read registers if relevant
UINT32 num_reads = 0;
REG *reads = NULL;
if ( g_knob_enable_performance_modeling )
{
num_reads = INS_MaxNumRRegs(ins);
reads = new REG[num_reads];
for (UINT32 i = 0; i < num_reads; i++) {
reads[i] = INS_RegR(ins, i);
}
}
// Build a list of write registers if relevant
UINT32 num_writes = 0;
REG *writes = NULL;
if ( g_knob_enable_performance_modeling )
{
num_writes = INS_MaxNumWRegs(ins);
writes = new REG[num_writes];
for (UINT32 i = 0; i < num_writes; i++) {
writes[i] = INS_RegW(ins, i);
}
}
//for building the arguments to the function which dispatches calls to the various modelers
IARGLIST args = IARGLIST_Alloc();
// Properly add the associated addresses for the argument call
if(do_dcache_read_modeling)
{
IARGLIST_AddArguments(args, IARG_MEMORYREAD_EA, IARG_END);
// If it's a dual read then we need the read2 ea otherwise, null
if(is_dual_read)
IARGLIST_AddArguments(args, IARG_MEMORYREAD2_EA, IARG_END);
else
IARGLIST_AddArguments(args, IARG_ADDRINT, (ADDRINT) NULL, IARG_END);
IARGLIST_AddArguments(args, IARG_MEMORYREAD_SIZE, IARG_END);
}
else
{
IARGLIST_AddArguments(args, IARG_ADDRINT, (ADDRINT) NULL, IARG_ADDRINT, (ADDRINT) NULL, IARG_UINT32, 0, IARG_END);
}
// Do this after those first three
if(do_dcache_write_modeling)
IARGLIST_AddArguments(args,IARG_MEMORYWRITE_EA, IARG_MEMORYWRITE_SIZE, IARG_END);
else
IARGLIST_AddArguments(args,IARG_ADDRINT, (ADDRINT) NULL, IARG_UINT32, 0, IARG_END);
// Now pass on our values for the appropriate models
IARGLIST_AddArguments(args,
// perf modeling
IARG_PTR, (VOID *) stats,
IARG_PTR, (VOID *) reads, IARG_UINT32, num_reads,
IARG_PTR, (VOID *) writes, IARG_UINT32, num_writes,
// model-enable flags
IARG_BOOL, do_network_modeling, IARG_BOOL, do_icache_modeling,
IARG_BOOL, do_dcache_read_modeling, IARG_BOOL, is_dual_read,
IARG_BOOL, do_dcache_write_modeling, IARG_BOOL, do_bpred_modeling,
IARG_BOOL, do_perf_modeling, IARG_BOOL, check_scoreboard,
IARG_END);
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR) runModels, IARG_IARGLIST, args, IARG_END);
IARGLIST_Free(args);
return true;
}
void getPotentialLoadFirstUses(const RTN& rtn, set<INS>& ins_uses)
{
//FIXME: does not currently account for load registers live across rtn boundaries
UINT32 rtn_ins_count = 0;
// find the write registers not consumed within the basic block for instructs which read mem
BitVector bbl_dest_regs(LEVEL_BASE::REG_LAST);
BitVector dest_regs(LEVEL_BASE::REG_LAST);
for (BBL bbl = RTN_BblHead(rtn); BBL_Valid(bbl); bbl = BBL_Next(bbl)) {
rtn_ins_count += BBL_NumIns(bbl);
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) {
// remove from list of outstanding regs if is a use
for (UINT32 i = 0; i < INS_MaxNumRRegs(ins); i++)
{
REG r = INS_RegR(ins, i);
assert(0 <= r && r < LEVEL_BASE::REG_LAST);
if ( bbl_dest_regs.at(r) ) {
bbl_dest_regs.clear(r);
ins_uses.insert( ins );
}
}
if ( !INS_IsMemoryRead(ins) ) {
// remove from list of outstanding regs if is overwrite
for (UINT32 i = 0; i < INS_MaxNumWRegs(ins); i++)
{
REG r = INS_RegW(ins, i);
bbl_dest_regs.clear(r);
}
}
else
{
// add to list if writing some function of memory read; remove other writes
// FIXME: not all r will be dependent on memory; need to remove those
for (UINT32 i = 0; i < INS_MaxNumWRegs(ins); i++)
{
REG r = INS_RegW(ins, i);
bbl_dest_regs.set(r);
}
}
}
dest_regs.set( bbl_dest_regs );
}
// find the instructs that source these registers
for (BBL bbl = RTN_BblHead(rtn); BBL_Valid(bbl); bbl = BBL_Next(bbl)) {
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) {
for (UINT32 i = 0; i < INS_MaxNumRRegs(ins); i++)
{
REG r = INS_RegR(ins, i);
assert(0 <= r && r < LEVEL_BASE::REG_LAST);
if ( dest_regs.at(r) )
ins_uses.insert(ins);
}
}
}
#if 0
cout << "Routine " << RTN_Name(rtn) << endl;
cout << " instrumented " << ins_uses.size() << " of " << rtn_ins_count << endl;
for (set<INS>::iterator it = ins_uses.begin(); it != ins_uses.end(); it++) {
cout << " " << INS_Disassemble( *it ) << endl;
}
#endif
}
/* ===================================================================== */
bool replaceUserAPIFunction(RTN& rtn, string& name)
{
AFUNPTR msg_ptr = NULL;
PROTO proto = NULL;
if(name == "CAPI_Initialize")
{
msg_ptr = AFUNPTR(chipInit);
}
else if(name == "CAPI_rank")
{
msg_ptr = AFUNPTR(commRank);
}
else if(name == "CAPI_message_send_w")
{
msg_ptr = AFUNPTR(chipSendW);
}
else if(name == "CAPI_message_receive_w")
{
msg_ptr = AFUNPTR(chipRecvW);
}
else if(name == "runMCP")
{
msg_ptr = AFUNPTR(MCPRun);
}
else if(name == "finishMCP")
{
msg_ptr = AFUNPTR(MCPFinish);
}
else if(name == "mutexInit")
{
msg_ptr = AFUNPTR(SimMutexInit);
}
else if(name == "mutexLock")
{
msg_ptr = AFUNPTR(SimMutexLock);
}
else if(name == "mutexUnlock")
{
msg_ptr = AFUNPTR(SimMutexUnlock);
}
if ( (msg_ptr == AFUNPTR(chipInit))
|| (msg_ptr == AFUNPTR(commRank))
|| (msg_ptr == AFUNPTR(SimMutexInit))
|| (msg_ptr == AFUNPTR(SimMutexLock))
|| (msg_ptr == AFUNPTR(SimMutexUnlock))
)
{
proto = PROTO_Allocate(PIN_PARG(CAPI_return_t),
CALLINGSTD_DEFAULT,
name.c_str(),
PIN_PARG(int*),
PIN_PARG_END() );
RTN_ReplaceSignature(rtn, msg_ptr,
IARG_PROTOTYPE, proto,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_END);
//RTN_Close(rtn);
PROTO_Free(proto);
return true;
}
else if ( (msg_ptr == AFUNPTR(chipSendW)) || (msg_ptr == AFUNPTR(chipRecvW) ) )
{
proto = PROTO_Allocate(PIN_PARG(CAPI_return_t),
CALLINGSTD_DEFAULT,
name.c_str(),
PIN_PARG(CAPI_endpoint_t),
PIN_PARG(CAPI_endpoint_t),
PIN_PARG(char*),
PIN_PARG(int),
PIN_PARG_END() );
RTN_ReplaceSignature(rtn, msg_ptr,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
IARG_FUNCARG_ENTRYPOINT_VALUE, 2,
IARG_FUNCARG_ENTRYPOINT_VALUE, 3,
IARG_END);
//RTN_Close(rtn);
PROTO_Free(proto);
return true;
}
else if ( (msg_ptr == AFUNPTR(MCPRun)) || (msg_ptr == AFUNPTR(MCPFinish)) )
{
proto = PROTO_Allocate(PIN_PARG(void),
CALLINGSTD_DEFAULT,
name.c_str(),
PIN_PARG_END() );
RTN_ReplaceSignature(rtn, msg_ptr,
IARG_END);
//RTN_Close(rtn);
PROTO_Free(proto);
return true;
}
return false;
}
VOID routine(RTN rtn, VOID *v)
{
string rtn_name = RTN_Name(rtn);
// cout << "routine " << RTN_Name(rtn) << endl;
bool did_func_replace = replaceUserAPIFunction(rtn, rtn_name);
if ( did_func_replace == false )
{
RTN_Open(rtn);
INS rtn_head = RTN_InsHead(rtn);
bool is_rtn_ins_head = true;
set<INS> ins_uses;
if ( g_knob_enable_performance_modeling && g_knob_enable_dcache_modeling && !g_knob_dcache_ignore_loads )
{
getPotentialLoadFirstUses(rtn, ins_uses);
}
// Add instrumentation to each basic block for modeling
for (BBL bbl = RTN_BblHead(rtn); BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
UINT32 inst_offset = 0;
UINT32 last_offset = BBL_NumIns(bbl);
INS start_ins = BBL_InsHead(bbl);
INS ins;
for (ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins))
{
INS next = INS_Next(ins);
assert( !INS_Valid(next) || (INS_Address(next) > INS_Address(ins)) );
assert( !is_rtn_ins_head || (ins==rtn_head) );
set<INS>::iterator it = ins_uses.find(ins);
bool is_potential_load_use = ( it != ins_uses.end() );
if ( is_potential_load_use ) {
ins_uses.erase( it );
}
bool instrumented =
insertInstructionModelingCall(rtn_name, start_ins, ins, is_rtn_ins_head, (inst_offset == 0),
!INS_Valid(next), is_potential_load_use );
if ( instrumented ) {
start_ins = INS_Next(ins);
}
++inst_offset;
is_rtn_ins_head = false;
}
assert( inst_offset == last_offset );
}
RTN_Close(rtn);
}
}
/* ===================================================================== */
VOID fini(int code, VOID * v)
{
Transport::ptFinish();
g_chip->fini(code, v);
}
/* ===================================================================== */
VOID init_globals()
{
//FIXME
//InitLock(&g_lock1);
//InitLock(&g_lock2);
g_config = new Config;
//g_config->loadFromFile(FIXME);
// NOTE: transport and queues must be inited before the chip
Transport::ptInitQueue(g_knob_num_cores);
g_chip = new Chip(g_knob_num_cores);
// Note the MCP has a dependency on the transport layer and the chip
g_MCP = new MCP();
}
void SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
//GetLock(&g_lock1, 1);
syscallEnterRunModel(ctxt, std);
//ReleaseLock(&g_lock1);
}
void SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v)
{
//GetLock(&g_lock2, 1);
syscallExitRunModel(ctxt, std);
//ReleaseLock(&g_lock2);
//ReleaseLock(&g_lock1);
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
if( PIN_Init(argc,argv) )
return usage();
init_globals();
RTN_AddInstrumentFunction(routine, 0);
PIN_AddSyscallEntryFunction(SyscallEntry, 0);
PIN_AddSyscallExitFunction(SyscallExit, 0);
PIN_AddFiniFunction(fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
/* ===================================================================== */
/* eof */
/* ===================================================================== */
<|endoftext|> |
<commit_before>
#include "platform.h"
#include <platform/xlib/system.h>
//#include <platform/xcb/system.h>
//#include <platform/dummy/system.h>
namespace platform
{
////////////////////////////////////////
void platform::init( void )
{
platform::platform::enroll( "xlib", "gl", [] { return std::make_shared<xlib::system>(); } );
// platform::platform::enroll( "xcb", "cairo", [] { return std::make_shared<xcb::system>(); } );
// platform::platform::enroll( "dummy", "dummy", [] { return std::make_shared<dummy::system>(); } );
}
}
<commit_msg>set locale so we can use multi-byte functions<commit_after>
#include "platform.h"
#include <platform/xlib/system.h>
//#include <platform/xcb/system.h>
//#include <platform/dummy/system.h>
#include <clocale>
namespace platform
{
////////////////////////////////////////
void platform::init( void )
{
std::setlocale( LC_ALL, "" );
platform::platform::enroll( "xlib", "gl", [] { return std::make_shared<xlib::system>(); } );
// platform::platform::enroll( "xcb", "cairo", [] { return std::make_shared<xcb::system>(); } );
// platform::platform::enroll( "dummy", "dummy", [] { return std::make_shared<dummy::system>(); } );
}
}
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.
#include <iostream>
#include <string>
#include <string.h> // memcpy
#include <fstream>
#include <vector>
#include "tclap/CmdLine.h"
#include <lz4.h>
#define STB_IMAGE_IMPLEMENTATION
#include "../third-party/stb_image.h"
#define RS_EMBED_VERSION "0.0.0.1"
struct float3
{
float x, y, z;
};
struct short3
{
uint16_t x, y, z;
};
using namespace std;
using namespace TCLAP;
bool file_exists(const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
struct int6
{
int x, y, z, a, b, c;
};
bool ends_with(const std::string& s, const std::string& suffix)
{
auto i = s.rbegin(), j = suffix.rbegin();
for (; i != s.rend() && j != suffix.rend() && *i == *j;
i++, j++);
return j == suffix.rend();
}
int main(int argc, char** argv) try
{
// Parse command line arguments
CmdLine cmd("librealsense rs-embed tool", ' ', RS_EMBED_VERSION);
ValueArg<string> inputFilename("i", "input", "Input filename", true, "", "input-file");
ValueArg<string> outputFilename("o", "output", "Output filename", false, "", "output-file");
ValueArg<string> objectName("n", "name", "Name", false, "", "object-name");
cmd.add(inputFilename);
cmd.add(outputFilename);
cmd.add(objectName);
cmd.parse(argc, argv);
auto input = inputFilename.getValue();
auto output = outputFilename.getValue();
auto name = objectName.getValue();
if (ends_with(input, ".obj"))
{
std::vector<float3> vertex_data;
std::vector<float3> normals_raw_data;
std::vector<float3> normals_data;
std::vector<int6> index_raw_data;
std::vector<short3> index_data;
if (file_exists(input))
{
std::ifstream file(input);
std::string str;
while (std::getline(file, str))
{
if (str.size())
{
if (str[0] == 'v')
{
float a, b, c;
if (str[1] == 'n')
{
sscanf(str.c_str(), "vn %f %f %f", &a, &b, &c);
normals_raw_data.push_back({ a, b, c });
}
else
{
sscanf(str.c_str(), "v %f %f %f", &a, &b, &c);
vertex_data.push_back({ a, b, c });
}
}
if (str[0] == 'f')
{
int x, y, z, a, b, c;
sscanf(str.c_str(), "f %d//%d %d//%d %d//%d", &x, &a, &y, &b, &z, &c);
index_raw_data.push_back({ x, y, z, a, b, c });
}
}
}
}
else
{
std::cout << "file: " << input << " could not be found!" << std::endl;
return EXIT_FAILURE;
}
normals_data.resize(vertex_data.size());
for (auto& idx : index_raw_data)
{
// TODO - normals data are currently disabled
// normals_data[idx.x] = normals_raw_data[idx.a];
// normals_data[idx.y] = normals_raw_data[idx.b];
// normals_data[idx.z] = normals_raw_data[idx.c];
index_data.push_back({ static_cast<uint16_t>(idx.x - 1),
static_cast<uint16_t>(idx.y - 1),
static_cast<uint16_t>(idx.z - 1) });
}
size_t vertex_data_size = vertex_data.size() * sizeof(float3);
size_t index_data_size = index_data.size() * sizeof(short3);
//size_t normals_data_size = normals_data.size() * sizeof(float3);
std::vector<uint8_t> data(vertex_data_size + index_data_size, 0);
memcpy(data.data(), vertex_data.data(), vertex_data_size);
memcpy(data.data() + vertex_data_size, index_data.data(), index_data_size);
//memcpy(data.data() + vertex_data_size + index_data_size, normals_data.data(), normals_data_size);
// compress szSource into pchCompressed
auto rawDataSize = (int)data.size();
auto compressBufSize = LZ4_compressBound(rawDataSize);
char* pchCompressed = new char[compressBufSize];
memset(pchCompressed, compressBufSize, 0);
int nCompressedSize = LZ4_compress_default((const char*)data.data(), pchCompressed, rawDataSize, compressBufSize);
ofstream myfile;
myfile.open(output);
myfile << "// License: Apache 2.0. See LICENSE file in root directory.\n";
myfile << "// Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n";
myfile << "// This file is auto-generated from " << name << ".obj\n";
myfile << "#pragma once\n";
myfile << "static uint32_t " << name << "_obj_data [] { ";
auto nAllignedCompressedSize = nCompressedSize;
auto leftover = nCompressedSize % 4;
if (leftover % 4 != 0) nAllignedCompressedSize += (4 - leftover);
for (int i = 0; i < nAllignedCompressedSize; i += 4)
{
uint32_t* ptr = (uint32_t*)(pchCompressed + i);
myfile << "0x" << std::hex << (int)(*ptr);
if (i < nAllignedCompressedSize - 1) myfile << ",";
}
myfile << "};\n";
myfile << "#include <lz4.h>\n";
myfile << "#include <vector>\n";
myfile << "inline void uncompress_" << name << "_obj(std::vector<float3>& vertex_data, std::vector<float3>& normals, std::vector<short3>& index_data)\n";
myfile << "{\n";
myfile << " std::vector<char> uncompressed(0x" << std::hex << rawDataSize << ", 0);\n";
myfile << " LZ4_decompress_safe((const char*)" << name << "_obj_data, uncompressed.data(), 0x" << std::hex << nCompressedSize << ", 0x" << std::hex << rawDataSize << ");\n";
myfile << " const int vertex_size = 0x" << std::hex << vertex_data.size() << " * sizeof(float3);\n";
myfile << " const int index_size = 0x" << std::hex << index_data.size() << " * sizeof(short3);\n";
myfile << " vertex_data.resize(0x" << std::hex << vertex_data.size() << ");\n";
myfile << " memcpy(vertex_data.data(), uncompressed.data(), vertex_size);\n";
myfile << " index_data.resize(0x" << std::hex << index_data.size() << ");\n";
myfile << " memcpy(index_data.data(), uncompressed.data() + vertex_size, index_size);\n";
myfile << " //normals.resize(0x" << std::hex << vertex_data.size() << ");\n";
myfile << " //memcpy(normals.data(), uncompressed.data() + vertex_size + index_size, vertex_size);\n";
myfile << "}\n";
myfile.close();
}
if (ends_with(input, ".png"))
{
ifstream ifs(input, ios::binary | ios::ate);
ifstream::pos_type pos = ifs.tellg();
std::vector<char> buffer(pos);
ifs.seekg(0, ios::beg);
ifs.read(&buffer[0], pos);
ofstream myfile;
myfile.open(output);
myfile << "// License: Apache 2.0. See LICENSE file in root directory.\n";
myfile << "// Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n";
myfile << "// This file is auto-generated from " << name << ".png\n";
myfile << "static uint32_t " << name << "_png_size = 0x" << std::hex << buffer.size() << ";\n";
myfile << "static uint8_t " << name << "_png_data [] { ";
for (int i = 0; i < buffer.size(); i++)
{
uint8_t byte = buffer[i];
myfile << "0x" << std::hex << (int)byte;
if (i < buffer.size() - 1) myfile << ",";
}
myfile << "};\n";
myfile.close();
}
return EXIT_SUCCESS;
}
catch (const exception& e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
catch (...)
{
cerr << "some error" << endl;
return EXIT_FAILURE;
}
<commit_msg>add creation time to output file<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2021 Intel Corporation. All Rights Reserved.
#include <iostream>
#include <string>
#include <string.h> // memcpy
#include <fstream>
#include <vector>
#include "tclap/CmdLine.h"
#include <lz4.h>
#define STB_IMAGE_IMPLEMENTATION
#include "../third-party/stb_image.h"
#define RS_EMBED_VERSION "0.0.0.1"
struct float3
{
float x, y, z;
};
struct short3
{
uint16_t x, y, z;
};
using namespace std;
using namespace TCLAP;
bool file_exists(const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
struct int6
{
int x, y, z, a, b, c;
};
bool ends_with(const std::string& s, const std::string& suffix)
{
auto i = s.rbegin(), j = suffix.rbegin();
for (; i != s.rend() && j != suffix.rend() && *i == *j;
i++, j++);
return j == suffix.rend();
}
std::string get_current_time()
{
auto t = time(nullptr);
char buffer[20] = {};
const tm* time = localtime(&t);
if (nullptr != time)
strftime(buffer, sizeof(buffer), "%m/%d/%Y %H:%M:%S", time);
return std::string(buffer);
}
int main(int argc, char** argv) try
{
// Parse command line arguments
CmdLine cmd("librealsense rs-embed tool", ' ', RS_EMBED_VERSION);
ValueArg<string> inputFilename("i", "input", "Input filename", true, "", "input-file");
ValueArg<string> outputFilename("o", "output", "Output filename", false, "", "output-file");
ValueArg<string> objectName("n", "name", "Name", false, "", "object-name");
cmd.add(inputFilename);
cmd.add(outputFilename);
cmd.add(objectName);
cmd.parse(argc, argv);
auto input = inputFilename.getValue();
auto output = outputFilename.getValue();
auto name = objectName.getValue();
if (ends_with(input, ".obj"))
{
std::vector<float3> vertex_data;
std::vector<float3> normals_raw_data;
std::vector<float3> normals_data;
std::vector<int6> index_raw_data;
std::vector<short3> index_data;
if (file_exists(input))
{
std::ifstream file(input);
std::string str;
while (std::getline(file, str))
{
if (str.size())
{
if (str[0] == 'v')
{
float a, b, c;
if (str[1] == 'n')
{
sscanf(str.c_str(), "vn %f %f %f", &a, &b, &c);
normals_raw_data.push_back({ a, b, c });
}
else
{
sscanf(str.c_str(), "v %f %f %f", &a, &b, &c);
vertex_data.push_back({ a, b, c });
}
}
if (str[0] == 'f')
{
int x, y, z, a, b, c;
sscanf(str.c_str(), "f %d//%d %d//%d %d//%d", &x, &a, &y, &b, &z, &c);
index_raw_data.push_back({ x, y, z, a, b, c });
}
}
}
}
else
{
std::cout << "file: " << input << " could not be found!" << std::endl;
return EXIT_FAILURE;
}
normals_data.resize(vertex_data.size());
for (auto& idx : index_raw_data)
{
// TODO - normals data are currently disabled
// normals_data[idx.x] = normals_raw_data[idx.a];
// normals_data[idx.y] = normals_raw_data[idx.b];
// normals_data[idx.z] = normals_raw_data[idx.c];
index_data.push_back({ static_cast<uint16_t>(idx.x - 1),
static_cast<uint16_t>(idx.y - 1),
static_cast<uint16_t>(idx.z - 1) });
}
size_t vertex_data_size = vertex_data.size() * sizeof(float3);
size_t index_data_size = index_data.size() * sizeof(short3);
//size_t normals_data_size = normals_data.size() * sizeof(float3);
std::vector<uint8_t> data(vertex_data_size + index_data_size, 0);
memcpy(data.data(), vertex_data.data(), vertex_data_size);
memcpy(data.data() + vertex_data_size, index_data.data(), index_data_size);
//memcpy(data.data() + vertex_data_size + index_data_size, normals_data.data(), normals_data_size);
// compress szSource into pchCompressed
auto rawDataSize = (int)data.size();
auto compressBufSize = LZ4_compressBound(rawDataSize);
char* pchCompressed = new char[compressBufSize];
memset(pchCompressed, compressBufSize, 0);
int nCompressedSize = LZ4_compress_default((const char*)data.data(), pchCompressed, rawDataSize, compressBufSize);
ofstream myfile;
myfile.open(output);
myfile << "// License: Apache 2.0. See LICENSE file in root directory.\n";
myfile << "// Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n";
myfile << "// This file is auto-generated from " << name << ".obj using rs-embed tool version: " << RS_EMBED_VERSION <<"\n";
myfile << "// Generation time: " << get_current_time() << ".\n\n";
myfile << "#pragma once\n";
myfile << "static uint32_t " << name << "_obj_data [] { ";
auto nAllignedCompressedSize = nCompressedSize;
auto leftover = nCompressedSize % 4;
if (leftover % 4 != 0) nAllignedCompressedSize += (4 - leftover);
for (int i = 0; i < nAllignedCompressedSize; i += 4)
{
uint32_t* ptr = (uint32_t*)(pchCompressed + i);
myfile << "0x" << std::hex << (int)(*ptr);
if (i < nAllignedCompressedSize - 1) myfile << ",";
}
myfile << "};\n";
myfile << "#include <lz4.h>\n";
myfile << "#include <vector>\n";
myfile << "inline void uncompress_" << name << "_obj(std::vector<float3>& vertex_data, std::vector<float3>& normals, std::vector<short3>& index_data)\n";
myfile << "{\n";
myfile << " std::vector<char> uncompressed(0x" << std::hex << rawDataSize << ", 0);\n";
myfile << " LZ4_decompress_safe((const char*)" << name << "_obj_data, uncompressed.data(), 0x" << std::hex << nCompressedSize << ", 0x" << std::hex << rawDataSize << ");\n";
myfile << " const int vertex_size = 0x" << std::hex << vertex_data.size() << " * sizeof(float3);\n";
myfile << " const int index_size = 0x" << std::hex << index_data.size() << " * sizeof(short3);\n";
myfile << " vertex_data.resize(0x" << std::hex << vertex_data.size() << ");\n";
myfile << " memcpy(vertex_data.data(), uncompressed.data(), vertex_size);\n";
myfile << " index_data.resize(0x" << std::hex << index_data.size() << ");\n";
myfile << " memcpy(index_data.data(), uncompressed.data() + vertex_size, index_size);\n";
myfile << " //normals.resize(0x" << std::hex << vertex_data.size() << ");\n";
myfile << " //memcpy(normals.data(), uncompressed.data() + vertex_size + index_size, vertex_size);\n";
myfile << "}\n";
myfile.close();
}
if (ends_with(input, ".png"))
{
ifstream ifs(input, ios::binary | ios::ate);
ifstream::pos_type pos = ifs.tellg();
std::vector<char> buffer(pos);
ifs.seekg(0, ios::beg);
ifs.read(&buffer[0], pos);
ofstream myfile;
myfile.open(output);
myfile << "// License: Apache 2.0. See LICENSE file in root directory.\n";
myfile << "// Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n";
myfile << "// This file is auto-generated from " << name << ".png using rs-embed tool version: " << RS_EMBED_VERSION << "\n";
myfile << "// Generation time: " << get_current_time() << ".\n\n";
myfile << "static uint32_t " << name << "_png_size = 0x" << std::hex << buffer.size() << ";\n";
myfile << "static uint8_t " << name << "_png_data [] { ";
for (int i = 0; i < buffer.size(); i++)
{
uint8_t byte = buffer[i];
myfile << "0x" << std::hex << (int)byte;
if (i < buffer.size() - 1) myfile << ",";
}
myfile << "};\n";
myfile.close();
}
return EXIT_SUCCESS;
}
catch (const exception& e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
catch (...)
{
cerr << "some error" << endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>namespace mant {
template <typename T, typename U = double>
class GridSearch : public SamplingBasedOptimisationAlgorithm<T, U> {
public:
explicit GridSearch(
const std::shared_ptr<OptimisationProblem<T, U>> optimisationProblem) noexcept;
void setNumberOfSamples(
const arma::Col<unsigned int>& numberOfSamples);
std::string toString() const noexcept override;
protected:
arma::Col<unsigned int> numberOfSamples_;
void optimiseImplementation() noexcept override;
};
//
// Implementation
//
template <typename T, typename U>
GridSearch<T, U>::GridSearch(
const std::shared_ptr<OptimisationProblem<T>> optimisationProblem) noexcept
: SamplingBasedOptimisationAlgorithm<T>(optimisationProblem) {
setNumberOfSamples(arma::zeros(this->numberOfDimensions_) + 10);
}
template <typename T, typename U>
void GridSearch<T, U>::optimiseImplementation() noexcept {
verify(arma::accu(numberOfSamples_) <= this->maximalNumberOfIterations_ * this->numberOfNodes_, "");
if (std::is_integral<T>::value) {
// For integral types, ensure that each dimension has as least the same amout of elements as
// samples.
verify(arma::all(numberOfSamples_ >= this->getUpperBounds() - this->getLowerBounds()), "");
}
std::vector<arma::Col<T>> samples;
for (std::size_t n = 0; n < this->numberOfDimensions_; ++n) {
samples.push_back(arma::linspace<arma::Col<T>>(this->getLowerBounds()(n), this->getUpperBounds()(n), numberOfSamples_(n)));
}
arma::Col<unsigned int> sampleIndicies = arma::zeros<arma::Col<unsigned int>>(this->numberOfDimensions_);
for(std::size_t n = 0; n < arma::accu(numberOfSamples_); ++n) {
if (n % this->numberOfNodes_ == this->rank_) {
++this->numberOfIterations_;
arma::Col<T> candidateParameter(this->numberOfDimensions_);;
for(std::size_t k = 0; k < sampleIndicies.n_elem; ++k) {
candidateParameter(k) = samples.at(k)(sampleIndicies(k));
}
updateBestParameter(candidateParameter, this->getSoftConstraintsValue(candidateParameter), this->getObjectiveValue(candidateParameter));
if (this->isFinished()) {
break;
}
}
++sampleIndicies(0);
for(std::size_t k = 0; k < sampleIndicies.n_elem - 1; ++k) {
if(sampleIndicies(k) >= numberOfSamples_(k)) {
sampleIndicies(k) = 0;
++sampleIndicies(k + 1);
} else {
break;
}
}
}
}
template <typename T, typename U>
void GridSearch<T, U>::setNumberOfSamples(
const arma::Col<unsigned int>& numberOfSamples) {
verify(arma::all(numberOfSamples > 0), "");
numberOfSamples_ = numberOfSamples;
}
template <typename T, typename U>
std::string GridSearch<T, U>::toString() const noexcept {
return "grid_search";
}
}
<commit_msg>Fixed constructor list<commit_after>namespace mant {
template <typename T, typename U = double>
class GridSearch : public SamplingBasedOptimisationAlgorithm<T, U> {
public:
explicit GridSearch(
const std::shared_ptr<OptimisationProblem<T, U>> optimisationProblem) noexcept;
void setNumberOfSamples(
const arma::Col<unsigned int>& numberOfSamples);
std::string toString() const noexcept override;
protected:
arma::Col<unsigned int> numberOfSamples_;
void optimiseImplementation() noexcept override;
};
//
// Implementation
//
template <typename T, typename U>
GridSearch<T, U>::GridSearch(
const std::shared_ptr<OptimisationProblem<T, U>> optimisationProblem) noexcept
: SamplingBasedOptimisationAlgorithm<T, U>(optimisationProblem) {
setNumberOfSamples(arma::zeros(this->numberOfDimensions_) + 10);
}
template <typename T, typename U>
void GridSearch<T, U>::optimiseImplementation() noexcept {
verify(arma::accu(numberOfSamples_) <= this->maximalNumberOfIterations_ * this->numberOfNodes_, "");
if (std::is_integral<T>::value) {
// For integral types, ensure that each dimension has as least the same amout of elements as
// samples.
verify(arma::all(numberOfSamples_ >= this->getUpperBounds() - this->getLowerBounds()), "");
}
std::vector<arma::Col<T>> samples;
for (std::size_t n = 0; n < this->numberOfDimensions_; ++n) {
samples.push_back(arma::linspace<arma::Col<T>>(this->getLowerBounds()(n), this->getUpperBounds()(n), numberOfSamples_(n)));
}
arma::Col<unsigned int> sampleIndicies = arma::zeros<arma::Col<unsigned int>>(this->numberOfDimensions_);
for(std::size_t n = 0; n < arma::accu(numberOfSamples_); ++n) {
if (n % this->numberOfNodes_ == this->rank_) {
++this->numberOfIterations_;
arma::Col<T> candidateParameter(this->numberOfDimensions_);;
for(std::size_t k = 0; k < sampleIndicies.n_elem; ++k) {
candidateParameter(k) = samples.at(k)(sampleIndicies(k));
}
updateBestParameter(candidateParameter, this->getSoftConstraintsValue(candidateParameter), this->getObjectiveValue(candidateParameter));
if (this->isFinished()) {
break;
}
}
++sampleIndicies(0);
for(std::size_t k = 0; k < sampleIndicies.n_elem - 1; ++k) {
if(sampleIndicies(k) >= numberOfSamples_(k)) {
sampleIndicies(k) = 0;
++sampleIndicies(k + 1);
} else {
break;
}
}
}
}
template <typename T, typename U>
void GridSearch<T, U>::setNumberOfSamples(
const arma::Col<unsigned int>& numberOfSamples) {
verify(arma::all(numberOfSamples > 0), "");
numberOfSamples_ = numberOfSamples;
}
template <typename T, typename U>
std::string GridSearch<T, U>::toString() const noexcept {
return "grid_search";
}
}
<|endoftext|> |
<commit_before>// symbiosis: A framework for toy compilers
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
#include <functional>
#include "cpu_defines.hpp"
using namespace std;
namespace symbiosis {
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
}
#ifdef __x86_64__
bool intel = true;
bool arm = false;
#endif
#ifdef __arm__
bool intel = false;
bool arm = true;
#endif
bool pic_mode;
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
constexpr int parameters_max = 3;
class Backend {
vector<function<void()> > callbacks;
public:
int parameter_count = 0;
Backend() { }
virtual ~Backend() { }
void callback(function<void()> f) { callbacks.push_back(f); }
void perform_callbacks() {
for (size_t i = 0; i < callbacks.size(); ++i) { callbacks[i](); }}
virtual void add_parameter(id p) = 0;
virtual void jmp(void *f) = 0;
virtual void __call(void *f) = 0;
virtual void __vararg_call(void *f) = 0;
virtual void emit_byte(uchar uc) = 0;
virtual void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
for (uchar * b = s; b < e; b++) emit_byte(*b);
//dump(out_start, l);
}
};
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
class Intel : public Backend {
public:
Intel() : Backend() { }
void emit_byte(uchar c) {
if (out_c + 1 > out_code_end) throw exception("Code: Out of memory");
*out_c = c;
out_c++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_JMP_e9);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_CALL_e8);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __vararg_call(void *f) {
emit_byte(I_XOR_30); emit_byte(0xc0); // xor al,al
__call(f);
}
};
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
class Arm : public Backend {
int ofs = 4;
public:
Arm() : Backend() { }
void emit_byte(uchar c) {
if (ofs == 4) {
if (out_c > out_code_start) { printf("<<"); dump(out_c - 3, 4); printf(">>"); }
if (out_c + 4 > out_code_end) throw exception("Code: Out of memory");
out_c += 4;
ofs = 0;
}
printf(".%02x", c);
*(out_c - ofs) = c;
ofs++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set string ref for : " <<
parameter_count << endl; });
} else {
throw exception("pic mode not supported yet!");
//uchar *out_current_code_pos = out_c;
//emit(register_rip_relative_parameters_intel_64[parameter_count]);
//emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set imm for : " << parameter_count << endl; });
} else if (p.is_64()) {
throw exception("64bit not supported yet!");
}
} else {
//cout << "No integer not supported yet" << endl;
throw exception("No integer not supported yet");
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_B_08);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_BL_eb);
emit(call_offset(out_current_code_pos, f), 4);
perform_callbacks();
}
virtual void __vararg_call(void *f) {
throw exception("No arm support yet!");
}
};
Backend* backend;
id add_parameter(id p) {
if (backend->parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
backend->add_parameter(p);
++backend->parameter_count;
return p;
}
void jmp(void *f) { backend->jmp(f); }
void __call(void *f) { backend->__call(f); backend->parameter_count = 0; }
void __vararg_call(void *f) { backend->__vararg_call(f); }
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
arm = true; intel = false; pic_mode = false;
cout << "intel: " << intel << ", arm: " << arm <<
", pic_mode: " << pic_mode << endl;
if (intel) { backend = new Intel(); }
if (arm) { backend = new Arm(); }
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
out_s = out_strings_start;
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<commit_msg>Fixed for arm.<commit_after>// symbiosis: A framework for toy compilers
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
#include <functional>
#include "cpu_defines.hpp"
using namespace std;
namespace symbiosis {
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
}
#ifdef __x86_64__
bool intel = true;
bool arm = false;
#endif
#ifdef __arm__
bool intel = false;
bool arm = true;
#endif
bool pic_mode;
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
constexpr int parameters_max = 3;
class Backend {
vector<function<void()> > callbacks;
public:
int parameter_count = 0;
Backend() { }
virtual ~Backend() { }
void callback(function<void()> f) { callbacks.push_back(f); }
void perform_callbacks() {
for (size_t i = 0; i < callbacks.size(); ++i) { callbacks[i](); }}
virtual void add_parameter(id p) = 0;
virtual void jmp(void *f) = 0;
virtual void __call(void *f) = 0;
virtual void __vararg_call(void *f) = 0;
virtual void emit_byte(uchar uc) = 0;
virtual void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
for (uchar * b = s; b < e; b++) emit_byte(*b);
//dump(out_start, l);
}
};
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
class Intel : public Backend {
public:
Intel() : Backend() { }
void emit_byte(uchar c) {
if (out_c + 1 > out_code_end) throw exception("Code: Out of memory");
*out_c = c;
out_c++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_JMP_e9);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_CALL_e8);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __vararg_call(void *f) {
emit_byte(I_XOR_30); emit_byte(0xc0); // xor al,al
__call(f);
}
};
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
class Arm : public Backend {
int ofs = 4;
public:
Arm() : Backend() { }
void emit_byte(uchar c) {
if (ofs == 4) {
if (out_c > out_code_start) { printf("<<"); dump(out_c - 3, 4); printf(">>"); }
if (out_c + 4 > out_code_end) throw exception("Code: Out of memory");
out_c += 4;
ofs = 0;
}
printf(".%02x", c);
*(out_c - ofs) = c;
ofs++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set string ref for : " <<
parameter_count << endl; });
} else {
throw exception("pic mode not supported yet!");
//uchar *out_current_code_pos = out_c;
//emit(register_rip_relative_parameters_intel_64[parameter_count]);
//emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set imm for : " << parameter_count << endl; });
} else if (p.is_64()) {
throw exception("64bit not supported yet!");
}
} else {
//cout << "No integer not supported yet" << endl;
throw exception("No integer not supported yet");
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_B_08);
emit(call_offset(out_current_code_pos, f), 3);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_BL_eb);
emit(call_offset(out_current_code_pos, f), 3);
perform_callbacks();
}
virtual void __vararg_call(void *f) {
throw exception("No arm support yet!");
}
};
Backend* backend;
id add_parameter(id p) {
if (backend->parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
backend->add_parameter(p);
++backend->parameter_count;
return p;
}
void jmp(void *f) { backend->jmp(f); }
void __call(void *f) { backend->__call(f); backend->parameter_count = 0; }
void __vararg_call(void *f) { backend->__vararg_call(f); }
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
arm = true; intel = false; pic_mode = false;
cout << "intel: " << intel << ", arm: " << arm <<
", pic_mode: " << pic_mode << endl;
if (intel) { backend = new Intel(); }
if (arm) { backend = new Arm(); }
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
out_s = out_strings_start;
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
#define N 10100
int par[N];
int n;
int l, r;
vector<int> lv, rv;
int main () {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
::memset(par, 0, sizeof par);
lv.clear();
rv.clear();
cin >> n;
int p, c;
for (int j = 0; j < n-1; j++) {
cin >> p >> c;
par[c] = p;
}
cin >> l >> r;
int li = l, ri = r;
while(li != 0) {
lv.push_back(li);
li = par[li];
}
while(ri != 0) {
rv.push_back(ri);
ri = par[ri];
}
reverse(lv.begin(), lv.end());
reverse(rv.begin(), rv.end());
int prefix = 0;
for (size_t i = 0; i < lv.size() && i < rv.size(); i++) {
if (lv[i] == rv[i]) {
prefix = i;
} else {
break;
}
}
printf("%d\n", lv[prefix]);
}
return 0;
}
<commit_msg>add tag for poj1330<commit_after>//Tag search Nearest Common Ancestors
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
#define N 10100
int par[N];
int n;
int l, r;
vector<int> lv, rv;
int main () {
int T;
cin >> T;
for (int i = 0; i < T; i++) {
::memset(par, 0, sizeof par);
lv.clear();
rv.clear();
cin >> n;
int p, c;
for (int j = 0; j < n-1; j++) {
cin >> p >> c;
par[c] = p;
}
cin >> l >> r;
int li = l, ri = r;
while(li != 0) {
lv.push_back(li);
li = par[li];
}
while(ri != 0) {
rv.push_back(ri);
ri = par[ri];
}
reverse(lv.begin(), lv.end());
reverse(rv.begin(), rv.end());
int prefix = 0;
for (size_t i = 0; i < lv.size() && i < rv.size(); i++) {
if (lv[i] == rv[i]) {
prefix = i;
} else {
break;
}
}
printf("%d\n", lv[prefix]);
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef VEXCL_VECTOR_POINTER_HPP
#define VEXCL_VECTOR_POINTER_HPP
/*
The MIT License
Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/vector_pointer.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Cast vex::vector to a raw pointer.
*/
#include <vexcl/vector.hpp>
#include <vexcl/operations.hpp>
namespace vex {
/// \cond INTERNAL
template <typename T>
struct vector_pointer {
typedef T value_type;
const vector<T> &v;
vector_pointer(const vector<T> &v) : v(v) {}
};
#ifndef VEXCL_BACKEND_CUDA
template <typename T>
struct constant_vector_pointer {
typedef T value_type;
const vector<T> &v;
constant_vector_pointer(const vector<T> &v) : v(v) {}
};
#endif
namespace traits {
template <typename T>
struct is_vector_expr_terminal< vector_pointer<T> > : std::true_type {};
template <typename T>
struct kernel_param_declaration< vector_pointer<T> >
{
static void get(backend::source_generator &src,
const vector_pointer<T>&,
const backend::command_queue&, const std::string &prm_name,
detail::kernel_generator_state_ptr)
{
src.parameter< global_ptr<T> >(prm_name);
}
};
template <typename T>
struct kernel_arg_setter< vector_pointer<T> >
{
static void set(const vector_pointer<T> &term,
backend::kernel &kernel, unsigned/*part*/, size_t/*index_offset*/,
detail::kernel_generator_state_ptr)
{
kernel.push_arg(term.v(0));
}
};
template <typename T>
struct expression_properties< vector_pointer<T> >
{
static void get(const vector_pointer<T> &term,
std::vector<backend::command_queue> &queue_list,
std::vector<size_t> &partition,
size_t &/*size*/
)
{
queue_list = term.v.queue_list();
// Raw pointers should not have size or partition info.
}
};
#ifndef VEXCL_BACKEND_CUDA
template <typename T>
struct is_vector_expr_terminal< constant_vector_pointer<T> > : std::true_type {};
template <typename T>
struct kernel_param_declaration< constant_vector_pointer<T> >
{
static void get(backend::source_generator &src,
const constant_vector_pointer<T>&,
const backend::command_queue&, const std::string &prm_name,
detail::kernel_generator_state_ptr)
{
src.parameter< constant_ptr<T> >(prm_name);
}
};
template <typename T>
struct kernel_arg_setter< constant_vector_pointer<T> >
{
static void set(const constant_vector_pointer<T> &term,
backend::kernel &kernel, unsigned/*part*/, size_t/*index_offset*/,
detail::kernel_generator_state_ptr)
{
kernel.push_arg(term.v(0));
}
};
template <typename T>
struct expression_properties< constant_vector_pointer<T> >
{
static void get(const constant_vector_pointer<T> &term,
std::vector<backend::command_queue> &queue_list,
std::vector<size_t> &partition,
size_t &/*size*/
)
{
queue_list = term.v.queue_list();
partition = term.v.partition();
// Raw pointers should not have size.
}
};
#endif
} // namespace traits
/// \endcond
/// Cast vex::vector to a raw pointer.
/**
* Useful when user wants to get a pointer to a vector instead of its current
* element inside a vector expression. Could be combined with calls to
* address_of/dereference operators or with user-defined functions iterating
* through the vector. See examples in tests/vector_pointer.cpp.
*/
template <typename T>
#ifdef DOXYGEN
vector_pointer<T>
#else
inline typename boost::proto::result_of::as_expr<vector_pointer<T>, vector_domain>::type
#endif
raw_pointer(const vector<T> &v) {
precondition(
v.nparts() == 1,
"raw_pointer is not supported for multi-device contexts"
);
return boost::proto::as_expr<vector_domain>(vector_pointer<T>(v));
}
#ifndef VEXCL_BACKEND_CUDA
/// Cast vex::vector to a constant pointer.
/**
* Useful when user wants to get a pointer to a constant vector instead of its
* current element inside a vector expression. Could be combined with calls to
* address_of/dereference operators or with user-defined functions iterating
* through the constant vector. This vector is atleast 64kB in size as defined
* by the openCL standard.
* One could for example cache some logarithmic math instead of calculating it.
\code
auto ptr = constant_pointer(log_table);
s = ptr[I];
\endcode
*/
template <typename T>
#ifdef DOXYGEN
constant_vector_pointer<T>
#else
inline typename boost::proto::result_of::as_expr<constant_vector_pointer<T>, vector_domain>::type
#endif
constant_pointer(const vector<T> &v) {
precondition(
v.nparts() == 1,
"constant_pointer is not supported for multi-device contexts"
);
return boost::proto::as_expr<vector_domain>(constant_vector_pointer<T>(v));
}
#endif
} // namespace vex
#endif
<commit_msg>Fix "unused parameter" warning<commit_after>#ifndef VEXCL_VECTOR_POINTER_HPP
#define VEXCL_VECTOR_POINTER_HPP
/*
The MIT License
Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* \file vexcl/vector_pointer.hpp
* \author Denis Demidov <dennis.demidov@gmail.com>
* \brief Cast vex::vector to a raw pointer.
*/
#include <vexcl/vector.hpp>
#include <vexcl/operations.hpp>
namespace vex {
/// \cond INTERNAL
template <typename T>
struct vector_pointer {
typedef T value_type;
const vector<T> &v;
vector_pointer(const vector<T> &v) : v(v) {}
};
#ifndef VEXCL_BACKEND_CUDA
template <typename T>
struct constant_vector_pointer {
typedef T value_type;
const vector<T> &v;
constant_vector_pointer(const vector<T> &v) : v(v) {}
};
#endif
namespace traits {
template <typename T>
struct is_vector_expr_terminal< vector_pointer<T> > : std::true_type {};
template <typename T>
struct kernel_param_declaration< vector_pointer<T> >
{
static void get(backend::source_generator &src,
const vector_pointer<T>&,
const backend::command_queue&, const std::string &prm_name,
detail::kernel_generator_state_ptr)
{
src.parameter< global_ptr<T> >(prm_name);
}
};
template <typename T>
struct kernel_arg_setter< vector_pointer<T> >
{
static void set(const vector_pointer<T> &term,
backend::kernel &kernel, unsigned/*part*/, size_t/*index_offset*/,
detail::kernel_generator_state_ptr)
{
kernel.push_arg(term.v(0));
}
};
template <typename T>
struct expression_properties< vector_pointer<T> >
{
static void get(const vector_pointer<T> &term,
std::vector<backend::command_queue> &queue_list,
std::vector<size_t>&,
size_t &/*size*/
)
{
queue_list = term.v.queue_list();
// Raw pointers should not have size or partition info.
}
};
#ifndef VEXCL_BACKEND_CUDA
template <typename T>
struct is_vector_expr_terminal< constant_vector_pointer<T> > : std::true_type {};
template <typename T>
struct kernel_param_declaration< constant_vector_pointer<T> >
{
static void get(backend::source_generator &src,
const constant_vector_pointer<T>&,
const backend::command_queue&, const std::string &prm_name,
detail::kernel_generator_state_ptr)
{
src.parameter< constant_ptr<T> >(prm_name);
}
};
template <typename T>
struct kernel_arg_setter< constant_vector_pointer<T> >
{
static void set(const constant_vector_pointer<T> &term,
backend::kernel &kernel, unsigned/*part*/, size_t/*index_offset*/,
detail::kernel_generator_state_ptr)
{
kernel.push_arg(term.v(0));
}
};
template <typename T>
struct expression_properties< constant_vector_pointer<T> >
{
static void get(const constant_vector_pointer<T> &term,
std::vector<backend::command_queue> &queue_list,
std::vector<size_t> &partition,
size_t &/*size*/
)
{
queue_list = term.v.queue_list();
partition = term.v.partition();
// Raw pointers should not have size.
}
};
#endif
} // namespace traits
/// \endcond
/// Cast vex::vector to a raw pointer.
/**
* Useful when user wants to get a pointer to a vector instead of its current
* element inside a vector expression. Could be combined with calls to
* address_of/dereference operators or with user-defined functions iterating
* through the vector. See examples in tests/vector_pointer.cpp.
*/
template <typename T>
#ifdef DOXYGEN
vector_pointer<T>
#else
inline typename boost::proto::result_of::as_expr<vector_pointer<T>, vector_domain>::type
#endif
raw_pointer(const vector<T> &v) {
precondition(
v.nparts() == 1,
"raw_pointer is not supported for multi-device contexts"
);
return boost::proto::as_expr<vector_domain>(vector_pointer<T>(v));
}
#ifndef VEXCL_BACKEND_CUDA
/// Cast vex::vector to a constant pointer.
/**
* Useful when user wants to get a pointer to a constant vector instead of its
* current element inside a vector expression. Could be combined with calls to
* address_of/dereference operators or with user-defined functions iterating
* through the constant vector. This vector is atleast 64kB in size as defined
* by the openCL standard.
* One could for example cache some logarithmic math instead of calculating it.
\code
auto ptr = constant_pointer(log_table);
s = ptr[I];
\endcode
*/
template <typename T>
#ifdef DOXYGEN
constant_vector_pointer<T>
#else
inline typename boost::proto::result_of::as_expr<constant_vector_pointer<T>, vector_domain>::type
#endif
constant_pointer(const vector<T> &v) {
precondition(
v.nparts() == 1,
"constant_pointer is not supported for multi-device contexts"
);
return boost::proto::as_expr<vector_domain>(constant_vector_pointer<T>(v));
}
#endif
} // namespace vex
#endif
<|endoftext|> |
<commit_before>/* Simulation of a neural network - read the header and README for further documentation */
#include "neuron.hpp"
#include <fstream>
#include "ppm/ppm.hpp"
#include "tclap/ValueArg.h"
#include <cassert>
#define INIT_SPIKE_FACTOR 10
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(CellEvent)
std::vector<std::shared_ptr<warped::Event> > Cell::initializeLP() {
std::vector<std::shared_ptr<warped::Event> > events;
/* Don't send any event if membrane_potential < 1 */
if (this->state_.membrane_potential_ < 1) { return events; }
/* Send spike events to all connected neighbors with receive time = refractory period */
for (auto neighbor : this->state_.neighbors_) {
auto weight = neighbor.second;
// TODO : Update the weight for the connected neighbors and send that
neighbor.second = weight + .01;
events.emplace_back(new CellEvent {neighbor.first, this->refractory_period_, neighbor.second});
}
/* Send the refractory self-event with receive time = refractory period */
events.emplace_back(new CellEvent {this->name_, this->refractory_period_, 0});
return events;
}
std::vector<std::shared_ptr<warped::Event> > Cell::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
auto received_event = static_cast<const CellEvent&>(event);
/* Check whether it is a refractory self-event */
if (received_event.sender_name_ == received_event.receiverName()) {
this->state_.membrane_potential_ = 0;
this->state_.latest_update_ts_ = received_event.timestamp();
return response_events;
}
/* Check if there is any connection for a spike to occur*/
auto it = this->state_.neighbors_.find(received_event.sender_name_);
assert(it != this->state_.neighbors_.end());
it->second = received_event.weight_;
if (received_event.weight_ < this->connection_threshold_) {
return response_events;
}
/* Check if the neuron is responsive */
if (this->state_.membrane_potential_ < 1.0) {
/* IntFire1 : Basic Integrate and Fire Model */
double delta_t = received_event.timestamp() - this->state_.latest_update_ts_;
this->state_.membrane_potential_ *= exp(-delta_t/membrane_time_const_);
this->state_.membrane_potential_ += received_event.weight_;
this->state_.latest_update_ts_ = received_event.timestamp();
}
/* Check if neuron is about to fire */
if (this->state_.membrane_potential_ >= 1.0) {
this->state_.num_spikes_++;
unsigned int ts = received_event.timestamp() + this->refractory_period_;
/* Send spike events to all connected neighbors with receive time = current time + ts */
for (auto neighbor : this->state_.neighbors_) {
auto weight = neighbor.second;
// TODO : Update the weight for the connected neighbors and send that
neighbor.second = weight + .01;
response_events.emplace_back(new CellEvent {neighbor.first, ts, neighbor.second});
}
/* Send the refractory self-event with receive time = current time + ts */
response_events.emplace_back(new CellEvent {this->name_, ts, 0});
}
return response_events;
}
int main(int argc, const char** argv) {
/* Read the command line arguments for study name and connection threshold */
std::string study_name = "ADHD200_CC200";
double connection_threshold = 0.0;
double membrane_time_const = 10.0; /* Unit is msecs */
unsigned int refractory_period = 5; /* Unit is msecs */
TCLAP::ValueArg<std::string> study_name_arg( "", "study-name",
"Name of the study", false, study_name, "string");
TCLAP::ValueArg<double> connection_threshold_arg( "", "connection-threshold",
"Threshold of connection strength", false, connection_threshold, "double");
TCLAP::ValueArg<double> membrane_time_const_arg( "", "membrane-time-const",
"Membrane Time Constant (in milli seconds)", false, membrane_time_const, "double");
TCLAP::ValueArg<unsigned int> refractory_period_arg( "", "refractory-period",
"Refractory Period (in milli seconds)", false, refractory_period, "unsigned int");
std::vector<TCLAP::Arg*> args = { &study_name_arg,
&connection_threshold_arg,
&membrane_time_const_arg,
&refractory_period_arg
};
warped::Simulation neuron_sim {"Neural Network Simulation", argc, argv, args};
study_name = study_name_arg.getValue();
connection_threshold = connection_threshold_arg.getValue();
membrane_time_const = membrane_time_const_arg.getValue();
refractory_period = refractory_period_arg.getValue();
/* Read the abbreviated file for neuron names and create the LPs */
std::ifstream file_stream;
std::string buffer = study_name + "/names.txt";
file_stream.open(buffer);
if (!file_stream.is_open()) {
std::cerr << "Invalid names file - " << buffer << std::endl;
return 0;
}
std::default_random_engine gen;
std::uniform_int_distribution<int> mem_potential(0, INIT_SPIKE_FACTOR);
std::vector<Cell> lps;
unsigned int row_index = 0;
while (getline(file_stream, buffer)) {
auto name = buffer + "_" + std::to_string(row_index++);
double membrane_potential = (static_cast<double> (mem_potential(gen))) / INIT_SPIKE_FACTOR;
lps.emplace_back(name, connection_threshold, membrane_time_const, refractory_period, membrane_potential);
}
file_stream.close();
/* Read the connection matrix and create the network for the neurons */
buffer = study_name + "/connection_matrix.txt";
file_stream.open(buffer);
if (!file_stream.is_open()) {
std::cerr << "Invalid connection matrix file - " << buffer << std::endl;
return 0;
}
row_index = 0;
while (getline(file_stream, buffer)) {
size_t pos = 0;
unsigned int col_index = 0;
while ((pos = buffer.find_first_of(" ", 0)) != std::string::npos) {
std::string::size_type sz;
auto weight = std::stod(buffer.substr(0, pos), &sz);
/* Note: Negative weight indicates inhibitory neurons
Positive weight indicates excitatory neurons
*/
if (row_index != col_index) {
lps[row_index].addNeighbor(lps[col_index].name_, weight);
}
buffer = buffer.substr(pos+1);
col_index++;
}
row_index++;
}
file_stream.close();
/* Simulate the neuron model */
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
neuron_sim.simulate(lp_pointers);
/** Post-simulation statistics **/
/* PPM spike heatmap setup*/
auto cols = std::ceil( sqrt(lps.size()) );
auto rows = (lps.size()+cols-1)/cols;
auto spikes_hmap = new ppm(cols, rows);
unsigned int num_active_neurons = 0, num_spikes = 0, max_spikes = 0;
for (auto& lp : lps) {
num_active_neurons += lp.spikeCount() ? 1 : 0;
num_spikes += lp.spikeCount();
if (lp.spikeCount() > max_spikes) {max_spikes = lp.spikeCount();}
}
std::cout << num_active_neurons << " out of " << lps.size()
<< " neurons fired a total of " << num_spikes << " spikes."
<< std::endl
<< "neuron with the most spikes fired " << max_spikes << " times."
<< std::endl;
/* Color heatmap red based on ratio of lp spikes versus the lp with the most spikes*/
for (unsigned int i = 0; i < lps.size(); i++) {
double ratio = ((double)lps[i].spikeCount()) / max_spikes;
if (ratio >= 0.5) {
spikes_hmap->r[i] = ratio * 255;
} else {
spikes_hmap->g[i] = (1.0-ratio) * 255;
}
}
spikes_hmap->write("neuron_spikes_hmap.ppm");
delete spikes_hmap;
/* Temporary debugging statistics */
std::ofstream LPDiag;
LPDiag.open("Diagnostics/LPData.txt");
for (auto lp : lps) {
LPDiag << lp.state_.membrane_potential_ << " " << lp.state_.latest_update_ts_ << std::endl;
}
LPDiag.close();
LPDiag.open("Diagnostics/NeighborData.txt");
for (auto lp : lps) {
for (auto neighbor : lp.state_.neighbors_) {
LPDiag << neighbor.first << " " << neighbor.second << std::endl;
}
LPDiag << "Next LP:" << std::endl;
}
return 0;
}
<commit_msg>refined post-simulation heatmap to represent with more colors<commit_after>/* Simulation of a neural network - read the header and README for further documentation */
#include "neuron.hpp"
#include <fstream>
#include "ppm/ppm.hpp"
#include "tclap/ValueArg.h"
#include <cassert>
#define INIT_SPIKE_FACTOR 10
WARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(CellEvent)
std::vector<std::shared_ptr<warped::Event> > Cell::initializeLP() {
std::vector<std::shared_ptr<warped::Event> > events;
/* Don't send any event if membrane_potential < 1 */
if (this->state_.membrane_potential_ < 1) { return events; }
/* Send spike events to all connected neighbors with receive time = refractory period */
for (auto neighbor : this->state_.neighbors_) {
auto weight = neighbor.second;
// TODO : Update the weight for the connected neighbors and send that
neighbor.second = weight + .01;
events.emplace_back(new CellEvent {neighbor.first, this->refractory_period_, neighbor.second});
}
/* Send the refractory self-event with receive time = refractory period */
events.emplace_back(new CellEvent {this->name_, this->refractory_period_, 0});
return events;
}
std::vector<std::shared_ptr<warped::Event> > Cell::receiveEvent(const warped::Event& event) {
std::vector<std::shared_ptr<warped::Event> > response_events;
auto received_event = static_cast<const CellEvent&>(event);
/* Check whether it is a refractory self-event */
if (received_event.sender_name_ == received_event.receiverName()) {
this->state_.membrane_potential_ = 0;
this->state_.latest_update_ts_ = received_event.timestamp();
return response_events;
}
/* Check if there is any connection for a spike to occur*/
auto it = this->state_.neighbors_.find(received_event.sender_name_);
assert(it != this->state_.neighbors_.end());
it->second = received_event.weight_;
if (received_event.weight_ < this->connection_threshold_) {
return response_events;
}
/* Check if the neuron is responsive */
if (this->state_.membrane_potential_ < 1.0) {
/* IntFire1 : Basic Integrate and Fire Model */
double delta_t = received_event.timestamp() - this->state_.latest_update_ts_;
this->state_.membrane_potential_ *= exp(-delta_t/membrane_time_const_);
this->state_.membrane_potential_ += received_event.weight_;
this->state_.latest_update_ts_ = received_event.timestamp();
}
/* Check if neuron is about to fire */
if (this->state_.membrane_potential_ >= 1.0) {
this->state_.num_spikes_++;
unsigned int ts = received_event.timestamp() + this->refractory_period_;
/* Send spike events to all connected neighbors with receive time = current time + ts */
for (auto neighbor : this->state_.neighbors_) {
auto weight = neighbor.second;
// TODO : Update the weight for the connected neighbors and send that
neighbor.second = weight + .01;
response_events.emplace_back(new CellEvent {neighbor.first, ts, neighbor.second});
}
/* Send the refractory self-event with receive time = current time + ts */
response_events.emplace_back(new CellEvent {this->name_, ts, 0});
}
return response_events;
}
int main(int argc, const char** argv) {
/* Read the command line arguments for study name and connection threshold */
std::string study_name = "ADHD200_CC200";
double connection_threshold = 0.0;
double membrane_time_const = 10.0; /* Unit is msecs */
unsigned int refractory_period = 5; /* Unit is msecs */
TCLAP::ValueArg<std::string> study_name_arg( "", "study-name",
"Name of the study", false, study_name, "string");
TCLAP::ValueArg<double> connection_threshold_arg( "", "connection-threshold",
"Threshold of connection strength", false, connection_threshold, "double");
TCLAP::ValueArg<double> membrane_time_const_arg( "", "membrane-time-const",
"Membrane Time Constant (in milli seconds)", false, membrane_time_const, "double");
TCLAP::ValueArg<unsigned int> refractory_period_arg( "", "refractory-period",
"Refractory Period (in milli seconds)", false, refractory_period, "unsigned int");
std::vector<TCLAP::Arg*> args = { &study_name_arg,
&connection_threshold_arg,
&membrane_time_const_arg,
&refractory_period_arg
};
warped::Simulation neuron_sim {"Neural Network Simulation", argc, argv, args};
study_name = study_name_arg.getValue();
connection_threshold = connection_threshold_arg.getValue();
membrane_time_const = membrane_time_const_arg.getValue();
refractory_period = refractory_period_arg.getValue();
/* Read the abbreviated file for neuron names and create the LPs */
std::ifstream file_stream;
std::string buffer = study_name + "/names.txt";
file_stream.open(buffer);
if (!file_stream.is_open()) {
std::cerr << "Invalid names file - " << buffer << std::endl;
return 0;
}
std::default_random_engine gen;
std::uniform_int_distribution<int> mem_potential(0, INIT_SPIKE_FACTOR);
std::vector<Cell> lps;
unsigned int row_index = 0;
while (getline(file_stream, buffer)) {
auto name = buffer + "_" + std::to_string(row_index++);
double membrane_potential = (static_cast<double> (mem_potential(gen))) / INIT_SPIKE_FACTOR;
lps.emplace_back(name, connection_threshold, membrane_time_const, refractory_period, membrane_potential);
}
file_stream.close();
/* Read the connection matrix and create the network for the neurons */
buffer = study_name + "/connection_matrix.txt";
file_stream.open(buffer);
if (!file_stream.is_open()) {
std::cerr << "Invalid connection matrix file - " << buffer << std::endl;
return 0;
}
row_index = 0;
while (getline(file_stream, buffer)) {
size_t pos = 0;
unsigned int col_index = 0;
while ((pos = buffer.find_first_of(" ", 0)) != std::string::npos) {
std::string::size_type sz;
auto weight = std::stod(buffer.substr(0, pos), &sz);
/* Note: Negative weight indicates inhibitory neurons
Positive weight indicates excitatory neurons
*/
if (row_index != col_index) {
lps[row_index].addNeighbor(lps[col_index].name_, weight);
}
buffer = buffer.substr(pos+1);
col_index++;
}
row_index++;
}
file_stream.close();
/* Simulate the neuron model */
std::vector<warped::LogicalProcess*> lp_pointers;
for (auto& lp : lps) {
lp_pointers.push_back(&lp);
}
neuron_sim.simulate(lp_pointers);
/** Post-simulation statistics **/
/* PPM spike heatmap setup*/
auto cols = std::ceil( sqrt(lps.size()) );
auto rows = (lps.size()+cols-1)/cols;
auto spikes_hmap = new ppm(cols, rows);
unsigned int num_active_neurons = 0, num_spikes = 0, max_spikes = 0;
for (auto& lp : lps) {
num_active_neurons += lp.spikeCount() ? 1 : 0;
num_spikes += lp.spikeCount();
if (lp.spikeCount() > max_spikes) {max_spikes = lp.spikeCount();}
}
std::cout << num_active_neurons << " out of " << lps.size()
<< " neurons fired a total of " << num_spikes << " spikes."
<< std::endl
<< "neuron with the most spikes fired " << max_spikes << " times."
<< std::endl;
/* Color heatmap red based on ratio of lp spikes versus the lp with the most spikes*/
for (unsigned int i = 0; i < lps.size(); i++) {
double ratio = ((double)lps[i].spikeCount()) / max_spikes;
/*Color red if the neuron spiked more than half as much as the neuron with the most spikes*/
if (ratio >= 0.5) {
ratio = (ratio - 0.5) / 0.5;
spikes_hmap->r[i] = ratio * 255;
}
/*Color green if the neuron spiked from 25% to 75% as much as the max spiked neuron*/
/*Green + Red (from above) = Yellow*/
if (ratio >= 0.25 && ratio <= 0.75) {
ratio = (ratio - 0.25) / 0.5;
spikes_hmap->g[i] = ratio * 255;
}
/*Color blue if the neuron spiked from 50% to 0% as much as the max spiked neuron*/
/*Green (from above) + Blue should be cyan but in this map it is very dark*/
if (ratio < 0.5) {
ratio = (ratio * 2);
spikes_hmap->b[i] = (1.0 - ratio) * 255;
}
}
spikes_hmap->write("neuron_spikes_hmap.ppm");
delete spikes_hmap;
/* Temporary debugging statistics */
std::ofstream LPDiag;
LPDiag.open("Diagnostics/LPData.txt");
for (auto lp : lps) {
LPDiag << lp.state_.membrane_potential_
<< " " << lp.state_.latest_update_ts_
<< " " << lp.spikeCount() << std::endl;
}
LPDiag.close();
LPDiag.open("Diagnostics/NeighborData.txt");
for (auto lp : lps) {
for (auto neighbor : lp.state_.neighbors_) {
LPDiag << neighbor.first << " " << neighbor.second << std::endl;
}
LPDiag << "Next LP:" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "utils.h"
#ifdef HAVE_PTHREAD_NAMING
#include <pthread.h>
#ifndef DEBUG
#ifdef HAVE_PTHREAD_SET_NAME_NP
#include <pthread_np.h>
#endif
#endif
#elif defined(HAVE_SETPROCTITLE)
#include <cstdlib>
#elif defined(__linux__)
#include <sys/prctl.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <cstdlib>
#endif
#if defined(_WIN32) || defined(_WIN64)
// The mechanism only make sense in debugging mode.
#ifndef NDEBUG
static DWORD const current_thread = -1;
static void SetThreadName(DWORD dwThreadID, LPCSTR threadName);
#endif
#endif
/**
* \file utils.cxx
*
* \brief Implementation of pipeline utilities.
*/
namespace vistk
{
bool
name_thread(thread_name_t const& name)
{
#ifdef HAVE_PTHREAD_NAMING
#ifdef HAVE_PTHREAD_SETNAME_NP
#ifdef PTHREAD_SETNAME_NP_TAKES_ID
pthread_t const tid = pthread_self();
int const ret = pthread_setname_np(tid, name.c_str());
#else
int const ret = pthread_setname_np(name.c_str());
#endif
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
// The documentation states that it only makes sense in debugging; respect it.
#ifndef NDEBUG
pthread_t const tid = pthread_self();
int const ret = pthread_set_name_np(tid, name.c_str());
#else
// Fail if not debugging.
bool const ret = true;
#endif
#endif
return !ret;
#elif defined(HAVE_SETPROCTITLE)
setproctitle("%s", name.c_str());
#elif defined(__linux__)
int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0);
return (ret < 0);
#elif defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
SetThreadName(current_thread, name.c_str());
#else
return false;
#endif
#else
(void)name;
return false;
#endif
return true;
}
envvar_value_t
get_envvar(envvar_name_t const& name)
{
envvar_value_t value = NULL;
#if defined(_WIN32) || defined(_WIN64)
DWORD sz = GetEnvironmentVariable(name, NULL, 0);
if (sz)
{
value = new char[sz];
sz = GetEnvironmentVariable(name, value, sz);
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
value = getenv(name);
#endif
return value;
}
void
free_envvar(envvar_value_t value)
{
#if defined(_WIN32) || defined(_WIN64)
delete [] value;
#else
(void)value;
#endif
}
}
#if defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
// Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
static DWORD const MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1 = caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName(DWORD dwThreadID, LPCSTR threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
#endif
#endif
<commit_msg>Fix the check for naming the thread on Linux<commit_after>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "utils.h"
#ifdef HAVE_PTHREAD_NAMING
#include <pthread.h>
#ifndef DEBUG
#ifdef HAVE_PTHREAD_SET_NAME_NP
#include <pthread_np.h>
#endif
#endif
#elif defined(HAVE_SETPROCTITLE)
#include <cstdlib>
#elif defined(__linux__)
#include <sys/prctl.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <cstdlib>
#endif
#if defined(_WIN32) || defined(_WIN64)
// The mechanism only make sense in debugging mode.
#ifndef NDEBUG
static DWORD const current_thread = -1;
static void SetThreadName(DWORD dwThreadID, LPCSTR threadName);
#endif
#endif
/**
* \file utils.cxx
*
* \brief Implementation of pipeline utilities.
*/
namespace vistk
{
bool
name_thread(thread_name_t const& name)
{
#ifdef HAVE_PTHREAD_NAMING
#ifdef HAVE_PTHREAD_SETNAME_NP
#ifdef PTHREAD_SETNAME_NP_TAKES_ID
pthread_t const tid = pthread_self();
int const ret = pthread_setname_np(tid, name.c_str());
#else
int const ret = pthread_setname_np(name.c_str());
#endif
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
// The documentation states that it only makes sense in debugging; respect it.
#ifndef NDEBUG
pthread_t const tid = pthread_self();
int const ret = pthread_set_name_np(tid, name.c_str());
#else
// Fail if not debugging.
bool const ret = true;
#endif
#endif
return !ret;
#elif defined(HAVE_SETPROCTITLE)
setproctitle("%s", name.c_str());
#elif defined(__linux__)
int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0);
if (ret)
{
return false;
}
#elif defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
SetThreadName(current_thread, name.c_str());
#else
return false;
#endif
#else
(void)name;
return false;
#endif
return true;
}
envvar_value_t
get_envvar(envvar_name_t const& name)
{
envvar_value_t value = NULL;
#if defined(_WIN32) || defined(_WIN64)
DWORD sz = GetEnvironmentVariable(name, NULL, 0);
if (sz)
{
value = new char[sz];
sz = GetEnvironmentVariable(name, value, sz);
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
value = getenv(name);
#endif
return value;
}
void
free_envvar(envvar_value_t value)
{
#if defined(_WIN32) || defined(_WIN64)
delete [] value;
#else
(void)value;
#endif
}
}
#if defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
// Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
static DWORD const MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1 = caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName(DWORD dwThreadID, LPCSTR threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
#endif
#endif
<|endoftext|> |
<commit_before>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>
namespace gg
{
VideoSourceVLC::VideoSourceVLC(const std::string path)
: _vlc_inst(nullptr)
, _vlc_mp(nullptr)
, _running(false)
, _video_buffer(nullptr)
, _data_length(0)
, _cols(0)
, _rows(0)
, _sub(nullptr)
, _path(path)
{
init_vlc();
run_vlc();
determine_full();
}
VideoSourceVLC::~VideoSourceVLC()
{
stop_vlc();
release_vlc();
clear();
}
bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if(this->_cols == 0 || this->_rows == 0)
return false;
width = this->_cols;
height = this->_rows;
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
throw VideoSourceError("VLC video source supports only I420 colour space");
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
return false;
// allocate and fill the image
if (_cols * _rows * 4 == this->_data_length)
frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
else
throw VideoSourceError("VLC video source does not support padded images");
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_data_length > 0)
{
// TODO manage data?
frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
return true;
}
else
return false;
// TODO #86
}
double VideoSourceVLC::get_frame_rate()
{
return libvlc_media_player_get_fps(_vlc_mp);
}
void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
if (_sub != nullptr) return; // TODO: see issue #101
if (x >= _full.x and x + width <= _full.x + _full.width and
y >= _full.y and y + height <= _full.y + _full.height)
{
stop_vlc();
release_vlc();
set_crop(x, y, width, height);
init_vlc();
run_vlc();
}
}
void VideoSourceVLC::get_full_frame()
{
return; // TODO: see issue #101
stop_vlc();
release_vlc();
reset_crop();
init_vlc();
run_vlc();
}
void VideoSourceVLC::init_vlc()
{
// VLC pointers
libvlc_media_t * vlc_media = nullptr;
// VLC options
char smem_options[512];
sprintf(smem_options, "#");
if (_sub != nullptr)
{
unsigned int croptop = _sub->y,
cropbottom = _full.height - (_sub->y + _sub->height),
cropleft = _sub->x,
cropright = _full.width - (_sub->x + _sub->width);
sprintf(smem_options,
"%stranscode{vcodec=I420,vfilter=croppadd{",
smem_options);
sprintf(smem_options,
"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}",
smem_options,
croptop, cropbottom, cropleft, cropright);
sprintf(smem_options, "%s}:", smem_options);
}
sprintf(smem_options,
"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
smem_options,
(long long int)(intptr_t)(void*) this,
(long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
(long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );
const char * const vlc_args[] = {
"-I", "dummy", // Don't use any interface
"--ignore-config", // Don't use VLC's config
"--file-logging",
// TODO - what about the options below?
//"--verbose=2", // Be much more verbose then normal for debugging purpose
//"--clock-jitter=0",
//"--file-caching=150",
"--no-audio",
"--sout", smem_options // Stream to memory
};
// We launch VLC
_vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
if (_vlc_inst == nullptr)
throw VideoSourceError("Could not create VLC engine");
// If path contains a colon (:), it will be treated as a
// URL. Else, it will be considered as a local path.
if (_path.find(":") == std::string::npos)
vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
else
vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
if (vlc_media == nullptr)
throw VideoSourceError(std::string("Could not open ").append(_path));
libvlc_media_add_option(vlc_media, ":noaudio");
libvlc_media_add_option(vlc_media, ":no-video-title-show");
// Create a media player playing environement
_vlc_mp = libvlc_media_player_new_from_media(vlc_media);
if (_vlc_mp == nullptr)
throw VideoSourceError("Could not create VLC media player");
// No need to keep the media now
libvlc_media_release(vlc_media);
}
void VideoSourceVLC::run_vlc()
{
{ // artificial scope for the mutex guard below
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
_running = true;
// play the media_player
if (libvlc_media_player_play(_vlc_mp) != 0)
throw VideoSourceError("Could not start VLC media player");
}
// empirically determined value that allows for initialisation
// to succeed before any API functions are called on this object
std::this_thread::sleep_for(std::chrono::milliseconds(350));
}
void VideoSourceVLC::stop_vlc()
{
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
// stop playing
libvlc_media_player_stop(_vlc_mp);
_running = false;
}
void VideoSourceVLC::release_vlc()
{
// free media player
libvlc_media_player_release(_vlc_mp);
// free engine
libvlc_release(_vlc_inst);
}
void VideoSourceVLC::clear()
{
// free buffer
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_video_buffer != nullptr)
{
delete[] _video_buffer;
_video_buffer = nullptr;
}
_data_length = 0;
_cols = 0;
_rows = 0;
reset_crop();
}
void VideoSourceVLC::determine_full()
{
unsigned int width, height;
if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
throw VideoSourceError("Could not get video dimensions");
_full.x = 0;
_full.y = 0;
_full.width = width;
_full.height = height;
}
void VideoSourceVLC::set_crop(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
if (_sub == nullptr) _sub = new FrameBox;
_sub->x = x;
_sub->y = y;
_sub->width = width;
_sub->height = height;
}
void VideoSourceVLC::reset_crop()
{
// free sub-frame
if (_sub != nullptr)
{
delete _sub;
_sub = nullptr;
}
}
void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
uint8_t ** pp_pixel_buffer,
size_t size)
{
std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock);
if (p_video_data->_running)
{
if (size > p_video_data->_data_length)
{
if (p_video_data->_data_length == 0)
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
malloc(size * sizeof(uint8_t))
);
else
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
);
}
p_video_data->_data_length = size;
*pp_pixel_buffer = p_video_data->_video_buffer;
}
}
void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
uint8_t * p_pixel_buffer,
size_t cols,
size_t rows,
size_t colour_depth,
size_t size)
{
std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock);
// TODO: explain how data should be handled (see #86)
if (p_video_data->_running)
{
p_video_data->_cols = cols;
p_video_data->_rows = rows;
}
}
}
<commit_msg>Issue #83: full_frame working now, and move mutex guard in stop_vlc, which was causing the stall randomly (race condition?)<commit_after>#include "vlc_video_source.h"
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <thread>
namespace gg
{
VideoSourceVLC::VideoSourceVLC(const std::string path)
: _vlc_inst(nullptr)
, _vlc_mp(nullptr)
, _running(false)
, _video_buffer(nullptr)
, _data_length(0)
, _cols(0)
, _rows(0)
, _sub(nullptr)
, _path(path)
{
init_vlc();
run_vlc();
determine_full();
}
VideoSourceVLC::~VideoSourceVLC()
{
stop_vlc();
release_vlc();
clear();
}
bool VideoSourceVLC::get_frame_dimensions(int & width, int & height)
{
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if(this->_cols == 0 || this->_rows == 0)
return false;
width = this->_cols;
height = this->_rows;
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame)
{
throw VideoSourceError("VLC video source supports only I420 colour space");
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_cols == 0 || _rows == 0 || _video_buffer == nullptr)
return false;
// allocate and fill the image
if (_cols * _rows * 4 == this->_data_length)
frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows);
else
throw VideoSourceError("VLC video source does not support padded images");
return true;
}
bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame)
{
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_data_length > 0)
{
// TODO manage data?
frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false);
return true;
}
else
return false;
// TODO #86
}
double VideoSourceVLC::get_frame_rate()
{
return libvlc_media_player_get_fps(_vlc_mp);
}
void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height)
{
if (_sub != nullptr) return; // TODO: see issue #101
if (x >= _full.x and x + width <= _full.x + _full.width and
y >= _full.y and y + height <= _full.y + _full.height)
{
stop_vlc();
release_vlc();
set_crop(x, y, width, height);
init_vlc();
run_vlc();
}
}
void VideoSourceVLC::get_full_frame()
{
stop_vlc();
release_vlc();
reset_crop();
init_vlc();
run_vlc();
}
void VideoSourceVLC::init_vlc()
{
// VLC pointers
libvlc_media_t * vlc_media = nullptr;
// VLC options
char smem_options[512];
sprintf(smem_options, "#");
if (_sub != nullptr)
{
unsigned int croptop = _sub->y,
cropbottom = _full.height - (_sub->y + _sub->height),
cropleft = _sub->x,
cropright = _full.width - (_sub->x + _sub->width);
sprintf(smem_options,
"%stranscode{vcodec=I420,vfilter=croppadd{",
smem_options);
sprintf(smem_options,
"%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}",
smem_options,
croptop, cropbottom, cropleft, cropright);
sprintf(smem_options, "%s}:", smem_options);
}
sprintf(smem_options,
"%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}",
smem_options,
(long long int)(intptr_t)(void*) this,
(long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender,
(long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream );
const char * const vlc_args[] = {
"-I", "dummy", // Don't use any interface
"--ignore-config", // Don't use VLC's config
"--file-logging",
// TODO - what about the options below?
//"--verbose=2", // Be much more verbose then normal for debugging purpose
//"--clock-jitter=0",
//"--file-caching=150",
"--no-audio",
"--sout", smem_options // Stream to memory
};
// We launch VLC
_vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
if (_vlc_inst == nullptr)
throw VideoSourceError("Could not create VLC engine");
// If path contains a colon (:), it will be treated as a
// URL. Else, it will be considered as a local path.
if (_path.find(":") == std::string::npos)
vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str());
else
vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str());
if (vlc_media == nullptr)
throw VideoSourceError(std::string("Could not open ").append(_path));
libvlc_media_add_option(vlc_media, ":noaudio");
libvlc_media_add_option(vlc_media, ":no-video-title-show");
// Create a media player playing environement
_vlc_mp = libvlc_media_player_new_from_media(vlc_media);
if (_vlc_mp == nullptr)
throw VideoSourceError("Could not create VLC media player");
// No need to keep the media now
libvlc_media_release(vlc_media);
}
void VideoSourceVLC::run_vlc()
{
{ // artificial scope for the mutex guard below
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
_running = true;
// play the media_player
if (libvlc_media_player_play(_vlc_mp) != 0)
throw VideoSourceError("Could not start VLC media player");
}
// empirically determined value that allows for initialisation
// to succeed before any API functions are called on this object
std::this_thread::sleep_for(std::chrono::milliseconds(350));
}
void VideoSourceVLC::stop_vlc()
{
// stop playing
libvlc_media_player_stop(_vlc_mp);
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
_running = false;
}
void VideoSourceVLC::release_vlc()
{
// free media player
libvlc_media_player_release(_vlc_mp);
// free engine
libvlc_release(_vlc_inst);
}
void VideoSourceVLC::clear()
{
// free buffer
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_video_buffer != nullptr)
{
delete[] _video_buffer;
_video_buffer = nullptr;
}
_data_length = 0;
_cols = 0;
_rows = 0;
reset_crop();
}
void VideoSourceVLC::determine_full()
{
unsigned int width, height;
if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0)
throw VideoSourceError("Could not get video dimensions");
_full.x = 0;
_full.y = 0;
_full.width = width;
_full.height = height;
}
void VideoSourceVLC::set_crop(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
if (_sub == nullptr) _sub = new FrameBox;
_sub->x = x;
_sub->y = y;
_sub->width = width;
_sub->height = height;
}
void VideoSourceVLC::reset_crop()
{
// free sub-frame
if (_sub != nullptr)
{
delete _sub;
_sub = nullptr;
}
}
void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data,
uint8_t ** pp_pixel_buffer,
size_t size)
{
std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock);
if (p_video_data->_running)
{
if (size > p_video_data->_data_length)
{
if (p_video_data->_data_length == 0)
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
malloc(size * sizeof(uint8_t))
);
else
p_video_data->_video_buffer = reinterpret_cast<uint8_t *>(
realloc(p_video_data->_video_buffer, size * sizeof(uint8_t))
);
}
p_video_data->_data_length = size;
*pp_pixel_buffer = p_video_data->_video_buffer;
}
}
void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data,
uint8_t * p_pixel_buffer,
size_t cols,
size_t rows,
size_t colour_depth,
size_t size)
{
std::lock_guard<std::mutex> data_lock_guard(p_video_data->_data_lock);
// TODO: explain how data should be handled (see #86)
if (p_video_data->_running)
{
p_video_data->_cols = cols;
p_video_data->_rows = rows;
}
}
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE EnergyStorageDevice
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <cap/resistor_capacitor.h>
#include <boost/test/unit_test.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/export.hpp>
#include <sstream>
//BOOST_SERIALIZATION_ASSUME_ABSTRACT(cap::EnergyStorageDevice)
//BOOST_CLASS_EXPORT(cap::SeriesRC)
// list of valid inputs to build an EnergyStorageDevice
// These are meant as example
std::list<std::string> const valid_device_input = {
"series_rc.info",
"parallel_rc.info",
#ifdef WITH_DEAL_II
"super_capacitor.info",
#endif
};
BOOST_AUTO_TEST_CASE( test_factory )
{
for (auto const & filename : valid_device_input)
{
boost::property_tree::ptree ptree;
boost::property_tree::info_parser::read_info(filename, ptree);
BOOST_CHECK_NO_THROW(
cap::EnergyStorageDevice::build(
boost::mpi::communicator(), ptree) );
}
// invalid type must throw an exception
boost::property_tree::ptree ptree;
ptree.put("type", "InvalidDeviceType");
BOOST_CHECK_THROW(
cap::buildEnergyStorageDevice(
boost::mpi::communicator(), ptree ),
std::runtime_error );
}
// TODO: won't work for SuperCapacitor
#ifdef WITH_DEAL_II
BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_serialization, 1 )
#endif
BOOST_AUTO_TEST_CASE( test_serialization )
{
for (auto const & filename : valid_device_input)
{
boost::property_tree::ptree ptree;
boost::property_tree::info_parser::read_info(filename, ptree);
auto original_device = cap::buildEnergyStorageDevice(
boost::mpi::communicator(), ptree );
original_device->evolve_one_time_step_constant_voltage(0.1, 2.1);
double original_voltage;
double original_current;
original_device->get_voltage(original_voltage);
original_device->get_current(original_current);
try {
std::stringstream ss;
// save device
boost::archive::text_oarchive oa(ss);
oa.register_type<cap::SeriesRC>();
oa.register_type<cap::ParallelRC>();
oa<<original_device;
// print the content of the stream to the screen
std::cout<<ss.str()<<"\n";
BOOST_CHECK( !ss.str().empty() );
// restore device
boost::archive::text_iarchive ia(ss);
ia.register_type<cap::SeriesRC>();
ia.register_type<cap::ParallelRC>();
std::shared_ptr<cap::EnergyStorageDevice> restored_device;
ia>>restored_device;
double restored_voltage;
double restored_current;
restored_device->get_voltage(restored_voltage);
restored_device->get_current(restored_current);
BOOST_CHECK_EQUAL(original_voltage, restored_voltage);
BOOST_CHECK_EQUAL(original_current, restored_current);
} catch (boost::archive::archive_exception e) {
BOOST_TEST_MESSAGE("unable to serialize the device");
BOOST_TEST(false);
} catch (...) {
throw std::runtime_error("unexpected exception occured");
}
}
}
<commit_msg>add test/example of simple device inspector<commit_after>#define BOOST_TEST_MODULE EnergyStorageDevice
#define BOOST_TEST_MAIN
#include <cap/energy_storage_device.h>
#include <cap/resistor_capacitor.h>
#include <boost/test/unit_test.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/export.hpp>
#include <sstream>
//BOOST_SERIALIZATION_ASSUME_ABSTRACT(cap::EnergyStorageDevice)
//BOOST_CLASS_EXPORT(cap::SeriesRC)
// list of valid inputs to build an EnergyStorageDevice
// These are meant as example
std::list<std::string> const valid_device_input = {
"series_rc.info",
"parallel_rc.info",
#ifdef WITH_DEAL_II
"super_capacitor.info",
#endif
};
BOOST_AUTO_TEST_CASE( test_energy_storage_device_builders )
{
boost::mpi::communicator world;
for (auto const & filename : valid_device_input)
{
boost::property_tree::ptree ptree;
boost::property_tree::info_parser::read_info(filename, ptree);
BOOST_CHECK_NO_THROW(
cap::EnergyStorageDevice::build(world, ptree) );
}
// invalid type must throw an exception
boost::property_tree::ptree ptree;
ptree.put("type", "InvalidDeviceType");
BOOST_CHECK_THROW(
cap::EnergyStorageDevice::build(world, ptree),
std::runtime_error );
}
class ExampleInspector : public cap::EnergyStorageDeviceInspector
{
public:
// get the device type and set the voltage to 1.4 volt
void inspect(cap::EnergyStorageDevice * device)
{
// use dynamic_cast to find out the actual type
if (dynamic_cast<cap::SeriesRC*>(device) != nullptr)
_type = "SeriesRC";
else if (dynamic_cast<cap::ParallelRC*>(device) != nullptr)
_type = "ParallelRC";
else
throw std::runtime_error("not an equivalent circuit model");
// if we make ExampleInspector friend of the derived
// class for the EnergyStorageDevice we could virtually
// do anything
device->evolve_one_time_step_constant_voltage(1.0, 1.4);
}
// the type of the device last inspected
std::string _type;
};
BOOST_AUTO_TEST_CASE( test_energy_storage_device_inspectors )
{
std::string const filename = "series_rc.info";
boost::mpi::communicator world;
boost::property_tree::ptree ptree;
boost::property_tree::info_parser::read_info(filename, ptree);
auto device = cap::EnergyStorageDevice::build(world, ptree);
double voltage;
device->get_voltage(voltage);
BOOST_TEST( voltage != 1.4 );
ExampleInspector inspector;
device->inspect(&inspector);
BOOST_TEST( (inspector._type).compare("SeriesRC") == 0 );
device->get_voltage(voltage);
BOOST_TEST( voltage == 1.4 );
}
// TODO: won't work for SuperCapacitor
#ifdef WITH_DEAL_II
BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_serialization, 1 )
#endif
BOOST_AUTO_TEST_CASE( test_serialization )
{
for (auto const & filename : valid_device_input)
{
boost::property_tree::ptree ptree;
boost::property_tree::info_parser::read_info(filename, ptree);
auto original_device = cap::buildEnergyStorageDevice(
boost::mpi::communicator(), ptree );
original_device->evolve_one_time_step_constant_voltage(0.1, 2.1);
double original_voltage;
double original_current;
original_device->get_voltage(original_voltage);
original_device->get_current(original_current);
try {
std::stringstream ss;
// save device
boost::archive::text_oarchive oa(ss);
oa.register_type<cap::SeriesRC>();
oa.register_type<cap::ParallelRC>();
oa<<original_device;
// print the content of the stream to the screen
std::cout<<ss.str()<<"\n";
BOOST_CHECK( !ss.str().empty() );
// restore device
boost::archive::text_iarchive ia(ss);
ia.register_type<cap::SeriesRC>();
ia.register_type<cap::ParallelRC>();
std::shared_ptr<cap::EnergyStorageDevice> restored_device;
ia>>restored_device;
double restored_voltage;
double restored_current;
restored_device->get_voltage(restored_voltage);
restored_device->get_current(restored_current);
BOOST_CHECK_EQUAL(original_voltage, restored_voltage);
BOOST_CHECK_EQUAL(original_current, restored_current);
} catch (boost::archive::archive_exception e) {
BOOST_TEST_MESSAGE("unable to serialize the device");
BOOST_TEST(false);
} catch (...) {
throw std::runtime_error("unexpected exception occured");
}
}
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/Rpc.h>
#include <vw/Plate/IndexService.h>
#include <vw/Core/Stopwatch.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Log.h>
#include <signal.h>
#include <boost/format.hpp>
#include <google/protobuf/descriptor.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;
// ------------------------------ SIGNAL HANDLER -------------------------------
volatile bool process_messages = true;
volatile bool force_sync = false;
void sig_unexpected_shutdown(int sig_num) {
signal(sig_num, SIG_IGN);
process_messages = false;
signal(sig_num, sig_unexpected_shutdown);
}
void sig_sync(int sig_num) {
signal(sig_num, SIG_IGN);
force_sync = true;
signal(sig_num, sig_sync);
}
struct Options {
Url url;
std::string root;
float sync_interval;
bool debug;
bool help;
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void process_args(Options& opt, int argc, char *argv[]) {
po::options_description general_options("Runs a master index manager.\n\nGeneral Options:");
general_options.add_options()
("url", po::value(&opt.url), "Url to listen on")
("debug", po::bool_switch(&opt.debug)->default_value(false), "Allow server to die.")
("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message")
("sync-interval,s", po::value(&opt.sync_interval)->default_value(60.),
"Specify the time interval (in minutes) for automatically synchronizing the index to disk.");
po::options_description hidden_options("");
hidden_options.add_options()
("root-directory", po::value(&opt.root));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description p;
p.add("root-directory", -1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " --url <url> root_directory" << std::endl << std::endl;
usage << general_options << std::endl;
if(opt.help)
vw_throw(Usage() << usage.str());
if( vm.count("root-directory") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nError: must specify a root directory that contains plate files!");
}
if ( vm.count("url") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nMust specify a url to listen on");
}
}
int main(int argc, char** argv) {
Options opt;
try {
process_args(opt, argc, argv);
} catch (const Usage& u) {
std::cerr << u.what() << std::endl;
::exit(EXIT_FAILURE);
}
// Install Unix Signal Handlers. These will help us to gracefully
// recover and salvage the index under most unexpected error
// conditions.
signal(SIGINT, sig_unexpected_shutdown);
signal(SIGUSR1, sig_sync);
// Start the server task in another thread
RpcServer<IndexServiceImpl> server(opt.url, new IndexServiceImpl(opt.root));
server.set_debug(opt.debug);
vw_out(InfoMessage) << "Starting index server\n\n";
uint64 sync_interval_us = uint64(opt.sync_interval * 60000000);
uint64 t0 = Stopwatch::microtime(), t1;
uint64 next_sync = t0 + sync_interval_us;
size_t win = 0, lose = 0, draw = 0, total = 0;
boost::format status("qps[%7.1f] total[%9u] server_err[%9u] client_err[%9u]\r");
while(process_messages) {
if (server.error()) {
vw_out(InfoMessage) << "IO Thread has terminated with message: " << server.error() << "\n";
break;
}
bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync);
if (should_sync) {
vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "manual" : "auto") << ")\n";
uint64 s0 = Stopwatch::microtime();
server.impl()->sync();
uint64 s1 = Stopwatch::microtime();
next_sync = s1 + sync_interval_us;
vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n";
force_sync = false;
}
t1 = Stopwatch::microtime();
size_t win_dt, lose_dt, draw_dt, total_dt;
{
ThreadMap::Locked stats = server.stats();
win_dt = stats.get("msgs");
lose_dt = stats.get("server_error");
draw_dt = stats.get("client_error");
stats.clear();
}
total_dt = win_dt + lose_dt + draw_dt;
win += win_dt;
lose += lose_dt;
draw += draw_dt;
total += total_dt;
float dt = float(t1 - t0) / 1e6f;
t0 = t1;
vw_out(InfoMessage)
<< status % (float(total_dt)/dt) % total % lose % draw
<< std::flush;
Thread::sleep_ms(500);
}
vw_out(InfoMessage) << "\nShutting down the index service safely.\n";
server.stop();
server.impl()->sync();
return 0;
}
<commit_msg>make sure index_server catches SIGTERM, too<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/Plate/Rpc.h>
#include <vw/Plate/IndexService.h>
#include <vw/Core/Stopwatch.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Log.h>
#include <signal.h>
#include <boost/format.hpp>
#include <google/protobuf/descriptor.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
using namespace vw::platefile;
using namespace vw;
// ------------------------------ SIGNAL HANDLER -------------------------------
volatile bool process_messages = true;
volatile bool force_sync = false;
void sig_unexpected_shutdown(int sig_num) {
signal(sig_num, SIG_IGN);
process_messages = false;
signal(sig_num, sig_unexpected_shutdown);
}
void sig_sync(int sig_num) {
signal(sig_num, SIG_IGN);
force_sync = true;
signal(sig_num, sig_sync);
}
struct Options {
Url url;
std::string root;
float sync_interval;
bool debug;
bool help;
};
VW_DEFINE_EXCEPTION(Usage, Exception);
void process_args(Options& opt, int argc, char *argv[]) {
po::options_description general_options("Runs a master index manager.\n\nGeneral Options:");
general_options.add_options()
("url", po::value(&opt.url), "Url to listen on")
("debug", po::bool_switch(&opt.debug)->default_value(false), "Allow server to die.")
("help,h", po::bool_switch(&opt.help)->default_value(false), "Display this help message")
("sync-interval,s", po::value(&opt.sync_interval)->default_value(60.),
"Specify the time interval (in minutes) for automatically synchronizing the index to disk.");
po::options_description hidden_options("");
hidden_options.add_options()
("root-directory", po::value(&opt.root));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description p;
p.add("root-directory", -1);
po::variables_map vm;
po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " --url <url> root_directory" << std::endl << std::endl;
usage << general_options << std::endl;
if(opt.help)
vw_throw(Usage() << usage.str());
if( vm.count("root-directory") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nError: must specify a root directory that contains plate files!");
}
if ( vm.count("url") != 1 ) {
vw_throw(Usage() << usage.str()
<< "\n\nMust specify a url to listen on");
}
}
int main(int argc, char** argv) {
Options opt;
try {
process_args(opt, argc, argv);
} catch (const Usage& u) {
std::cerr << u.what() << std::endl;
::exit(EXIT_FAILURE);
}
// Install Unix Signal Handlers. These will help us to gracefully
// recover and salvage the index under most unexpected error
// conditions.
signal(SIGINT, sig_unexpected_shutdown);
signal(SIGTERM, sig_unexpected_shutdown);
signal(SIGUSR1, sig_sync);
// Start the server task in another thread
RpcServer<IndexServiceImpl> server(opt.url, new IndexServiceImpl(opt.root));
server.set_debug(opt.debug);
vw_out(InfoMessage) << "Starting index server\n\n";
uint64 sync_interval_us = uint64(opt.sync_interval * 60000000);
uint64 t0 = Stopwatch::microtime(), t1;
uint64 next_sync = t0 + sync_interval_us;
size_t win = 0, lose = 0, draw = 0, total = 0;
boost::format status("qps[%7.1f] total[%9u] server_err[%9u] client_err[%9u]\r");
while(process_messages) {
if (server.error()) {
vw_out(InfoMessage) << "IO Thread has terminated with message: " << server.error() << "\n";
break;
}
bool should_sync = force_sync || (Stopwatch::microtime() >= next_sync);
if (should_sync) {
vw_out(InfoMessage) << "\nStarting sync to disk. (" << (force_sync ? "manual" : "auto") << ")\n";
uint64 s0 = Stopwatch::microtime();
server.impl()->sync();
uint64 s1 = Stopwatch::microtime();
next_sync = s1 + sync_interval_us;
vw_out(InfoMessage) << "Sync complete (took " << float(s1-s0) / 1e6 << " seconds).\n";
force_sync = false;
}
t1 = Stopwatch::microtime();
size_t win_dt, lose_dt, draw_dt, total_dt;
{
ThreadMap::Locked stats = server.stats();
win_dt = stats.get("msgs");
lose_dt = stats.get("server_error");
draw_dt = stats.get("client_error");
stats.clear();
}
total_dt = win_dt + lose_dt + draw_dt;
win += win_dt;
lose += lose_dt;
draw += draw_dt;
total += total_dt;
float dt = float(t1 - t0) / 1e6f;
t0 = t1;
vw_out(InfoMessage)
<< status % (float(total_dt)/dt) % total % lose % draw
<< std::flush;
Thread::sleep_ms(500);
}
vw_out(InfoMessage) << "\nShutting down the index service safely.\n";
server.stop();
server.impl()->sync();
return 0;
}
<|endoftext|> |
<commit_before> /**
* \file main.cc
* \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
* \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars
* \copyright Copyright (c) 2017, The R2D2 Team
* \license See LICENSE
*/
#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include "databasemanager.hh"
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <iostream>
struct MFAuthentData {
uint8_t command_code;
uint8_t blockAddress;
uint8_t sectorKey[5];
uint8_t serialNumber[4];
};
int main(int argc, char **argv) {
#define USING_PIN // Comment out this rule if not using a pincode on your application
try {
std::string ip;
std::string username;
std::string password;
//int encryptionKey;
ConfigFileParser factory("database-config.txt");
factory.loadDatabaseSettings(ip, username, password);
MySql connection;
connection.connectTo(ip, username, password);
connection.selectDatabase("R2D2");
std::cout << "Made connection to the database\n";
wiringPiSetup();
wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
MFRC522 rfid;
rfid.PCD_Init();
//Keypad pinSetup
const int keypadRow[] = {15, 16, 1, 4};
const int keypadColumn[] = {8, 9, 7, 2};
//Keypad objects
MatrixKeypad keypad(keypadRow, keypadColumn, 4);
LedController led(0);
while (true) {
delay(1000);
std::cout << "\n\nWaiting for rfid tag: \n";
rfid.PICC_IsNewCardPresent();
rfid.PICC_ReadCardSerial();
// Hier moet het database gedeelte komen om te checken of je ID al in de database staat
std::string id;
for(byte i = 0; i < rfid.uid.size; ++i){
if(rfid.uid.uidByte[i] < 0x10){
id +=(char)rfid.uid.uidByte[i];
}
else{
id += (char)rfid.uid.uidByte[i];
}
}
DatabaseManager information;
if ( information.isCardInDatabase(id)){
std::cout << " id in database";
}
#ifdef USING_PIN
MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
continue;
//read pincode
byte bufferSize = (byte)18;
byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);
std::cout << "Readarray contains: \n";
for (int i = 0; i < 18; i++){
std::cout <<(int)readArray[i] << '\n';
}
//pincode invoeren
std::cout << "Input PIN and finish with #\n";
std::string value = keypad.getString();
// write pincode
byte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int index = 0;
for(auto c :value){
if (c >47 && c < 58 ){
int number = c - 48;
writeArray[index++] = (byte)number;
}
}
rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);
for (int i = 0; i < 16; i++){
std::cout <<(int)writeArray[i] << '\n';
}
#endif
rfid.PCD_StopCrypto1();
for(byte i = 0; i < rfid.uid.size; ++i){
if(rfid.uid.uidByte[i] < 0x10){
printf(" 0");
printf("%X",rfid.uid.uidByte[i]);
}
else{
printf(" ");
printf("%X", rfid.uid.uidByte[i]);
}
}
connection.executeQuery("SELECT * FROM RFID");
// std::cout << "Database information: "
// << database.getAllCardIdFromDatabase()
// << '\n';
led.blinkLed(1000);
}
} catch (const std::string &error) {
std::cerr << error << '\n';
exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "Something went wrong\n";
exit(EXIT_FAILURE);
}
return 0;
}
<commit_msg>[rfid-03] bug fix id from database<commit_after> /**
* \file main.cc
* \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
* \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars
* \copyright Copyright (c) 2017, The R2D2 Team
* \license See LICENSE
*/
#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include "databasemanager.hh"
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include <iostream>
struct MFAuthentData {
uint8_t command_code;
uint8_t blockAddress;
uint8_t sectorKey[5];
uint8_t serialNumber[4];
};
int main(int argc, char **argv) {
#define USING_PIN // Comment out this rule if not using a pincode on your application
try {
std::string ip;
std::string username;
std::string password;
//int encryptionKey;
ConfigFileParser factory("database-config.txt");
factory.loadDatabaseSettings(ip, username, password);
MySql connection;
connection.connectTo(ip, username, password);
connection.selectDatabase("R2D2");
std::cout << "Made connection to the database\n";
wiringPiSetup();
wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
MFRC522 rfid;
rfid.PCD_Init();
//Keypad pinSetup
const int keypadRow[] = {15, 16, 1, 4};
const int keypadColumn[] = {8, 9, 7, 2};
//Keypad objects
MatrixKeypad keypad(keypadRow, keypadColumn, 4);
LedController led(0);
while (true) {
delay(1000);
std::cout << "\n\nWaiting for rfid tag: \n";
rfid.PICC_IsNewCardPresent();
rfid.PICC_ReadCardSerial();
// Hier moet het database gedeelte komen om te checken of je ID al in de database staat
#ifdef USING_PIN
MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
continue;
//read pincode
std::string id;
for(byte i = 0; i < rfid.uid.size; ++i){
if(rfid.uid.uidByte[i] < 0x10){
id +=(char)rfid.uid.uidByte[i];
}
else{
id += (char)rfid.uid.uidByte[i];
}
}
DatabaseManager information;
if ( information.isCardInDatabase(id)){
std::cout << " id in database";
}
byte bufferSize = (byte)18;
byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);
std::cout << "Readarray contains: \n";
for (int i = 0; i < 18; i++){
std::cout <<(int)readArray[i] << '\n';
}
//pincode invoeren
std::cout << "Input PIN and finish with #\n";
std::string value = keypad.getString();
// write pincode
byte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int index = 0;
for(auto c :value){
if (c >47 && c < 58 ){
int number = c - 48;
writeArray[index++] = (byte)number;
}
}
rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);
for (int i = 0; i < 16; i++){
std::cout <<(int)writeArray[i] << '\n';
}
#endif
rfid.PCD_StopCrypto1();
for(byte i = 0; i < rfid.uid.size; ++i){
if(rfid.uid.uidByte[i] < 0x10){
printf(" 0");
printf("%X",rfid.uid.uidByte[i]);
}
else{
printf(" ");
printf("%X", rfid.uid.uidByte[i]);
}
}
connection.executeQuery("SELECT * FROM RFID");
// std::cout << "Database information: "
// << database.getAllCardIdFromDatabase()
// << '\n';
led.blinkLed(1000);
}
} catch (const std::string &error) {
std::cerr << error << '\n';
exit(EXIT_FAILURE);
} catch (...) {
std::cerr << "Something went wrong\n";
exit(EXIT_FAILURE);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Matthew Arsenault
*
* This is part of moor, a wrapper for libarchive
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "moor_build_config.hpp"
#include "types.hpp"
#include <archive_entry.h>
#include <cstdint>
#include <limits>
#include <vector>
namespace moor
{
// Non-owning references to archive*, archive_entry*
class MOOR_API ArchiveEntry
{
private:
archive* m_archive; // Archive the entry belongs to
archive_entry* m_entry;
static const int s_defaultExtractFlags;
bool extractDataImpl(archive* a,
unsigned char* ptr,
ssize_t size,
ssize_t entrySize);
int copyData(archive* ar, archive* aw);
public:
explicit ArchiveEntry(archive* a,
archive_entry* e = nullptr)
: m_archive(a),
m_entry(e) { }
operator archive_entry*()
{
return m_entry;
}
operator const archive_entry*() const
{
return m_entry;
}
archive_entry* entry()
{
return m_entry;
}
const archive_entry* entry() const
{
return m_entry;
}
template <class Resizeable>
bool extractData(Resizeable& out)
{
typedef typename Resizeable::value_type value_type;
if (!size_is_set())
{
return false;
}
std::int64_t entrySize = size();
if (entrySize < 0 || entrySize >= std::numeric_limits<ssize_t>::max())
{
return false;
}
out.resize(entrySize);
return extractDataImpl(m_archive,
reinterpret_cast<unsigned char*>(out.data()),
sizeof(value_type) * out.size(),
entrySize);
}
void skip();
bool extractData(std::vector<unsigned char>& out);
bool extractData(void* out, size_t size);
// Like extract data but extract to the given filepath instead
bool extractDisk(const std::string& rootPath);
void clear()
{
m_entry = archive_entry_clear(m_entry);
}
time_t atime() const
{
return archive_entry_atime(m_entry);
}
long atime_nsec() const
{
return archive_entry_atime_nsec(m_entry);
}
bool atime_is_set() const
{
return (archive_entry_atime_is_set(m_entry) != 0);
}
time_t birthtime() const
{
return archive_entry_birthtime(m_entry);
}
long birthtime_nsec() const
{
return archive_entry_birthtime_nsec(m_entry);
}
bool birthtime_is_set() const
{
return (archive_entry_birthtime_is_set(m_entry) != 0);
}
time_t ctime() const
{
return archive_entry_ctime(m_entry);
}
long ctime_nsec() const
{
return archive_entry_ctime_nsec(m_entry);
}
bool ctime_is_set() const
{
return (archive_entry_ctime_is_set(m_entry) != 0);
}
FileType filetype() const
{
return static_cast<FileType>(archive_entry_filetype(m_entry));
}
void fflags(unsigned long* set, unsigned long* clear)
{
archive_entry_fflags(m_entry, set, clear);
}
std::int64_t gid() const
{
return archive_entry_gid(m_entry);
}
const char* gname() const
{
return archive_entry_gname(m_entry);
}
const wchar_t* gname_w() const
{
return archive_entry_gname_w(m_entry);
}
const char* hardlink() const
{
return archive_entry_hardlink(m_entry);
}
const wchar_t* hardlink_w() const
{
return archive_entry_hardlink_w(m_entry);
}
std::int64_t ino() const
{
return archive_entry_ino(m_entry);
}
std::int64_t ino64() const
{
return archive_entry_ino64(m_entry);
}
bool ino_is_set() const
{
return (archive_entry_ino_is_set(m_entry) != 0);
}
__LA_MODE_T mode() const
{
return archive_entry_mode(m_entry);
}
time_t mtime() const
{
return archive_entry_mtime(m_entry);
}
long mtime_nsec() const
{
return archive_entry_mtime_nsec(m_entry);
}
bool mtime_is_set() const
{
return (archive_entry_mtime_is_set(m_entry) != 0);
}
unsigned int nlink() const
{
return archive_entry_nlink(m_entry);
}
const char* pathname() const
{
return archive_entry_pathname(m_entry);
}
const wchar_t* pathname_w() const
{
return archive_entry_pathname_w(m_entry);
}
__LA_MODE_T perm() const
{
return archive_entry_perm(m_entry);
}
const char* sourcepath() const
{
return archive_entry_sourcepath(m_entry);
}
const wchar_t* sourcepath_w() const
{
return archive_entry_sourcepath_w(m_entry);
}
std::int64_t size() const
{
return archive_entry_size(m_entry);
}
bool size_is_set() const
{
return archive_entry_size_is_set(m_entry);
}
const char* strmode() const
{
return archive_entry_strmode(m_entry);
}
const char* symlink() const
{
return archive_entry_symlink(m_entry);
}
const wchar_t* symlink_w() const
{
return archive_entry_symlink_w(m_entry);
}
std::int64_t uid() const
{
return archive_entry_uid(m_entry);
}
const char* uname() const
{
return archive_entry_uname(m_entry);
}
const wchar_t* uname_w() const
{
return archive_entry_uname_w(m_entry);
}
void set_atime(std::int64_t t, long x)
{
archive_entry_set_atime(m_entry, t, x);
}
void unset_atime()
{
archive_entry_unset_atime(m_entry);
}
void set_birthtime(std::int64_t t, long x)
{
archive_entry_set_birthtime(m_entry, t, x);
}
void unset_birthtime()
{
archive_entry_unset_birthtime(m_entry);
}
void set_ctime(std::int64_t t, long x)
{
archive_entry_set_ctime(m_entry, t, x);
}
void unset_ctime()
{
archive_entry_unset_ctime(m_entry);
}
void set_filetype(FileType type)
{
archive_entry_set_filetype(m_entry, static_cast<int>(type));
}
void set_fflags(long set, long clear)
{
archive_entry_set_fflags(m_entry, set, clear);
}
void set_gid(std::int64_t g)
{
archive_entry_set_gid(m_entry, g);
}
void set_gname(const char* n)
{
archive_entry_set_gname(m_entry, n);
}
void set_hardlink(const char* s)
{
archive_entry_set_hardlink(m_entry, s);
}
void set_ino(std::int64_t i)
{
archive_entry_set_ino(m_entry, i);
}
void set_ino64(std::int64_t i)
{
archive_entry_set_ino64(m_entry, i);
}
void set_mode(__LA_MODE_T mode)
{
archive_entry_set_mode(m_entry, mode);
}
void set_mtime(time_t t, long i)
{
archive_entry_set_mtime(m_entry, t, i);
}
void unset_mtime()
{
archive_entry_unset_mtime(m_entry);
}
void set_nlink(unsigned int n)
{
archive_entry_set_nlink(m_entry, n);
}
void set_pathname(const char* n)
{
archive_entry_set_pathname(m_entry, n);
}
void set_perm(__LA_MODE_T perm)
{
archive_entry_set_perm(m_entry, perm);
}
void set_size(std::int64_t s)
{
archive_entry_set_size(m_entry, s);
}
void unset_size()
{
archive_entry_unset_size(m_entry);
}
void set_symlink(const char* s)
{
archive_entry_set_symlink(m_entry, s);
}
void set_uid(std::int64_t i)
{
archive_entry_set_uid(m_entry, i);
}
void set_uname(const char* s)
{
archive_entry_set_uname(m_entry, s);
}
int update_uname_utf8(const char* s)
{
return archive_entry_update_uname_utf8(m_entry, s);
}
};
}
<commit_msg>Make method static<commit_after>/*
* Copyright (c) 2013 Matthew Arsenault
*
* This is part of moor, a wrapper for libarchive
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "moor_build_config.hpp"
#include "types.hpp"
#include <archive_entry.h>
#include <cstdint>
#include <limits>
#include <vector>
namespace moor
{
// Non-owning references to archive*, archive_entry*
class MOOR_API ArchiveEntry
{
private:
archive* m_archive; // Archive the entry belongs to
archive_entry* m_entry;
static const int s_defaultExtractFlags;
bool extractDataImpl(archive* a,
unsigned char* ptr,
ssize_t size,
ssize_t entrySize);
static int copyData(archive* ar, archive* aw);
public:
explicit ArchiveEntry(archive* a,
archive_entry* e = nullptr)
: m_archive(a),
m_entry(e) { }
operator archive_entry*()
{
return m_entry;
}
operator const archive_entry*() const
{
return m_entry;
}
archive_entry* entry()
{
return m_entry;
}
const archive_entry* entry() const
{
return m_entry;
}
template <class Resizeable>
bool extractData(Resizeable& out)
{
typedef typename Resizeable::value_type value_type;
if (!size_is_set())
{
return false;
}
std::int64_t entrySize = size();
if (entrySize < 0 || entrySize >= std::numeric_limits<ssize_t>::max())
{
return false;
}
out.resize(entrySize);
return extractDataImpl(m_archive,
reinterpret_cast<unsigned char*>(out.data()),
sizeof(value_type) * out.size(),
entrySize);
}
void skip();
bool extractData(std::vector<unsigned char>& out);
bool extractData(void* out, size_t size);
// Like extract data but extract to the given filepath instead
bool extractDisk(const std::string& rootPath);
void clear()
{
m_entry = archive_entry_clear(m_entry);
}
time_t atime() const
{
return archive_entry_atime(m_entry);
}
long atime_nsec() const
{
return archive_entry_atime_nsec(m_entry);
}
bool atime_is_set() const
{
return (archive_entry_atime_is_set(m_entry) != 0);
}
time_t birthtime() const
{
return archive_entry_birthtime(m_entry);
}
long birthtime_nsec() const
{
return archive_entry_birthtime_nsec(m_entry);
}
bool birthtime_is_set() const
{
return (archive_entry_birthtime_is_set(m_entry) != 0);
}
time_t ctime() const
{
return archive_entry_ctime(m_entry);
}
long ctime_nsec() const
{
return archive_entry_ctime_nsec(m_entry);
}
bool ctime_is_set() const
{
return (archive_entry_ctime_is_set(m_entry) != 0);
}
FileType filetype() const
{
return static_cast<FileType>(archive_entry_filetype(m_entry));
}
void fflags(unsigned long* set, unsigned long* clear)
{
archive_entry_fflags(m_entry, set, clear);
}
std::int64_t gid() const
{
return archive_entry_gid(m_entry);
}
const char* gname() const
{
return archive_entry_gname(m_entry);
}
const wchar_t* gname_w() const
{
return archive_entry_gname_w(m_entry);
}
const char* hardlink() const
{
return archive_entry_hardlink(m_entry);
}
const wchar_t* hardlink_w() const
{
return archive_entry_hardlink_w(m_entry);
}
std::int64_t ino() const
{
return archive_entry_ino(m_entry);
}
std::int64_t ino64() const
{
return archive_entry_ino64(m_entry);
}
bool ino_is_set() const
{
return (archive_entry_ino_is_set(m_entry) != 0);
}
__LA_MODE_T mode() const
{
return archive_entry_mode(m_entry);
}
time_t mtime() const
{
return archive_entry_mtime(m_entry);
}
long mtime_nsec() const
{
return archive_entry_mtime_nsec(m_entry);
}
bool mtime_is_set() const
{
return (archive_entry_mtime_is_set(m_entry) != 0);
}
unsigned int nlink() const
{
return archive_entry_nlink(m_entry);
}
const char* pathname() const
{
return archive_entry_pathname(m_entry);
}
const wchar_t* pathname_w() const
{
return archive_entry_pathname_w(m_entry);
}
__LA_MODE_T perm() const
{
return archive_entry_perm(m_entry);
}
const char* sourcepath() const
{
return archive_entry_sourcepath(m_entry);
}
const wchar_t* sourcepath_w() const
{
return archive_entry_sourcepath_w(m_entry);
}
std::int64_t size() const
{
return archive_entry_size(m_entry);
}
bool size_is_set() const
{
return archive_entry_size_is_set(m_entry);
}
const char* strmode() const
{
return archive_entry_strmode(m_entry);
}
const char* symlink() const
{
return archive_entry_symlink(m_entry);
}
const wchar_t* symlink_w() const
{
return archive_entry_symlink_w(m_entry);
}
std::int64_t uid() const
{
return archive_entry_uid(m_entry);
}
const char* uname() const
{
return archive_entry_uname(m_entry);
}
const wchar_t* uname_w() const
{
return archive_entry_uname_w(m_entry);
}
void set_atime(std::int64_t t, long x)
{
archive_entry_set_atime(m_entry, t, x);
}
void unset_atime()
{
archive_entry_unset_atime(m_entry);
}
void set_birthtime(std::int64_t t, long x)
{
archive_entry_set_birthtime(m_entry, t, x);
}
void unset_birthtime()
{
archive_entry_unset_birthtime(m_entry);
}
void set_ctime(std::int64_t t, long x)
{
archive_entry_set_ctime(m_entry, t, x);
}
void unset_ctime()
{
archive_entry_unset_ctime(m_entry);
}
void set_filetype(FileType type)
{
archive_entry_set_filetype(m_entry, static_cast<int>(type));
}
void set_fflags(long set, long clear)
{
archive_entry_set_fflags(m_entry, set, clear);
}
void set_gid(std::int64_t g)
{
archive_entry_set_gid(m_entry, g);
}
void set_gname(const char* n)
{
archive_entry_set_gname(m_entry, n);
}
void set_hardlink(const char* s)
{
archive_entry_set_hardlink(m_entry, s);
}
void set_ino(std::int64_t i)
{
archive_entry_set_ino(m_entry, i);
}
void set_ino64(std::int64_t i)
{
archive_entry_set_ino64(m_entry, i);
}
void set_mode(__LA_MODE_T mode)
{
archive_entry_set_mode(m_entry, mode);
}
void set_mtime(time_t t, long i)
{
archive_entry_set_mtime(m_entry, t, i);
}
void unset_mtime()
{
archive_entry_unset_mtime(m_entry);
}
void set_nlink(unsigned int n)
{
archive_entry_set_nlink(m_entry, n);
}
void set_pathname(const char* n)
{
archive_entry_set_pathname(m_entry, n);
}
void set_perm(__LA_MODE_T perm)
{
archive_entry_set_perm(m_entry, perm);
}
void set_size(std::int64_t s)
{
archive_entry_set_size(m_entry, s);
}
void unset_size()
{
archive_entry_unset_size(m_entry);
}
void set_symlink(const char* s)
{
archive_entry_set_symlink(m_entry, s);
}
void set_uid(std::int64_t i)
{
archive_entry_set_uid(m_entry, i);
}
void set_uname(const char* s)
{
archive_entry_set_uname(m_entry, s);
}
int update_uname_utf8(const char* s)
{
return archive_entry_update_uname_utf8(m_entry, s);
}
};
}
<|endoftext|> |
<commit_before><commit_msg>corrected stream reading<commit_after><|endoftext|> |
<commit_before>#ifndef ITER_DROPWHILE_H_
#define ITER_DROPWHILE_H_
#include <iterbase.hpp>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename FilterFunc, typename Container>
class DropWhile;
template <typename FilterFunc, typename Container>
DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class DropWhile {
private:
Container container;
FilterFunc filter_func;
friend DropWhile dropwhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend DropWhile<FF, std::initializer_list<T>> dropwhile(
FF, std::initializer_list<T>);
DropWhile(FilterFunc filter_func, Container container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
FilterFunc filter_func;
// skip all values for which the predicate is true
void skip_passes() {
while (this->sub_iter != this->sub_end
&& this->filter_func(*this->sub_iter)) {
++this->sub_iter;
}
}
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
this->skip_passes();
}
iterator_deref<Container> operator*() const {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
template <typename FilterFunc, typename Container>
DropWhile<FilterFunc, Container> dropwhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif
<commit_msg>eliminates extra moves<commit_after>#ifndef ITER_DROPWHILE_H_
#define ITER_DROPWHILE_H_
#include <iterbase.hpp>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename FilterFunc, typename Container>
class DropWhile;
template <typename FilterFunc, typename Container>
DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class DropWhile {
private:
Container container;
FilterFunc filter_func;
friend DropWhile dropwhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend DropWhile<FF, std::initializer_list<T>> dropwhile(
FF, std::initializer_list<T>);
DropWhile(FilterFunc filter_func, Container&& container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
FilterFunc filter_func;
// skip all values for which the predicate is true
void skip_passes() {
while (this->sub_iter != this->sub_end
&& this->filter_func(*this->sub_iter)) {
++this->sub_iter;
}
}
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
this->skip_passes();
}
iterator_deref<Container> operator*() {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
template <typename FilterFunc, typename Container>
DropWhile<FilterFunc, Container> dropwhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/widgets/layout.h"
#include <vector>
#include "moui/widgets/scroll_view.h"
#include "moui/widgets/widget.h"
namespace moui {
Layout::Layout() : adjusts_size_to_fit_contents_(false), bottom_padding_(0),
left_padding_(0), right_padding_(0),
should_rearrange_cells_(false), spacing_(0),
top_padding_(0) {
set_is_opaque(false);
}
Layout::~Layout() {
for (Widget* cell : GetCells())
delete cell;
}
// When adding a child widget, the child is actually added to a newly created
// cell widget.
void Layout::AddChild(Widget* child) {
auto cell = new Widget(false);
cell->set_is_opaque(false);
cell->AddChild(child);
ScrollView::AddChild(cell);
child->set_parent(this);
}
// Populates and returns a list of valid cells. Cells are actually the children
// of the content view's children of the inherited `ScrollView` class. Also,
// if `RemoveFromParent()` was called from one of the actual managed widgets,
// its corresponded cell will contain no child. And it's a good timing to
// free and remove the cell when this situation is detected.
std::vector<Widget*> Layout::GetCells() {
std::vector<Widget*> cells;
for (Widget* cell : reinterpret_cast<ScrollView*>(this)->children()) {
if (cell->children().size() != 1) {
cell->RemoveFromParent();
delete cell;
continue;
}
cells.push_back(cell);
}
return cells;
}
// Checks if there is any difference between the current child widgets and the
// managed widgets. If it is, the child widgets should be rearranged.
bool Layout::ShouldRearrangeCells() {
if (should_rearrange_cells_)
return true;
std::vector<Widget*> cells = GetCells();
if (cells.size() != managed_widgets_.size()) {
should_rearrange_cells_ = true;
return true;
}
int index = 0;
for (Widget* cell : cells) {
Widget* widget = cell->children().at(0);
Size occupied_size;
widget->GetOccupiedSpace(&occupied_size);
ManagedWidget managed_widget = managed_widgets_[index++];
if (managed_widget.widget != widget ||
managed_widget.occupied_size.width != occupied_size.width ||
managed_widget.occupied_size.height != occupied_size.height) {
should_rearrange_cells_ = true;
return true;
}
}
return false;
}
void Layout::UpdateContentSize(const float width, const float height) {
SetContentViewSize(width, height);
if (adjusts_size_to_fit_contents_) {
SetWidth(width);
SetHeight(height);
}
}
bool Layout::WidgetViewWillRender(NVGcontext* context) {
if (!ShouldRearrangeCells()) {
return ScrollView::WidgetViewWillRender(context);
}
should_rearrange_cells_ = false;
// Updates managed widgets.
managed_widgets_.clear();
for (Widget* cell : GetCells()) {
Widget* widget = cell->children().at(0);
Size occupied_size;
widget->GetOccupiedSpace(&occupied_size);
managed_widgets_.push_back({widget, occupied_size, cell});
}
ArrangeCells(managed_widgets_);
return false;
}
std::vector<Widget*>& Layout::children() {
managed_children_.clear();
for (Widget* cell : GetCells()) {
if (cell->children().size() == 1)
managed_children_.push_back(cell->children().at(0));
}
return managed_children_;
}
void Layout::set_bottom_padding(const float padding) {
if (padding == bottom_padding_)
return;
bottom_padding_ = padding;
Redraw();
}
void Layout::set_left_padding(const float padding) {
if (padding == left_padding_)
return;
left_padding_ = padding;
Redraw();
}
void Layout::set_right_padding(const float padding) {
if (padding == right_padding_)
return;
right_padding_ = padding;
Redraw();
}
void Layout::set_spacing(const float spacing) {
if (spacing == spacing_)
return;
spacing_ = spacing;
Redraw();
}
void Layout::set_top_padding(const float padding) {
if (padding == top_padding_)
return;
top_padding_ = padding;
Redraw();
}
} // namespace moui
<commit_msg>Fixes the `Layout::GetCells()` method.<commit_after>// Copyright (c) 2014 Ollix. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/widgets/layout.h"
#include <vector>
#include "moui/widgets/scroll_view.h"
#include "moui/widgets/widget.h"
namespace moui {
Layout::Layout() : adjusts_size_to_fit_contents_(false), bottom_padding_(0),
left_padding_(0), right_padding_(0),
should_rearrange_cells_(false), spacing_(0),
top_padding_(0) {
set_is_opaque(false);
}
Layout::~Layout() {
for (Widget* cell : GetCells())
delete cell;
}
// When adding a child widget, the child is actually added to a newly created
// cell widget.
void Layout::AddChild(Widget* child) {
auto cell = new Widget(false);
cell->set_is_opaque(false);
cell->AddChild(child);
ScrollView::AddChild(cell);
child->set_parent(this);
}
// Populates and returns a list of valid cells. Cells are actually the children
// of the content view's children of the inherited `ScrollView` class. Also,
// if `RemoveFromParent()` was called from one of the actual managed widgets,
// its corresponded cell will contain no child. And it's a good timing to
// free and remove the cell when this situation is detected.
std::vector<Widget*> Layout::GetCells() {
std::vector<Widget*> valid_cells;
std::vector<Widget*> stale_cells;
for (Widget* cell : reinterpret_cast<ScrollView*>(this)->children()) {
if (cell->children().size() == 1)
valid_cells.push_back(cell);
else
stale_cells.push_back(cell);
}
// Frees stale cells.
for (auto it = stale_cells.begin(); it != stale_cells.end(); ++it) {
Widget* cell = reinterpret_cast<Widget*>(*it);
cell->RemoveFromParent();
delete cell;
}
return valid_cells;
}
// Checks if there is any difference between the current child widgets and the
// managed widgets. If it is, the child widgets should be rearranged.
bool Layout::ShouldRearrangeCells() {
if (should_rearrange_cells_)
return true;
std::vector<Widget*> cells = GetCells();
if (cells.size() != managed_widgets_.size()) {
should_rearrange_cells_ = true;
return true;
}
int index = 0;
for (Widget* cell : cells) {
Widget* widget = cell->children().at(0);
Size occupied_size;
widget->GetOccupiedSpace(&occupied_size);
ManagedWidget managed_widget = managed_widgets_[index++];
if (managed_widget.widget != widget ||
managed_widget.occupied_size.width != occupied_size.width ||
managed_widget.occupied_size.height != occupied_size.height) {
should_rearrange_cells_ = true;
return true;
}
}
return false;
}
void Layout::UpdateContentSize(const float width, const float height) {
SetContentViewSize(width, height);
if (adjusts_size_to_fit_contents_) {
SetWidth(width);
SetHeight(height);
}
}
bool Layout::WidgetViewWillRender(NVGcontext* context) {
if (!ShouldRearrangeCells()) {
return ScrollView::WidgetViewWillRender(context);
}
should_rearrange_cells_ = false;
// Updates managed widgets.
managed_widgets_.clear();
for (Widget* cell : GetCells()) {
Widget* widget = cell->children().at(0);
Size occupied_size;
widget->GetOccupiedSpace(&occupied_size);
managed_widgets_.push_back({widget, occupied_size, cell});
}
ArrangeCells(managed_widgets_);
return false;
}
std::vector<Widget*>& Layout::children() {
managed_children_.clear();
for (Widget* cell : GetCells()) {
if (cell->children().size() == 1)
managed_children_.push_back(cell->children().at(0));
}
return managed_children_;
}
void Layout::set_bottom_padding(const float padding) {
if (padding == bottom_padding_)
return;
bottom_padding_ = padding;
Redraw();
}
void Layout::set_left_padding(const float padding) {
if (padding == left_padding_)
return;
left_padding_ = padding;
Redraw();
}
void Layout::set_right_padding(const float padding) {
if (padding == right_padding_)
return;
right_padding_ = padding;
Redraw();
}
void Layout::set_spacing(const float spacing) {
if (spacing == spacing_)
return;
spacing_ = spacing;
Redraw();
}
void Layout::set_top_padding(const float padding) {
if (padding == top_padding_)
return;
top_padding_ = padding;
Redraw();
}
} // namespace moui
<|endoftext|> |
<commit_before><commit_msg>Disable JingleSessionTests on Windows<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include <mach/mach_time.h>
double Timing::GetTickFrequency()
{
mach_timebase_info_data_t timeInfo;
mach_timebase_info(&timeInfo);
uint64_t numer = timeInfo.numer;
uint64_t denom = timeInfo.denom;
return (double)numer / (double)denom;
}
uint64_t Timing::GetTick()
{
return mach_absolute_time();
}
<commit_msg>Fix apple GetTickFrequency not calculating ratio for seconds<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include <mach/mach_time.h>
double Timing::GetTickFrequency()
{
mach_timebase_info_data_t timeInfo;
mach_timebase_info(&timeInfo);
uint64_t numer = timeInfo.numer;
uint64_t denom = timeInfo.denom;
return ((double)numer / (double)denom) * 1000000.0;
}
uint64_t Timing::GetTick()
{
return mach_absolute_time();
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "harness/compat.h"
#include "harness/testHarness.h"
#include "procs.h"
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32)
#include <unistd.h>
#endif
test_definition test_list[] = {
ADD_TEST(load_program_source),
ADD_TEST(load_multistring_source),
ADD_TEST(load_two_kernel_source),
ADD_TEST(load_null_terminated_source),
ADD_TEST(load_null_terminated_multi_line_source),
ADD_TEST(load_null_terminated_partial_multi_line_source),
ADD_TEST(load_discreet_length_source),
ADD_TEST(get_program_source),
ADD_TEST(get_program_build_info),
ADD_TEST(get_program_info),
ADD_TEST(large_compile),
ADD_TEST(async_build),
ADD_TEST(options_build_optimizations),
ADD_TEST(options_build_macro),
ADD_TEST(options_build_macro_existence),
ADD_TEST(options_include_directory),
ADD_TEST(options_denorm_cache),
ADD_TEST(preprocessor_define_udef),
ADD_TEST(preprocessor_include),
ADD_TEST(preprocessor_line_error),
ADD_TEST(preprocessor_pragma),
ADD_TEST(compiler_defines_for_extensions),
ADD_TEST(image_macro),
ADD_TEST(simple_compile_only),
ADD_TEST(simple_static_compile_only),
ADD_TEST(simple_extern_compile_only),
ADD_TEST(simple_compile_with_callback),
ADD_TEST(simple_embedded_header_compile),
ADD_TEST(simple_link_only),
ADD_TEST(two_file_regular_variable_access),
ADD_TEST(two_file_regular_struct_access),
ADD_TEST(two_file_regular_function_access),
ADD_TEST(simple_link_with_callback),
ADD_TEST(simple_embedded_header_link),
ADD_TEST(execute_after_simple_compile_and_link),
ADD_TEST(execute_after_simple_compile_and_link_no_device_info),
ADD_TEST(execute_after_simple_compile_and_link_with_defines),
ADD_TEST(execute_after_simple_compile_and_link_with_callbacks),
ADD_TEST(execute_after_simple_library_with_link),
ADD_TEST(execute_after_two_file_link),
ADD_TEST(execute_after_embedded_header_link),
ADD_TEST(execute_after_included_header_link),
ADD_TEST(execute_after_serialize_reload_object),
ADD_TEST(execute_after_serialize_reload_library),
ADD_TEST(simple_library_only),
ADD_TEST(simple_library_with_callback),
ADD_TEST(simple_library_with_link),
ADD_TEST(two_file_link),
ADD_TEST(multi_file_libraries),
ADD_TEST(multiple_files),
ADD_TEST(multiple_libraries),
ADD_TEST(multiple_files_multiple_libraries),
ADD_TEST(multiple_embedded_headers),
ADD_TEST(program_binary_type),
ADD_TEST(compile_and_link_status_options_log),
ADD_TEST_VERSION(pragma_unroll, Version(2, 0)),
ADD_TEST_VERSION(features_macro, Version(3, 0)),
ADD_TEST(unload_valid),
ADD_TEST(unload_invalid),
ADD_TEST(unload_repeated),
ADD_TEST(unload_compile_unload_link),
ADD_TEST(unload_build_unload_create_kernel),
ADD_TEST(unload_link_different),
ADD_TEST(unload_build_threaded),
ADD_TEST(unload_build_info),
ADD_TEST(unload_program_binaries),
};
const int test_num = ARRAY_SIZE(test_list);
int main(int argc, const char *argv[])
{
return runTestHarness(argc, argv, test_num, test_list, false, false, 0);
}
<commit_msg>temporarily disable the unload_invalid test case (#978)<commit_after>//
// Copyright (c) 2017 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "harness/compat.h"
#include "harness/testHarness.h"
#include "procs.h"
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32)
#include <unistd.h>
#endif
test_definition test_list[] = {
ADD_TEST(load_program_source),
ADD_TEST(load_multistring_source),
ADD_TEST(load_two_kernel_source),
ADD_TEST(load_null_terminated_source),
ADD_TEST(load_null_terminated_multi_line_source),
ADD_TEST(load_null_terminated_partial_multi_line_source),
ADD_TEST(load_discreet_length_source),
ADD_TEST(get_program_source),
ADD_TEST(get_program_build_info),
ADD_TEST(get_program_info),
ADD_TEST(large_compile),
ADD_TEST(async_build),
ADD_TEST(options_build_optimizations),
ADD_TEST(options_build_macro),
ADD_TEST(options_build_macro_existence),
ADD_TEST(options_include_directory),
ADD_TEST(options_denorm_cache),
ADD_TEST(preprocessor_define_udef),
ADD_TEST(preprocessor_include),
ADD_TEST(preprocessor_line_error),
ADD_TEST(preprocessor_pragma),
ADD_TEST(compiler_defines_for_extensions),
ADD_TEST(image_macro),
ADD_TEST(simple_compile_only),
ADD_TEST(simple_static_compile_only),
ADD_TEST(simple_extern_compile_only),
ADD_TEST(simple_compile_with_callback),
ADD_TEST(simple_embedded_header_compile),
ADD_TEST(simple_link_only),
ADD_TEST(two_file_regular_variable_access),
ADD_TEST(two_file_regular_struct_access),
ADD_TEST(two_file_regular_function_access),
ADD_TEST(simple_link_with_callback),
ADD_TEST(simple_embedded_header_link),
ADD_TEST(execute_after_simple_compile_and_link),
ADD_TEST(execute_after_simple_compile_and_link_no_device_info),
ADD_TEST(execute_after_simple_compile_and_link_with_defines),
ADD_TEST(execute_after_simple_compile_and_link_with_callbacks),
ADD_TEST(execute_after_simple_library_with_link),
ADD_TEST(execute_after_two_file_link),
ADD_TEST(execute_after_embedded_header_link),
ADD_TEST(execute_after_included_header_link),
ADD_TEST(execute_after_serialize_reload_object),
ADD_TEST(execute_after_serialize_reload_library),
ADD_TEST(simple_library_only),
ADD_TEST(simple_library_with_callback),
ADD_TEST(simple_library_with_link),
ADD_TEST(two_file_link),
ADD_TEST(multi_file_libraries),
ADD_TEST(multiple_files),
ADD_TEST(multiple_libraries),
ADD_TEST(multiple_files_multiple_libraries),
ADD_TEST(multiple_embedded_headers),
ADD_TEST(program_binary_type),
ADD_TEST(compile_and_link_status_options_log),
ADD_TEST_VERSION(pragma_unroll, Version(2, 0)),
ADD_TEST_VERSION(features_macro, Version(3, 0)),
ADD_TEST(unload_valid),
// ADD_TEST(unload_invalid), // disabling temporarily, see GitHub #977
ADD_TEST(unload_repeated),
ADD_TEST(unload_compile_unload_link),
ADD_TEST(unload_build_unload_create_kernel),
ADD_TEST(unload_link_different),
ADD_TEST(unload_build_threaded),
ADD_TEST(unload_build_info),
ADD_TEST(unload_program_binaries),
};
const int test_num = ARRAY_SIZE(test_list);
int main(int argc, const char *argv[])
{
return runTestHarness(argc, argv, test_num, test_list, false, false, 0);
}
<|endoftext|> |
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include <chrono>
#include <cinttypes>
#include <future>
#include <memory>
#include <stdexcept>
#include <string>
#include "gtest/gtest.h"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/rclcpp.hpp"
#include "test_rclcpp/utils.hpp"
#include "test_rclcpp/msg/u_int32.hpp"
#include "test_rclcpp/srv/add_two_ints.hpp"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
using namespace std::chrono_literals;
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), recursive_spin_call) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("recursive_spin_call");
auto timer = node->create_wall_timer(
0s,
[&executor]() {
ASSERT_THROW(executor.spin_some(), std::runtime_error);
ASSERT_THROW(executor.spin_once(), std::runtime_error);
ASSERT_THROW(executor.spin(), std::runtime_error);
executor.cancel();
});
executor.add_node(node);
executor.spin();
}
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), spin_some_max_duration) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("spin_some_max_duration");
auto timer = node->create_wall_timer(
0s,
[]() {
// Do nothing
});
executor.add_node(node);
const auto max_duration = 10ms;
const auto start = std::chrono::steady_clock::now();
executor.spin_some(max_duration);
const auto end = std::chrono::steady_clock::now();
ASSERT_LT(max_duration, end - start);
ASSERT_GT(max_duration + 5ms, end - start);
}
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multithreaded_spin_call) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("multithreaded_spin_call");
std::mutex m;
bool ready = false;
std::condition_variable cv;
std::thread t(
[&executor, &m, &cv, &ready]() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [&ready] {return ready;});
ASSERT_THROW(executor.spin_some(), std::runtime_error);
ASSERT_THROW(executor.spin_once(), std::runtime_error);
ASSERT_THROW(executor.spin(), std::runtime_error);
executor.cancel();
});
auto timer = node->create_wall_timer(
0s,
[&m, &cv, &ready]() {
if (!ready) {
{
std::lock_guard<std::mutex> lock(m);
ready = true;
}
cv.notify_one();
}
});
executor.add_node(node);
executor.spin();
t.join();
}
// Try spinning 2 single-threaded executors in two separate threads.
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multiple_executors) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
std::atomic_uint counter1;
counter1 = 0;
std::atomic_uint counter2;
counter2 = 0;
const uint32_t counter_goal = 20;
// Initialize executor 1.
rclcpp::executors::SingleThreadedExecutor executor1;
// I'm not a huge fan of unspecified capture variables in a lambda, but it
// is necessary in this case. On MacOS High Sierra and later, clang
// complains if we try to pass "counter_goal" as a specific lambda capture
// since it is a const. On the other hand, MSVC 2017 (19.12.25834.0)
// complains if you do *not* have the capture. To let both compilers be
// happy, we just let the compiler figure out the captures it wants; this
// is doubly OK because this is just for a test.
auto callback1 = [&]() {
if (counter1 == counter_goal) {
executor1.cancel();
return;
}
++counter1;
};
auto node1 = rclcpp::Node::make_shared("multiple_executors_1");
auto timer1 = node1->create_wall_timer(1ms, callback1);
executor1.add_node(node1);
// Initialize executor 2.
rclcpp::executors::SingleThreadedExecutor executor2;
// This lambda has the same problem & solution as the callback1 lambda above.
auto callback2 = [&]() {
if (counter2 == counter_goal) {
executor2.cancel();
return;
}
++counter2;
};
auto node2 = rclcpp::Node::make_shared("multiple_executors_2");
auto timer2 = node2->create_wall_timer(1ms, callback2);
executor2.add_node(node2);
auto spin_executor2 = [&executor2]() {
executor2.spin();
};
// Launch both executors
std::thread execution_thread(spin_executor2);
executor1.spin();
execution_thread.join();
EXPECT_EQ(counter1.load(), counter_goal);
EXPECT_EQ(counter2.load(), counter_goal);
// Try to add node1 to executor2. It should throw, since node1 was already added to executor1.
ASSERT_THROW(executor2.add_node(node1), std::runtime_error);
}
// Check that the executor is notified when a node adds a new timer, publisher, subscription,
// service or client.
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), notify) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto executor_spin_lambda = [&executor]() {
executor.spin();
};
auto node = rclcpp::Node::make_shared("test_executor_notify");
executor.add_node(node);
{
std::thread spin_thread(executor_spin_lambda);
std::promise<void> timer_promise;
std::shared_future<void> timer_future(timer_promise.get_future());
auto timer = node->create_wall_timer(
1ms,
[&timer_promise](rclcpp::TimerBase & timer)
{
timer_promise.set_value();
timer.cancel();
});
EXPECT_EQ(std::future_status::ready, timer_future.wait_for(50ms));
executor.cancel();
spin_thread.join();
}
{
std::thread spin_thread(executor_spin_lambda);
bool subscription_triggered = false;
auto sub_callback =
[&executor, &subscription_triggered](test_rclcpp::msg::UInt32::ConstSharedPtr msg) -> void
{
subscription_triggered = true;
EXPECT_EQ(msg->data, 42u);
executor.cancel();
};
auto subscription = node->create_subscription<test_rclcpp::msg::UInt32>(
"test_executor_notify_subscription",
10,
sub_callback);
test_rclcpp::wait_for_subscriber(node, "test_executor_notify_subscription");
auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>(
"test_executor_notify_subscription", 10);
auto timer = node->create_wall_timer(
1ms,
[&publisher]()
{
test_rclcpp::msg::UInt32 pub_msg;
pub_msg.data = 42;
publisher->publish(pub_msg);
});
spin_thread.join();
EXPECT_TRUE(subscription_triggered);
}
{
std::thread spin_thread(executor_spin_lambda);
auto service = node->create_service<test_rclcpp::srv::AddTwoInts>(
"test_executor_notify_service",
[](
test_rclcpp::srv::AddTwoInts::Request::SharedPtr request,
test_rclcpp::srv::AddTwoInts::Response::SharedPtr response)
{
response->sum = request->a + request->b;
});
auto client = node->create_client<test_rclcpp::srv::AddTwoInts>(
"test_executor_notify_service"
);
if (!client->wait_for_service(20s)) {
ASSERT_TRUE(false) << "service not available after waiting";
}
auto request = std::make_shared<test_rclcpp::srv::AddTwoInts::Request>();
request->a = 4;
request->b = 2;
auto future_result = client->async_send_request(request);
EXPECT_EQ(future_result.get()->sum, 6);
executor.cancel();
spin_thread.join();
}
}
// test removing a node
// test notify with multiple nodes
<commit_msg>Adjusted spin_some test due to new behavior (#394)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <atomic>
#include <chrono>
#include <cinttypes>
#include <future>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "rclcpp/exceptions.hpp"
#include "rclcpp/rclcpp.hpp"
#include "test_rclcpp/utils.hpp"
#include "test_rclcpp/msg/u_int32.hpp"
#include "test_rclcpp/srv/add_two_ints.hpp"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
using namespace std::chrono_literals;
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), recursive_spin_call) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("recursive_spin_call");
auto timer = node->create_wall_timer(
0s,
[&executor]() {
ASSERT_THROW(executor.spin_some(), std::runtime_error);
ASSERT_THROW(executor.spin_once(), std::runtime_error);
ASSERT_THROW(executor.spin(), std::runtime_error);
executor.cancel();
});
executor.add_node(node);
executor.spin();
}
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), spin_some_max_duration) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("spin_some_max_duration");
auto lambda = []() {
std::this_thread::sleep_for(1ms);
};
std::vector<std::shared_ptr<rclcpp::WallTimer<decltype(lambda)>>> timers;
// creating 20 timers which will try to do 1 ms of work each
// only about 10ms worth of them should actually be performed
for (int i = 0; i < 20; i++) {
auto timer = node->create_wall_timer(0s, lambda);
timers.push_back(timer);
}
executor.add_node(node);
const auto max_duration = 10ms;
const auto start = std::chrono::steady_clock::now();
executor.spin_some(max_duration);
const auto end = std::chrono::steady_clock::now();
ASSERT_LT(max_duration, end - start);
ASSERT_GT(max_duration + 5ms, end - start);
}
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multithreaded_spin_call) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto node = rclcpp::Node::make_shared("multithreaded_spin_call");
std::mutex m;
bool ready = false;
std::condition_variable cv;
std::thread t(
[&executor, &m, &cv, &ready]() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [&ready] {return ready;});
ASSERT_THROW(executor.spin_some(), std::runtime_error);
ASSERT_THROW(executor.spin_once(), std::runtime_error);
ASSERT_THROW(executor.spin(), std::runtime_error);
executor.cancel();
});
auto timer = node->create_wall_timer(
0s,
[&m, &cv, &ready]() {
if (!ready) {
{
std::lock_guard<std::mutex> lock(m);
ready = true;
}
cv.notify_one();
}
});
executor.add_node(node);
executor.spin();
t.join();
}
// Try spinning 2 single-threaded executors in two separate threads.
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multiple_executors) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
std::atomic_uint counter1;
counter1 = 0;
std::atomic_uint counter2;
counter2 = 0;
const uint32_t counter_goal = 20;
// Initialize executor 1.
rclcpp::executors::SingleThreadedExecutor executor1;
// I'm not a huge fan of unspecified capture variables in a lambda, but it
// is necessary in this case. On MacOS High Sierra and later, clang
// complains if we try to pass "counter_goal" as a specific lambda capture
// since it is a const. On the other hand, MSVC 2017 (19.12.25834.0)
// complains if you do *not* have the capture. To let both compilers be
// happy, we just let the compiler figure out the captures it wants; this
// is doubly OK because this is just for a test.
auto callback1 = [&]() {
if (counter1 == counter_goal) {
executor1.cancel();
return;
}
++counter1;
};
auto node1 = rclcpp::Node::make_shared("multiple_executors_1");
auto timer1 = node1->create_wall_timer(1ms, callback1);
executor1.add_node(node1);
// Initialize executor 2.
rclcpp::executors::SingleThreadedExecutor executor2;
// This lambda has the same problem & solution as the callback1 lambda above.
auto callback2 = [&]() {
if (counter2 == counter_goal) {
executor2.cancel();
return;
}
++counter2;
};
auto node2 = rclcpp::Node::make_shared("multiple_executors_2");
auto timer2 = node2->create_wall_timer(1ms, callback2);
executor2.add_node(node2);
auto spin_executor2 = [&executor2]() {
executor2.spin();
};
// Launch both executors
std::thread execution_thread(spin_executor2);
executor1.spin();
execution_thread.join();
EXPECT_EQ(counter1.load(), counter_goal);
EXPECT_EQ(counter2.load(), counter_goal);
// Try to add node1 to executor2. It should throw, since node1 was already added to executor1.
ASSERT_THROW(executor2.add_node(node1), std::runtime_error);
}
// Check that the executor is notified when a node adds a new timer, publisher, subscription,
// service or client.
TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), notify) {
if (!rclcpp::ok()) {rclcpp::init(0, nullptr);}
rclcpp::executors::SingleThreadedExecutor executor;
auto executor_spin_lambda = [&executor]() {
executor.spin();
};
auto node = rclcpp::Node::make_shared("test_executor_notify");
executor.add_node(node);
{
std::thread spin_thread(executor_spin_lambda);
std::promise<void> timer_promise;
std::shared_future<void> timer_future(timer_promise.get_future());
auto timer = node->create_wall_timer(
1ms,
[&timer_promise](rclcpp::TimerBase & timer)
{
timer_promise.set_value();
timer.cancel();
});
EXPECT_EQ(std::future_status::ready, timer_future.wait_for(50ms));
executor.cancel();
spin_thread.join();
}
{
std::thread spin_thread(executor_spin_lambda);
bool subscription_triggered = false;
auto sub_callback =
[&executor, &subscription_triggered](test_rclcpp::msg::UInt32::ConstSharedPtr msg) -> void
{
subscription_triggered = true;
EXPECT_EQ(msg->data, 42u);
executor.cancel();
};
auto subscription = node->create_subscription<test_rclcpp::msg::UInt32>(
"test_executor_notify_subscription",
10,
sub_callback);
test_rclcpp::wait_for_subscriber(node, "test_executor_notify_subscription");
auto publisher = node->create_publisher<test_rclcpp::msg::UInt32>(
"test_executor_notify_subscription", 10);
auto timer = node->create_wall_timer(
1ms,
[&publisher]()
{
test_rclcpp::msg::UInt32 pub_msg;
pub_msg.data = 42;
publisher->publish(pub_msg);
});
spin_thread.join();
EXPECT_TRUE(subscription_triggered);
}
{
std::thread spin_thread(executor_spin_lambda);
auto service = node->create_service<test_rclcpp::srv::AddTwoInts>(
"test_executor_notify_service",
[](
test_rclcpp::srv::AddTwoInts::Request::SharedPtr request,
test_rclcpp::srv::AddTwoInts::Response::SharedPtr response)
{
response->sum = request->a + request->b;
});
auto client = node->create_client<test_rclcpp::srv::AddTwoInts>(
"test_executor_notify_service"
);
if (!client->wait_for_service(20s)) {
ASSERT_TRUE(false) << "service not available after waiting";
}
auto request = std::make_shared<test_rclcpp::srv::AddTwoInts::Request>();
request->a = 4;
request->b = 2;
auto future_result = client->async_send_request(request);
EXPECT_EQ(future_result.get()->sum, 6);
executor.cancel();
spin_thread.join();
}
}
// test removing a node
// test notify with multiple nodes
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
#define PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
#include <pcl/registration/correspondence_estimation_organized_projection.h>
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> bool
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::initCompute ()
{
if (!CorrespondenceEstimationBase<PointSource, PointTarget>::initCompute ())
return (false);
/// Check if the target cloud is organized
if (!target_->isOrganized ())
{
PCL_WARN ("[pcl::registration::%s::initCompute] Target cloud is not organized.\n", getClassName ().c_str ());
return (false);
}
/// Put the projection matrix together
projection_matrix_ (0, 0) = fx_;
projection_matrix_ (1, 1) = fy_;
projection_matrix_ (0, 2) = cx_;
projection_matrix_ (1, 2) = cy_;
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> void
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::determineCorrespondences (
pcl::Correspondences &correspondences,
double max_distance)
{
if (!initCompute ())
return;
correspondences.resize (input_->size ());
size_t c_index = 0;
for (std::vector<int>::const_iterator src_it = indices_->begin (); src_it != indices_->end (); ++src_it)
{
if (isFinite (input_->points[*src_it]))
{
Eigen::Vector4f p_src = src_to_tgt_transformation_ * input_->points[*src_it].getVector4fMap ();
Eigen::Vector3f p_src3 (p_src[0], p_src[1], p_src[2]);
Eigen::Vector3f uv = projection_matrix_ * p_src3;
/// Check if the point was behind the camera
if (uv[2] < 0)
continue;
int u = static_cast<int> (uv[0] / uv[2]);
int v = static_cast<int> (uv[1] / uv[2]);
if (u >= 0 && u < target_->width &&
v >= 0 && v < target_->height &&
isFinite ((*target_) (u, v)))
{
/// Check if the depth difference is larger than the threshold
if (fabs (uv[2] - (*target_) (u, v).z) > depth_threshold_)
continue;
double dist = (p_src3 - (*target_) (u, v).getVector3fMap ()).norm ();
if (dist < max_distance)
correspondences[c_index ++] = pcl::Correspondence (*src_it, v * target_->width + u, static_cast<float> (dist));
}
}
}
correspondences.resize (c_index);
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> void
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::determineReciprocalCorrespondences (
pcl::Correspondences &correspondences,
double max_distance)
{
/// Call the normal determineCorrespondences (...), as doing it both ways will not improve the results
determineCorrespondences (correspondences, max_distance);
}
#endif // PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
<commit_msg>fixed compiler warnings<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
#define PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
#include <pcl/registration/correspondence_estimation_organized_projection.h>
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> bool
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::initCompute ()
{
if (!CorrespondenceEstimationBase<PointSource, PointTarget>::initCompute ())
return (false);
/// Check if the target cloud is organized
if (!target_->isOrganized ())
{
PCL_WARN ("[pcl::registration::%s::initCompute] Target cloud is not organized.\n", getClassName ().c_str ());
return (false);
}
/// Put the projection matrix together
projection_matrix_ (0, 0) = fx_;
projection_matrix_ (1, 1) = fy_;
projection_matrix_ (0, 2) = cx_;
projection_matrix_ (1, 2) = cy_;
return (true);
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> void
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::determineCorrespondences (
pcl::Correspondences &correspondences,
double max_distance)
{
if (!initCompute ())
return;
correspondences.resize (input_->size ());
size_t c_index = 0;
for (std::vector<int>::const_iterator src_it = indices_->begin (); src_it != indices_->end (); ++src_it)
{
if (isFinite (input_->points[*src_it]))
{
Eigen::Vector4f p_src (src_to_tgt_transformation_ * input_->points[*src_it].getVector4fMap ());
Eigen::Vector3f p_src3 (p_src[0], p_src[1], p_src[2]);
Eigen::Vector3f uv (projection_matrix_ * p_src3);
/// Check if the point was behind the camera
if (uv[2] < 0)
continue;
int u = static_cast<int> (uv[0] / uv[2]);
int v = static_cast<int> (uv[1] / uv[2]);
if (u >= 0 && u < int (target_->width) &&
v >= 0 && v < int (target_->height) &&
isFinite ((*target_) (u, v)))
{
/// Check if the depth difference is larger than the threshold
if (fabs (uv[2] - (*target_) (u, v).z) > depth_threshold_)
continue;
double dist = (p_src3 - (*target_) (u, v).getVector3fMap ()).norm ();
if (dist < max_distance)
correspondences[c_index ++] = pcl::Correspondence (*src_it, v * target_->width + u, static_cast<float> (dist));
}
}
}
correspondences.resize (c_index);
}
///////////////////////////////////////////////////////////////////////////////////////////
template <typename PointSource, typename PointTarget, typename Scalar> void
pcl::registration::CorrespondenceEstimationOrganizedProjection<PointSource, PointTarget, Scalar>::determineReciprocalCorrespondences (
pcl::Correspondences &correspondences,
double max_distance)
{
/// Call the normal determineCorrespondences (...), as doing it both ways will not improve the results
determineCorrespondences (correspondences, max_distance);
}
#endif // PCL_REGISTRATION_CORRESPONDENCE_ESTIMATION_BACK_PROJECTION_IMPL_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Int.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ThreadAbortException.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/IO/FileSystem/DirectoryIterable.h"
#include "../../../Foundation/Memory/BLOB.h"
#include "../CommonMeasurementTypes.h"
#include "ProcessDetails.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::ProcessDetails;
using Characters::String_Constant;
const MeasurementType Instruments::ProcessDetails::kProcessMapMeasurement = MeasurementType (String_Constant (L"Process-Details"));
//tmphack to test
//#define qUseProcFS_ 1
#ifndef qUseProcFS_
#define qUseProcFS_ qPlatform_POSIX
#endif
/*
********************************************************************************
************** Instruments::ProcessDetails::GetObjectVariantMapper *************
********************************************************************************
*/
ObjectVariantMapper Instruments::ProcessDetails::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<String>> ();
mapper.AddCommonType<Optional<Mapping<String, String>>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<ProcessType> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fCommandLine), String_Constant (L"Command-Line"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fCurrentWorkingDirectory), String_Constant (L"Current-Working-Directory"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fEnvironmentVariables), String_Constant (L"Environment-Variables"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fEXEPath), String_Constant (L"EXE-Path"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fRoot), String_Constant (L"Root"), StructureFieldInfo::NullFieldHandling::eOmit },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<ProcessMapType> ();
return mapper;
} ();
return sMapper_;
}
namespace {
// this reads /proc format files - meaning that a trialing nul-byte is the EOS
String ReadFileString_(const String& fullPath)
{
Memory::BLOB b = IO::FileSystem::BinaryFileInputStream (fullPath).ReadAll ();
const char* s = reinterpret_cast<const char*> (b.begin ());
const char* e = s + b.size ();
if (s < e and * (e - 1) == '\0') {
e--;
}
return String::FromNarrowSDKString (s, e);
}
ProcessMapType ExtractFromProcFS_ ()
{
/// Most status - like time - come from http://linux.die.net/man/5/proc
///proc/[pid]/stat
// Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.
//
ProcessMapType tmp;
#if qUseProcFS_
for (String dir : IO::FileSystem::DirectoryIterable (L"/proc")) {
bool isAllNumeric = dir.FindFirstThat ([] (Character c) -> bool { return not c.IsDigit (); });
pid_t pid = String2Int<pid_t> (dir);
ProcessType processDetails;
IgnoreExceptionsExceptThreadAbortForCall (processDetails.fCommandLine = ReadFileString_ (L"/proc/" + dir + L"/cmdline"));
Mapping<String, String> env;
env.Add (L"Home", L"/home/lewis");
processDetails.fEnvironmentVariables = env;
tmp.Add (pid, processDetails);
}
#else
ProcessType test;
test.fCommandLine = L"Hi mom comamndline";
Mapping<String, String> env;
env.Add (L"Home", L"/home/lewis");
test.fEnvironmentVariables = env;
tmp.Add (101, test);
#endif
return tmp;
}
}
/*
********************************************************************************
************* Instruments::ProcessDetails::GetInstrument **********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::ProcessDetails::GetInstrument (
const Optional<Set<Fields2Capture>>& onlyCaptureFields,
const Optional<Set<pid_t>>& restrictToPIDs,
const Optional<Set<pid_t>>& omitPIDs,
CachePolicy cachePolicy
)
{
// @todo can only use static one if right options passed in...
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"ProcessDetails")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
auto rawMeasurement = ExtractFromProcFS_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
m.fType = kProcessMapMeasurement;
results.fMeasurements.Add (m);
return results;
},
{kProcessMapMeasurement}
);
return kInstrument_;
}
<commit_msg>more SystemPerformance/Instruments/ProcessDetails read /proc fs support<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Int.h"
#include "../../../Foundation/Characters/StringBuilder.h"
#include "../../../Foundation/Characters/Tokenize.h"
#include "../../../Foundation/Containers/Mapping.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ThreadAbortException.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/IO/FileSystem/DirectoryIterable.h"
#include "../../../Foundation/Memory/BLOB.h"
#include "../../../Foundation/Memory/Optional.h"
#include "../../../Foundation/Streams/BufferedBinaryInputStream.h"
#include "../CommonMeasurementTypes.h"
#include "ProcessDetails.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::ProcessDetails;
using Characters::String_Constant;
const MeasurementType Instruments::ProcessDetails::kProcessMapMeasurement = MeasurementType (String_Constant (L"Process-Details"));
//tmphack to test
//#define qUseProcFS_ 1
#ifndef qUseProcFS_
#define qUseProcFS_ qPlatform_POSIX
#endif
/*
********************************************************************************
************** Instruments::ProcessDetails::GetObjectVariantMapper *************
********************************************************************************
*/
ObjectVariantMapper Instruments::ProcessDetails::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<String>> ();
mapper.AddCommonType<Optional<Mapping<String, String>>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<ProcessType> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fCommandLine), String_Constant (L"Command-Line"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fCurrentWorkingDirectory), String_Constant (L"Current-Working-Directory"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fEnvironmentVariables), String_Constant (L"Environment-Variables"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fEXEPath), String_Constant (L"EXE-Path"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (ProcessType, fRoot), String_Constant (L"Root"), StructureFieldInfo::NullFieldHandling::eOmit },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<ProcessMapType> ();
return mapper;
} ();
return sMapper_;
}
namespace {
// this reads /proc format files - meaning that a trialing nul-byte is the EOS
String ReadFileString_(const String& fullPath)
{
Memory::BLOB b = IO::FileSystem::BinaryFileInputStream (fullPath).ReadAll ();
const char* s = reinterpret_cast<const char*> (b.begin ());
const char* e = s + b.size ();
if (s < e and * (e - 1) == '\0') {
e--;
}
return String::FromNarrowSDKString (s, e);
}
Sequence<String> ReadFileStrings_(const String& fullPath)
{
Sequence<String> results;
Streams::BinaryInputStream in = Streams::BufferedBinaryInputStream (IO::FileSystem::BinaryFileInputStream (fullPath));
StringBuilder sb;
for (Memory::Optional<Memory::Byte> b; (b = in.Read ()).IsPresent ();) {
if (*b == '\0') {
results.Append (sb.As<String> ());
sb.clear();
}
else {
sb.Append ((char) (*b)); // for now assume no charset
}
}
return results;
}
Mapping<String, String> ReadFileStringsMap_(const String& fullPath)
{
Mapping<String, String> results;
for (auto i : ReadFileStrings_ (fullPath)) {
auto tokens = Tokenize<String> (i, L"=");
if (tokens.size () == 2) {
results.Add (tokens[0], tokens[1]);
}
}
return results;
}
ProcessMapType ExtractFromProcFS_ ()
{
/// Most status - like time - come from http://linux.die.net/man/5/proc
///proc/[pid]/stat
// Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.
//
ProcessMapType tmp;
#if qUseProcFS_
for (String dir : IO::FileSystem::DirectoryIterable (L"/proc")) {
bool isAllNumeric = dir.FindFirstThat ([] (Character c) -> bool { return not c.IsDigit (); });
pid_t pid = String2Int<pid_t> (dir);
ProcessType processDetails;
IgnoreExceptionsExceptThreadAbortForCall (processDetails.fCommandLine = ReadFileString_ (L"/proc/" + dir + L"/cmdline"));
IgnoreExceptionsExceptThreadAbortForCall (processDetails.fEnvironmentVariables = ReadFileStringsMap_ (L"/proc/" + dir + L"/environ"));
tmp.Add (pid, processDetails);
}
#else
ProcessType test;
test.fCommandLine = L"Hi mom comamndline";
Mapping<String, String> env;
env.Add (L"Home", L"/home/lewis");
test.fEnvironmentVariables = env;
tmp.Add (101, test);
#endif
return tmp;
}
}
/*
********************************************************************************
************* Instruments::ProcessDetails::GetInstrument **********************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::ProcessDetails::GetInstrument (
const Optional<Set<Fields2Capture>>& onlyCaptureFields,
const Optional<Set<pid_t>>& restrictToPIDs,
const Optional<Set<pid_t>>& omitPIDs,
CachePolicy cachePolicy
)
{
// @todo can only use static one if right options passed in...
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"ProcessDetails")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
auto rawMeasurement = ExtractFromProcFS_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
m.fType = kProcessMapMeasurement;
results.fMeasurements.Add (m);
return results;
},
{kProcessMapMeasurement}
);
return kInstrument_;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "richtextviewport.hxx"
#include <editeng/editview.hxx>
//........................................................................
namespace frm
{
//........................................................................
//====================================================================
//= RichTextViewPort
//====================================================================
//--------------------------------------------------------------------
RichTextViewPort::RichTextViewPort( Window* _pParent )
:Control ( _pParent )
,m_bHideInactiveSelection( true )
{
}
//--------------------------------------------------------------------
void RichTextViewPort::setView( EditView& _rView )
{
m_pView = &_rView;
SetPointer( _rView.GetPointer() );
}
//--------------------------------------------------------------------
void RichTextViewPort::Paint( const Rectangle& _rRect )
{
m_pView->Paint( _rRect );
}
//--------------------------------------------------------------------
void RichTextViewPort::GetFocus()
{
Control::GetFocus();
m_pView->SetSelectionMode( EE_SELMODE_STD );
m_pView->ShowCursor( sal_True );
}
//--------------------------------------------------------------------
void RichTextViewPort::LoseFocus()
{
m_pView->HideCursor();
m_pView->SetSelectionMode( m_bHideInactiveSelection ? EE_SELMODE_HIDDEN : EE_SELMODE_STD );
Control::LoseFocus();
}
//--------------------------------------------------------------------
void RichTextViewPort::KeyInput( const KeyEvent& _rKEvt )
{
if ( !m_pView->PostKeyEvent( _rKEvt ) )
Control::KeyInput( _rKEvt );
else
implInvalidateAttributes();
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseMove( const MouseEvent& _rMEvt )
{
Control::MouseMove( _rMEvt );
m_pView->MouseMove( _rMEvt );
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseButtonDown( const MouseEvent& _rMEvt )
{
Control::MouseButtonDown( _rMEvt );
m_pView->MouseButtonDown( _rMEvt );
GrabFocus();
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseButtonUp( const MouseEvent& _rMEvt )
{
Control::MouseButtonUp( _rMEvt );
m_pView->MouseButtonUp( _rMEvt );
implInvalidateAttributes();
}
//--------------------------------------------------------------------
void RichTextViewPort::SetHideInactiveSelection( bool _bHide )
{
if ( m_bHideInactiveSelection == _bHide )
return;
m_bHideInactiveSelection = _bHide;
if ( !HasFocus() )
m_pView->SetSelectionMode( m_bHideInactiveSelection ? EE_SELMODE_HIDDEN : EE_SELMODE_STD );
}
//--------------------------------------------------------------------
bool RichTextViewPort::GetHideInactiveSelection() const
{
return m_bHideInactiveSelection;
}
//........................................................................
} // namespace frm
//........................................................................
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix Member variable m_pView is not initialized in the constructor<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "richtextviewport.hxx"
#include <editeng/editview.hxx>
//........................................................................
namespace frm
{
//........................................................................
//====================================================================
//= RichTextViewPort
//====================================================================
//--------------------------------------------------------------------
RichTextViewPort::RichTextViewPort( Window* _pParent )
:Control ( _pParent )
,m_pView(NULL)
,m_bHideInactiveSelection( true )
{
}
//--------------------------------------------------------------------
void RichTextViewPort::setView( EditView& _rView )
{
m_pView = &_rView;
SetPointer( _rView.GetPointer() );
}
//--------------------------------------------------------------------
void RichTextViewPort::Paint( const Rectangle& _rRect )
{
m_pView->Paint( _rRect );
}
//--------------------------------------------------------------------
void RichTextViewPort::GetFocus()
{
Control::GetFocus();
m_pView->SetSelectionMode( EE_SELMODE_STD );
m_pView->ShowCursor( sal_True );
}
//--------------------------------------------------------------------
void RichTextViewPort::LoseFocus()
{
m_pView->HideCursor();
m_pView->SetSelectionMode( m_bHideInactiveSelection ? EE_SELMODE_HIDDEN : EE_SELMODE_STD );
Control::LoseFocus();
}
//--------------------------------------------------------------------
void RichTextViewPort::KeyInput( const KeyEvent& _rKEvt )
{
if ( !m_pView->PostKeyEvent( _rKEvt ) )
Control::KeyInput( _rKEvt );
else
implInvalidateAttributes();
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseMove( const MouseEvent& _rMEvt )
{
Control::MouseMove( _rMEvt );
m_pView->MouseMove( _rMEvt );
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseButtonDown( const MouseEvent& _rMEvt )
{
Control::MouseButtonDown( _rMEvt );
m_pView->MouseButtonDown( _rMEvt );
GrabFocus();
}
//--------------------------------------------------------------------
void RichTextViewPort::MouseButtonUp( const MouseEvent& _rMEvt )
{
Control::MouseButtonUp( _rMEvt );
m_pView->MouseButtonUp( _rMEvt );
implInvalidateAttributes();
}
//--------------------------------------------------------------------
void RichTextViewPort::SetHideInactiveSelection( bool _bHide )
{
if ( m_bHideInactiveSelection == _bHide )
return;
m_bHideInactiveSelection = _bHide;
if ( !HasFocus() )
m_pView->SetSelectionMode( m_bHideInactiveSelection ? EE_SELMODE_HIDDEN : EE_SELMODE_STD );
}
//--------------------------------------------------------------------
bool RichTextViewPort::GetHideInactiveSelection() const
{
return m_bHideInactiveSelection;
}
//........................................................................
} // namespace frm
//........................................................................
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <plasp/pddl/expressions/Not.h>
#include <plasp/pddl/expressions/And.h>
#include <plasp/pddl/expressions/Or.h>
namespace plasp
{
namespace pddl
{
namespace expressions
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Not
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Not::Not()
: m_argument{nullptr}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Not::setArgument(ExpressionPointer argument)
{
m_argument = argument;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ExpressionPointer Not::argument() const
{
return m_argument;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ExpressionPointer Not::normalized()
{
BOOST_ASSERT(m_argument);
// Remove double negations immediately
if (m_argument->expressionType() == Expression::Type::Not)
{
auto &argument = dynamic_cast<Not &>(*m_argument);
return argument.m_argument->normalized();
}
m_argument = m_argument->normalized();
// De Morgan for negative conjunctions
if (m_argument->expressionType() == Expression::Type::And)
{
auto &andExpression = dynamic_cast<And &>(*m_argument);
auto orExpression = OrPointer(new Or);
orExpression->arguments().reserve(andExpression.arguments().size());
for (size_t i = 0; i < andExpression.arguments().size(); i++)
orExpression->addArgument(andExpression.arguments()[i]->negated());
return orExpression->normalized();
}
// De Morgan for negative disjunctions
if (m_argument->expressionType() == Expression::Type::Or)
{
auto &orExpression = dynamic_cast<Or &>(*m_argument);
auto andExpression = AndPointer(new And);
andExpression->arguments().reserve(orExpression.arguments().size());
for (size_t i = 0; i < orExpression.arguments().size(); i++)
andExpression->addArgument(orExpression.arguments()[i]->negated());
return andExpression->normalized();
}
return this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Not::print(std::ostream &ostream) const
{
ostream << "(not ";
m_argument->print(ostream);
ostream << ")";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
<commit_msg>Added second double negation elimination step after normalizing the argument of a “not” expression.<commit_after>#include <plasp/pddl/expressions/Not.h>
#include <plasp/pddl/expressions/And.h>
#include <plasp/pddl/expressions/Or.h>
namespace plasp
{
namespace pddl
{
namespace expressions
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Not
//
////////////////////////////////////////////////////////////////////////////////////////////////////
Not::Not()
: m_argument{nullptr}
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Not::setArgument(ExpressionPointer argument)
{
m_argument = argument;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ExpressionPointer Not::argument() const
{
return m_argument;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
ExpressionPointer Not::normalized()
{
BOOST_ASSERT(m_argument);
// Remove immediate double negations
if (m_argument->expressionType() == Expression::Type::Not)
{
auto &argument = dynamic_cast<Not &>(*m_argument);
return argument.m_argument->normalized();
}
// Normalize argument
m_argument = m_argument->normalized();
// Remove double negations occurring after normalizing the argument
if (m_argument->expressionType() == Expression::Type::Not)
{
auto &argument = dynamic_cast<Not &>(*m_argument);
return argument.m_argument->normalized();
}
// De Morgan for negative conjunctions
if (m_argument->expressionType() == Expression::Type::And)
{
auto &andExpression = dynamic_cast<And &>(*m_argument);
auto orExpression = OrPointer(new Or);
orExpression->arguments().reserve(andExpression.arguments().size());
for (size_t i = 0; i < andExpression.arguments().size(); i++)
orExpression->addArgument(andExpression.arguments()[i]->negated());
return orExpression->normalized();
}
// De Morgan for negative disjunctions
if (m_argument->expressionType() == Expression::Type::Or)
{
auto &orExpression = dynamic_cast<Or &>(*m_argument);
auto andExpression = AndPointer(new And);
andExpression->arguments().reserve(orExpression.arguments().size());
for (size_t i = 0; i < orExpression.arguments().size(); i++)
andExpression->addArgument(orExpression.arguments()[i]->negated());
return andExpression->normalized();
}
return this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void Not::print(std::ostream &ostream) const
{
ostream << "(not ";
m_argument->print(ostream);
ostream << ")";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
<|endoftext|> |
<commit_before>#ifndef ITER_ENUMERATE_H_
#define ITER_ENUMERATE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <functional>
#include <initializer_list>
#include <type_traits>
// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
// std::cout << e.index
// << ": "
// << e.element
// << '\n';
// }
namespace iter {
//Forward declarations of Enumerable and enumerate
template <typename Container>
class Enumerable;
template <typename Container>
Enumerable<Container> enumerate(Container&&);
template <typename T>
Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T>);
template <typename Container>
class Enumerable {
private:
Container container;
// The only thing allowed to directly instantiate an Enumerable is
// the enumerate function
friend Enumerable enumerate<Container>(Container&&);
template <typename T>
friend Enumerable<std::initializer_list<T>> enumerate(
std::initializer_list<T>);
// for IterYield
using BasePair = std::pair<std::size_t, iterator_deref<Container>>;
// Value constructor for use only in the enumerate function
Enumerable(Container container)
: container(std::forward<Container>(container))
{ }
public:
// "yielded" by the Enumerable::Iterator. Has a .index, and a
// .element referencing the value yielded by the subiterator
class IterYield : public BasePair {
public:
using BasePair::BasePair;
decltype(BasePair::first)& index = BasePair::first;
decltype(BasePair::second)& element = BasePair::second;
};
// Holds an iterator of the contained type and a size_t for the
// index. Each call to ++ increments both of these data members.
// Each dereference returns an IterYield.
class Iterator :
public std::iterator<std::input_iterator_tag, IterYield>
{
private:
iterator_type<Container> sub_iter;
std::size_t index;
public:
Iterator (iterator_type<Container> si)
: sub_iter{si},
index{0}
{ }
IterYield operator*() {
return IterYield(this->index, *this->sub_iter);
}
Iterator& operator++() {
++this->sub_iter;
++this->index;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container)};
}
Iterator end() {
return {std::end(this->container)};
}
};
template <typename Container>
Enumerable<Container> enumerate(Container&& container) {
return {std::forward<Container>(container)};
}
// for initializer lists. copy constructs the list into the Enumerable
template <typename T>
Enumerable<std::initializer_list<T>> enumerate(
std::initializer_list<T> il)
{
return {il};
}
}
#endif //#ifndef ITER_ENUMERATE_H_
<commit_msg>uniform initialization in enumerate *<commit_after>#ifndef ITER_ENUMERATE_H_
#define ITER_ENUMERATE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <functional>
#include <initializer_list>
#include <type_traits>
// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
// std::cout << e.index
// << ": "
// << e.element
// << '\n';
// }
namespace iter {
//Forward declarations of Enumerable and enumerate
template <typename Container>
class Enumerable;
template <typename Container>
Enumerable<Container> enumerate(Container&&);
template <typename T>
Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T>);
template <typename Container>
class Enumerable {
private:
Container container;
// The only thing allowed to directly instantiate an Enumerable is
// the enumerate function
friend Enumerable enumerate<Container>(Container&&);
template <typename T>
friend Enumerable<std::initializer_list<T>> enumerate(
std::initializer_list<T>);
// for IterYield
using BasePair = std::pair<std::size_t, iterator_deref<Container>>;
// Value constructor for use only in the enumerate function
Enumerable(Container container)
: container(std::forward<Container>(container))
{ }
public:
// "yielded" by the Enumerable::Iterator. Has a .index, and a
// .element referencing the value yielded by the subiterator
class IterYield : public BasePair {
public:
using BasePair::BasePair;
decltype(BasePair::first)& index = BasePair::first;
decltype(BasePair::second)& element = BasePair::second;
};
// Holds an iterator of the contained type and a size_t for the
// index. Each call to ++ increments both of these data members.
// Each dereference returns an IterYield.
class Iterator :
public std::iterator<std::input_iterator_tag, IterYield>
{
private:
iterator_type<Container> sub_iter;
std::size_t index;
public:
Iterator (iterator_type<Container> si)
: sub_iter{si},
index{0}
{ }
IterYield operator*() {
return {this->index, *this->sub_iter};
}
Iterator& operator++() {
++this->sub_iter;
++this->index;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container)};
}
Iterator end() {
return {std::end(this->container)};
}
};
template <typename Container>
Enumerable<Container> enumerate(Container&& container) {
return {std::forward<Container>(container)};
}
// for initializer lists. copy constructs the list into the Enumerable
template <typename T>
Enumerable<std::initializer_list<T>> enumerate(
std::initializer_list<T> il)
{
return {il};
}
}
#endif //#ifndef ITER_ENUMERATE_H_
<|endoftext|> |
<commit_before>#include "equations.hpp"
#include <algorithm>
#include <stdexcept>
EquationPiece::EquationPiece(char op) : type(Type::Operation), operation(op) {}
EquationPiece::EquationPiece(double num) : type(Type::Number), number(num) {}
std::string Equation::doubleToString(double num) const {
std::string doubleString = std::to_string(num);
doubleString.erase(doubleString.find_last_not_of('0') + 1, std::string::npos);
if (!doubleString.empty() && doubleString.back() == '.') {
doubleString.pop_back();
}
return doubleString;
}
void Equation::addNumber(double num) {
equationPieces.emplace_back(num);
}
void Equation::addOperation(char op) {
if (find(OPERATIONS.begin(), OPERATIONS.end(), op) == OPERATIONS.end()) {
throw std::runtime_error(std::string("Invalid operation ")+op+" added to equation.");
}
equationPieces.emplace_back(op);
}
std::string Equation::toString() const {
std::string equationString;
for (auto piece : equationPieces) {
if (piece.type == EquationPiece::Type::Number) {
//Convert number to string and add it to the resulting string
equationString += doubleToString(piece.number);
} else {
//Add operation to resulting string
equationString += piece.operation;
}
equationString += ' ';
}
return equationString;
}
double Equation::evaluate() {
std::stack<double> evaluationStack;
for (auto piece : equationPieces) {
if (piece.type == EquationPiece::Type::Number) {
//Next thing in the equation is a number, add it to the stack
evaluationStack.emplace(piece.number);
} else {
//Next thing in the equation is a operation,
// pop the previous 2 numbers
if (evaluationStack.size() < 2) {
throw std::runtime_error("Trying to evaluate equation. Failed because too few numbers exist.");
}
double num1 = evaluationStack.top();
evaluationStack.pop();
double num2 = evaluationStack.top();
evaluationStack.pop();
// apply the operation
double result;
switch (piece.operation) {
case '+':
result = num2+num1;
break;
case '-':
result = num2-num1;
break;
case '*':
result = num2*num1;
break;
case '/':
if (num1 == 0) {
throw std::runtime_error("Trying to divide by 0.");
}
result = num2/num1;
break;
default:
//Cant get here because addOperation disallows invalid operations
break;
}
// push the result onto the stack
evaluationStack.push(result);
}
}
if (evaluationStack.size() != 1) {
throw std::runtime_error("Trying to evaluate equation. Failed because too few operations exist.");
}
return evaluationStack.top();
}
const std::vector<char> Equation::OPERATIONS = {'+','-','*','/'};
void RandomEquationBuilder::createRandomEngine() {
std::random_device rd;
std::vector<unsigned int> seeds;
seeds.reserve(std::mt19937::state_size);
for (size_t i=0; i<std::mt19937::state_size; ++i) {
seeds.emplace_back(rd());
}
std::seed_seq s(seeds.begin(), seeds.end());
eng = std::mt19937(s);
}
double RandomEquationBuilder::randomNumber() {
std::uniform_int_distribution<int> dist(0,NUMBERS.size()-1);
return NUMBERS[dist(eng)];
}
char RandomEquationBuilder::randomOperation() {
std::uniform_int_distribution<int> dist(0,Equation::OPERATIONS.size()-1);
return Equation::OPERATIONS[dist(eng)];
}
RandomEquationBuilder::RandomEquationBuilder(const std::vector<double> NUMS) : NUMBERS(NUMS) {
createRandomEngine();
}
Equation RandomEquationBuilder::build(const int DESIRED_NUMBER_COUNT_IN_EQUATION) {
Equation equation;
int numberCount=0;
int balance=0;
std::bernoulli_distribution opOrNumDist(0.5);
while (numberCount < DESIRED_NUMBER_COUNT_IN_EQUATION) {
if (balance >= 2) {
//50/50 chance to add number or operation
if (opOrNumDist(eng)) {
//Add operation
equation.addOperation(randomOperation());
--balance;
} else {
//Add number
equation.addNumber(randomNumber());
++numberCount;
++balance;
}
} else {
//Too few numbers in the equation, must add number
equation.addNumber(randomNumber());
++numberCount;
++balance;
}
}
while (balance > 1) {
//Not enough operations in the equation
equation.addOperation(randomOperation());
--balance;
}
return equation;
}<commit_msg>Removed extra space added by Equation::toString()<commit_after>#include "equations.hpp"
#include <algorithm>
#include <stdexcept>
EquationPiece::EquationPiece(char op) : type(Type::Operation), operation(op) {}
EquationPiece::EquationPiece(double num) : type(Type::Number), number(num) {}
std::string Equation::doubleToString(double num) const {
std::string doubleString = std::to_string(num);
doubleString.erase(doubleString.find_last_not_of('0') + 1, std::string::npos);
if (!doubleString.empty() && doubleString.back() == '.') {
doubleString.pop_back();
}
return doubleString;
}
void Equation::addNumber(double num) {
equationPieces.emplace_back(num);
}
void Equation::addOperation(char op) {
if (find(OPERATIONS.begin(), OPERATIONS.end(), op) == OPERATIONS.end()) {
throw std::runtime_error(std::string("Invalid operation ")+op+" added to equation.");
}
equationPieces.emplace_back(op);
}
std::string Equation::toString() const {
std::string equationString;
for (auto piece : equationPieces) {
if (piece.type == EquationPiece::Type::Number) {
//Convert number to string and add it to the resulting string
equationString += doubleToString(piece.number);
} else {
//Add operation to resulting string
equationString += piece.operation;
}
equationString += ' ';
}
equationString.pop_back();
return equationString;
}
double Equation::evaluate() {
std::stack<double> evaluationStack;
for (auto piece : equationPieces) {
if (piece.type == EquationPiece::Type::Number) {
//Next thing in the equation is a number, add it to the stack
evaluationStack.emplace(piece.number);
} else {
//Next thing in the equation is a operation,
// pop the previous 2 numbers
if (evaluationStack.size() < 2) {
throw std::runtime_error("Trying to evaluate equation. Failed because too few numbers exist.");
}
double num1 = evaluationStack.top();
evaluationStack.pop();
double num2 = evaluationStack.top();
evaluationStack.pop();
// apply the operation
double result;
switch (piece.operation) {
case '+':
result = num2+num1;
break;
case '-':
result = num2-num1;
break;
case '*':
result = num2*num1;
break;
case '/':
if (num1 == 0) {
throw std::runtime_error("Trying to divide by 0.");
}
result = num2/num1;
break;
default:
//Cant get here because addOperation disallows invalid operations
break;
}
// push the result onto the stack
evaluationStack.push(result);
}
}
if (evaluationStack.size() != 1) {
throw std::runtime_error("Trying to evaluate equation. Failed because too few operations exist.");
}
return evaluationStack.top();
}
const std::vector<char> Equation::OPERATIONS = {'+','-','*','/'};
void RandomEquationBuilder::createRandomEngine() {
std::random_device rd;
std::vector<unsigned int> seeds;
seeds.reserve(std::mt19937::state_size);
for (size_t i=0; i<std::mt19937::state_size; ++i) {
seeds.emplace_back(rd());
}
std::seed_seq s(seeds.begin(), seeds.end());
eng = std::mt19937(s);
}
double RandomEquationBuilder::randomNumber() {
std::uniform_int_distribution<int> dist(0,NUMBERS.size()-1);
return NUMBERS[dist(eng)];
}
char RandomEquationBuilder::randomOperation() {
std::uniform_int_distribution<int> dist(0,Equation::OPERATIONS.size()-1);
return Equation::OPERATIONS[dist(eng)];
}
RandomEquationBuilder::RandomEquationBuilder(const std::vector<double> NUMS) : NUMBERS(NUMS) {
createRandomEngine();
}
Equation RandomEquationBuilder::build(const int DESIRED_NUMBER_COUNT_IN_EQUATION) {
Equation equation;
int numberCount=0;
int balance=0;
std::bernoulli_distribution opOrNumDist(0.5);
while (numberCount < DESIRED_NUMBER_COUNT_IN_EQUATION) {
if (balance >= 2) {
//50/50 chance to add number or operation
if (opOrNumDist(eng)) {
//Add operation
equation.addOperation(randomOperation());
--balance;
} else {
//Add number
equation.addNumber(randomNumber());
++numberCount;
++balance;
}
} else {
//Too few numbers in the equation, must add number
equation.addNumber(randomNumber());
++numberCount;
++balance;
}
}
while (balance > 1) {
//Not enough operations in the equation
equation.addOperation(randomOperation());
--balance;
}
return equation;
}
<|endoftext|> |
<commit_before>#ifndef RING_BUFFER_HPP
#define RING_BUFFER_HPP
/// Code courtesy of: http://www.osix.net/modules/article/?id=464
template<typename kind>
class RingBuffer {
public:
// static const unsigned long RING_BUFFER_SIZE = 32768;
static const unsigned long RING_BUFFER_SIZE = 16384.
private:
kind buffer[RING_BUFFER_SIZE];
unsigned int current_element;
public:
RingBuffer() : current_element(0) {
}
RingBuffer(const RingBuffer& old_ring_buf) {
memcpy(buffer, old_ring_buf.buffer, RING_BUFFER_SIZE*sizeof(kind));
current_element = old_ring_buf.current_element;
}
RingBuffer operator = (const RingBuffer& old_ring_buf) {
memcpy(buffer, old_ring_buf.buffer, RING_BUFFER_SIZE*sizeof(kind));
current_element = old_ring_buf.current_element;
}
~RingBuffer() { }
void append(kind value) {
if (current_element >= RING_BUFFER_SIZE) {
current_element = 0;
}
buffer[current_element] = value;
++current_element;
}
kind back() {
if (current_element <= 0) {
current_element = RING_BUFFER_SIZE;
}
--current_element;
return buffer[current_element];
}
kind get() {
if(current_element >= RING_BUFFER_SIZE) {
current_element = 0;
}
++current_element;
return( buffer[(current_element-1)] );
}
int current() {
return (current_element);
}
};
#endif
<commit_msg>woops- forgot ;<commit_after>#ifndef RING_BUFFER_HPP
#define RING_BUFFER_HPP
/// Code courtesy of: http://www.osix.net/modules/article/?id=464
template<typename kind>
class RingBuffer {
public:
// static const unsigned long RING_BUFFER_SIZE = 32768;
static const unsigned long RING_BUFFER_SIZE = 16384;
private:
kind buffer[RING_BUFFER_SIZE];
unsigned int current_element;
public:
RingBuffer() : current_element(0) {
}
RingBuffer(const RingBuffer& old_ring_buf) {
memcpy(buffer, old_ring_buf.buffer, RING_BUFFER_SIZE*sizeof(kind));
current_element = old_ring_buf.current_element;
}
RingBuffer operator = (const RingBuffer& old_ring_buf) {
memcpy(buffer, old_ring_buf.buffer, RING_BUFFER_SIZE*sizeof(kind));
current_element = old_ring_buf.current_element;
}
~RingBuffer() { }
void append(kind value) {
if (current_element >= RING_BUFFER_SIZE) {
current_element = 0;
}
buffer[current_element] = value;
++current_element;
}
kind back() {
if (current_element <= 0) {
current_element = RING_BUFFER_SIZE;
}
--current_element;
return buffer[current_element];
}
kind get() {
if(current_element >= RING_BUFFER_SIZE) {
current_element = 0;
}
++current_element;
return( buffer[(current_element-1)] );
}
int current() {
return (current_element);
}
};
#endif
<|endoftext|> |
<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/quadrature.h>
using namespace libMesh;
#define MACROCOMMA ,
#define TEST_ONE_ORDER(qtype, order, maxorder) \
CPPUNIT_TEST( testBuild<qtype MACROCOMMA order> ); \
CPPUNIT_TEST( test1DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> ); \
CPPUNIT_TEST( test2DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> ); \
CPPUNIT_TEST( test3DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> );
// std::min isn't constexpr, and C++03 lacks constexpr anyway
#define mymin(a, b) (a < b ? a : b)
#define TEST_ALL_ORDERS(qtype, maxorder) \
TEST_ONE_ORDER(qtype, FIRST, mymin(1,maxorder)); \
TEST_ONE_ORDER(qtype, SECOND, mymin(2,maxorder)); \
TEST_ONE_ORDER(qtype, THIRD, mymin(3,maxorder)); \
TEST_ONE_ORDER(qtype, FOURTH, mymin(4,maxorder)); \
TEST_ONE_ORDER(qtype, FIFTH, mymin(5,maxorder)); \
TEST_ONE_ORDER(qtype, SIXTH, mymin(6,maxorder)); \
TEST_ONE_ORDER(qtype, SEVENTH, mymin(7,maxorder)); \
TEST_ONE_ORDER(qtype, EIGHTH, mymin(8,maxorder)); \
TEST_ONE_ORDER(qtype, NINTH, mymin(9,maxorder));
class QuadratureTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( QuadratureTest );
TEST_ALL_ORDERS(QGAUSS, 9999);
TEST_ONE_ORDER(QSIMPSON, FIRST, 3);
TEST_ONE_ORDER(QSIMPSON, SECOND, 3);
TEST_ONE_ORDER(QSIMPSON, THIRD, 3);
TEST_ONE_ORDER(QTRAP, FIRST, 1);
TEST_ALL_ORDERS(QGRID, 1);
// Edges/Tris only
// TEST_ALL_ORDERS(QCLOUGH, 9999);
// Quads/Hexes only
// TEST_ALL_ORDERS(QMONOMIAL, 1); // need "non-tensor" option?
// Tets only
// TEST_ALL_ORDERS(QGRUNDMANN_MOLLER, 9999);
// Tris+Tets only
// TEST_ALL_ORDERS(QCONICAL, 9999);
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp ()
{}
void tearDown ()
{}
template <QuadratureType qtype, Order order>
void testBuild ()
{
AutoPtr<QBase> qrule1D = QBase::build (qtype, 1, order);
AutoPtr<QBase> qrule2D = QBase::build (qtype, 2, order);
AutoPtr<QBase> qrule3D = QBase::build (qtype, 3, order);
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(1) , qrule1D->get_dim() );
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(2) , qrule2D->get_dim() );
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(3) , qrule3D->get_dim() );
}
//-------------------------------------------------------
// 1D Quadrature Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test1DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype , 1, order);
qrule->init (EDGE3);
for (unsigned int mode=0; mode <= exactorder; ++mode)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(mode));
const Real exact = (mode % 2) ?
0 : (Real(2.0) / (mode+1));
if (std::abs(exact - sum) >= TOLERANCE*TOLERANCE)
{
std::cout << "qtype = " << qtype << std::endl;
std::cout << "order = " << order << std::endl;
std::cout << "exactorder = " << exactorder << std::endl;
std::cout << "mode = " << mode << std::endl;
std::cout << "exact = " << exact << std::endl;
std::cout << "sum = " << sum << std::endl << std::endl;
}
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
}
//-------------------------------------------------------
// 2D Quadrature Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test2DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype, 2, order);
qrule->init (QUAD8);
for (unsigned int modex=0; modex <= exactorder; ++modex)
for (unsigned int modey=0; modey <= exactorder; ++modey)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(modex))
* std::pow(qrule->qp(qp)(1), static_cast<Real>(modey));
const Real exactx = (modex % 2) ?
0 : (Real(2.0) / (modex+1));
const Real exacty = (modey % 2) ?
0 : (Real(2.0) / (modey+1));
const Real exact = exactx*exacty;
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
qrule->init (TRI6);
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 0.5 , sum , TOLERANCE*TOLERANCE );
}
//-------------------------------------------------------
// 3D Gauss Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test3DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype, 3, order);
qrule->init (HEX20);
for (unsigned int modex=0; modex <= exactorder; ++modex)
for (unsigned int modey=0; modey <= exactorder; ++modey)
for (unsigned int modez=0; modez <= exactorder; ++modez)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(modex))
* std::pow(qrule->qp(qp)(1), static_cast<Real>(modey))
* std::pow(qrule->qp(qp)(2), static_cast<Real>(modez));
const Real exactx = (modex % 2) ?
0 : (Real(2.0) / (modex+1));
const Real exacty = (modey % 2) ?
0 : (Real(2.0) / (modey+1));
const Real exactz = (modez % 2) ?
0 : (Real(2.0) / (modez+1));
const Real exact = exactx*exacty*exactz;
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
qrule->init (TET10);
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 1./6., sum , TOLERANCE*TOLERANCE );
qrule->init (PRISM15);
sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 1., sum , TOLERANCE*TOLERANCE );
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( QuadratureTest );
<commit_msg>Add unit test for Gauss-Lobatto quadrature.<commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>
#include <libmesh/quadrature.h>
using namespace libMesh;
#define MACROCOMMA ,
#define TEST_ONE_ORDER(qtype, order, maxorder) \
CPPUNIT_TEST( testBuild<qtype MACROCOMMA order> ); \
CPPUNIT_TEST( test1DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> ); \
CPPUNIT_TEST( test2DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> ); \
CPPUNIT_TEST( test3DWeights<qtype MACROCOMMA order MACROCOMMA maxorder> );
// std::min isn't constexpr, and C++03 lacks constexpr anyway
#define mymin(a, b) (a < b ? a : b)
#define TEST_ALL_ORDERS(qtype, maxorder) \
TEST_ONE_ORDER(qtype, FIRST, mymin(1,maxorder)); \
TEST_ONE_ORDER(qtype, SECOND, mymin(2,maxorder)); \
TEST_ONE_ORDER(qtype, THIRD, mymin(3,maxorder)); \
TEST_ONE_ORDER(qtype, FOURTH, mymin(4,maxorder)); \
TEST_ONE_ORDER(qtype, FIFTH, mymin(5,maxorder)); \
TEST_ONE_ORDER(qtype, SIXTH, mymin(6,maxorder)); \
TEST_ONE_ORDER(qtype, SEVENTH, mymin(7,maxorder)); \
TEST_ONE_ORDER(qtype, EIGHTH, mymin(8,maxorder)); \
TEST_ONE_ORDER(qtype, NINTH, mymin(9,maxorder));
class QuadratureTest : public CppUnit::TestCase {
public:
CPPUNIT_TEST_SUITE( QuadratureTest );
TEST_ALL_ORDERS(QGAUSS, 9999);
TEST_ONE_ORDER(QSIMPSON, FIRST, 3);
TEST_ONE_ORDER(QSIMPSON, SECOND, 3);
TEST_ONE_ORDER(QSIMPSON, THIRD, 3);
TEST_ONE_ORDER(QTRAP, FIRST, 1);
TEST_ALL_ORDERS(QGRID, 1);
// Once we support up to at least 9th order, this can be changed to
// TEST_ALL_ORDERS(QGAUSS_LOBATTO, 9999);
TEST_ONE_ORDER(QGAUSS_LOBATTO, FIRST, 1);
TEST_ONE_ORDER(QGAUSS_LOBATTO, THIRD, 3);
TEST_ONE_ORDER(QGAUSS_LOBATTO, FIFTH, 5);
TEST_ONE_ORDER(QGAUSS_LOBATTO, SEVENTH, 7);
// Edges/Tris only
// TEST_ALL_ORDERS(QCLOUGH, 9999);
// Quads/Hexes only
// TEST_ALL_ORDERS(QMONOMIAL, 1); // need "non-tensor" option?
// Tets only
// TEST_ALL_ORDERS(QGRUNDMANN_MOLLER, 9999);
// Tris+Tets only
// TEST_ALL_ORDERS(QCONICAL, 9999);
CPPUNIT_TEST_SUITE_END();
private:
public:
void setUp ()
{}
void tearDown ()
{}
template <QuadratureType qtype, Order order>
void testBuild ()
{
AutoPtr<QBase> qrule1D = QBase::build (qtype, 1, order);
AutoPtr<QBase> qrule2D = QBase::build (qtype, 2, order);
AutoPtr<QBase> qrule3D = QBase::build (qtype, 3, order);
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(1) , qrule1D->get_dim() );
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(2) , qrule2D->get_dim() );
CPPUNIT_ASSERT_EQUAL ( static_cast<unsigned int>(3) , qrule3D->get_dim() );
}
//-------------------------------------------------------
// 1D Quadrature Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test1DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype , 1, order);
qrule->init (EDGE3);
for (unsigned int mode=0; mode <= exactorder; ++mode)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(mode));
const Real exact = (mode % 2) ?
0 : (Real(2.0) / (mode+1));
if (std::abs(exact - sum) >= TOLERANCE*TOLERANCE)
{
std::cout << "qtype = " << qtype << std::endl;
std::cout << "order = " << order << std::endl;
std::cout << "exactorder = " << exactorder << std::endl;
std::cout << "mode = " << mode << std::endl;
std::cout << "exact = " << exact << std::endl;
std::cout << "sum = " << sum << std::endl << std::endl;
}
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
}
//-------------------------------------------------------
// 2D Quadrature Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test2DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype, 2, order);
qrule->init (QUAD8);
for (unsigned int modex=0; modex <= exactorder; ++modex)
for (unsigned int modey=0; modey <= exactorder; ++modey)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(modex))
* std::pow(qrule->qp(qp)(1), static_cast<Real>(modey));
const Real exactx = (modex % 2) ?
0 : (Real(2.0) / (modex+1));
const Real exacty = (modey % 2) ?
0 : (Real(2.0) / (modey+1));
const Real exact = exactx*exacty;
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
// We may eventually support Gauss-Lobatto type quadrature on triangles...
if (qtype != QGAUSS_LOBATTO)
{
qrule->init (TRI6);
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 0.5 , sum , TOLERANCE*TOLERANCE );
}
}
//-------------------------------------------------------
// 3D Gauss Rule Test
template <QuadratureType qtype, Order order, unsigned int exactorder>
void test3DWeights ()
{
AutoPtr<QBase> qrule = QBase::build(qtype, 3, order);
qrule->init (HEX20);
for (unsigned int modex=0; modex <= exactorder; ++modex)
for (unsigned int modey=0; modey <= exactorder; ++modey)
for (unsigned int modez=0; modez <= exactorder; ++modez)
{
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp) * std::pow(qrule->qp(qp)(0), static_cast<Real>(modex))
* std::pow(qrule->qp(qp)(1), static_cast<Real>(modey))
* std::pow(qrule->qp(qp)(2), static_cast<Real>(modez));
const Real exactx = (modex % 2) ?
0 : (Real(2.0) / (modex+1));
const Real exacty = (modey % 2) ?
0 : (Real(2.0) / (modey+1));
const Real exactz = (modez % 2) ?
0 : (Real(2.0) / (modez+1));
const Real exact = exactx*exacty*exactz;
CPPUNIT_ASSERT_DOUBLES_EQUAL( exact , sum , TOLERANCE*TOLERANCE );
}
// We may eventually support Gauss-Lobatto type quadrature on tets and prisms...
if (qtype != QGAUSS_LOBATTO)
{
qrule->init (TET10);
Real sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 1./6., sum , TOLERANCE*TOLERANCE );
qrule->init (PRISM15);
sum = 0;
for (unsigned int qp=0; qp<qrule->n_points(); qp++)
sum += qrule->w(qp);
CPPUNIT_ASSERT_DOUBLES_EQUAL( 1., sum , TOLERANCE*TOLERANCE );
}
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( QuadratureTest );
<|endoftext|> |
<commit_before>#include "HalideRuntime.h"
#include "printer.h"
#include "runtime_internal.h"
#ifdef __cplusplus
extern "C" {
WEAK int halide_device_free(void *user_context, struct buffer_t *buf) {
return 0;
}
WEAK void halide_mutex_lock(struct halide_mutex *mutex) {
}
WEAK void halide_mutex_unlock(struct halide_mutex *mutex) {}
WEAK void halide_mutex_cleanup(struct halide_mutex *mutex_arg) {}
WEAK void halide_error(void *user_context, const char *s) {
write(STDERR_FILENO, s, strlen(s));
}
WEAK int halide_do_par_for(void *user_context, int (*f)(void *, int, uint8_t *),
int min, int size, uint8_t *closure) {
return -1;
}
WEAK int halide_copy_to_host(void *user_context, struct buffer_t *buf) {
return 0;
}
namespace Halide { namespace Runtime { namespace Internal {
WEAK void *default_malloc(void *user_context, size_t x) {
void *orig = malloc(x+40);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// Round up to next multiple of 32. Should add at least 8 bytes so we can fit the original pointer.
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
WEAK void default_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
WEAK void *(*custom_malloc)(void *, size_t) = default_malloc;
WEAK void (*custom_free)(void *, void *) = default_free;
}}}
WEAK void *(*halide_set_custom_malloc(void *(*user_malloc)(void *, size_t)))(void *, size_t) {
void *(*result)(void *, size_t) = custom_malloc;
custom_malloc = user_malloc;
return result;
}
WEAK void (*halide_set_custom_free(void (*user_free)(void *, void *)))(void *, void *) {
void (*result)(void *, void *) = custom_free;
custom_free = user_free;
return result;
}
WEAK void *halide_malloc(void *user_context, size_t x) {
return custom_malloc(user_context, x);
}
WEAK void halide_free(void *user_context, void *ptr) {
custom_free(user_context, ptr);
}
WEAK int halide_error_out_of_memory(void *user_context) {
// The error message builder uses malloc, so we can't use it here.
halide_error(user_context, "Out of memory (halide_malloc returned NULL)");
return halide_error_code_out_of_memory;
}
struct spawn_thread_task {
void (*f)(void *);
void *closure;
};
WEAK void *halide_spawn_thread_helper(void *arg) {
spawn_thread_task *t = (spawn_thread_task *)arg;
t->f(t->closure);
free(t);
return NULL;
}
WEAK void halide_spawn_thread(void *user_context, void (*f)(void *), void *closure) {
#if 0
// Note that we don't pass the user_context through to the
// thread. It may begin well after the user context is no longer a
// valid thing.
pthread_t thread;
// For the same reason we use malloc instead of
// halide_malloc. Custom malloc/free overrides may well not behave
// well if run at unexpected times (e.g. the matching free may
// occur at static destructor time if the thread never returns).
spawn_thread_task *t = (spawn_thread_task *)malloc(sizeof(spawn_thread_task));
t->f = f;
t->closure = closure;
pthread_create(&thread, NULL, halide_spawn_thread_helper, t);
#else
halide_error(user_context, "Halide spawn thread called");
#endif
}
typedef int32_t (*trace_fn)(void *, const halide_trace_event *);
namespace Halide { namespace Runtime { namespace Internal {
WEAK void halide_print_impl(void *user_context, const char * str) {
write(STDERR_FILENO, str, strlen(str));
}
WEAK int32_t default_trace(void *user_context, const halide_trace_event *e) {
stringstream ss(user_context);
// Round up bits to 8, 16, 32, or 64
int print_bits = 8;
while (print_bits < e->bits) print_bits <<= 1;
halide_assert(user_context, print_bits <= 64 && "Tracing bad type");
// Otherwise, use halide_printf and a plain-text format
const char *event_types[] = {"Load",
"Store",
"Begin realization",
"End realization",
"Produce",
"Update",
"Consume",
"End consume"};
// Only print out the value on stores and loads.
bool print_value = (e->event < 2);
ss << event_types[e->event] << " " << e->func << "." << e->value_index << "(";
if (e->vector_width > 1) {
ss << "<";
}
for (int i = 0; i < e->dimensions; i++) {
if (i > 0) {
if ((e->vector_width > 1) && (i % e->vector_width) == 0) {
ss << ">, <";
} else {
ss << ", ";
}
}
ss << e->coordinates[i];
}
if (e->vector_width > 1) {
ss << ">)";
} else {
ss << ")";
}
if (print_value) {
if (e->vector_width > 1) {
ss << " = <";
} else {
ss << " = ";
}
for (int i = 0; i < e->vector_width; i++) {
if (i > 0) {
ss << ", ";
}
if (e->type_code == 0) {
if (print_bits == 8) {
ss << ((int8_t *)(e->value))[i];
} else if (print_bits == 16) {
ss << ((int16_t *)(e->value))[i];
} else if (print_bits == 32) {
ss << ((int32_t *)(e->value))[i];
} else {
ss << ((int64_t *)(e->value))[i];
}
} else if (e->type_code == 1) {
if (print_bits == 8) {
ss << ((uint8_t *)(e->value))[i];
} else if (print_bits == 16) {
ss << ((uint16_t *)(e->value))[i];
} else if (print_bits == 32) {
ss << ((uint32_t *)(e->value))[i];
} else {
ss << ((uint64_t *)(e->value))[i];
}
} else if (e->type_code == 2) {
halide_assert(user_context, print_bits >= 32 && "Tracing a bad type");
if (print_bits == 32) {
ss << ((float *)(e->value))[i];
} else {
ss << ((double *)(e->value))[i];
}
} else if (e->type_code == 3) {
ss << ((void **)(e->value))[i];
}
}
if (e->vector_width > 1) {
ss << ">";
}
}
ss << "\n";
halide_print(user_context, ss.str());
return 0;
}
WEAK trace_fn halide_custom_trace = default_trace;
WEAK void (*halide_custom_print)(void *, const char *) = halide_print_impl;
}}} // namespace Halide::Runtime::Internal
WEAK trace_fn halide_set_custom_trace(trace_fn t) {
trace_fn result = halide_custom_trace;
halide_custom_trace = t;
return result;
}
WEAK int32_t halide_trace(void *user_context, const halide_trace_event *e) {
return (*halide_custom_trace)(user_context, e);
}
WEAK int halide_shutdown_trace() {
return 0;
}
WEAK void halide_print(void *user_context, const char *msg) {
(*halide_custom_print)(user_context, msg);
}
}
#endif
<commit_msg>Removed halide_copy_to_host and halide_device_free.<commit_after>#include "HalideRuntime.h"
#include "printer.h"
#include "runtime_internal.h"
#ifdef __cplusplus
extern "C" {
WEAK void halide_mutex_lock(struct halide_mutex *mutex) {
}
WEAK void halide_mutex_unlock(struct halide_mutex *mutex) {}
WEAK void halide_mutex_cleanup(struct halide_mutex *mutex_arg) {}
WEAK void halide_error(void *user_context, const char *s) {
write(STDERR_FILENO, s, strlen(s));
}
WEAK int halide_do_par_for(void *user_context, int (*f)(void *, int, uint8_t *),
int min, int size, uint8_t *closure) {
return -1;
}
namespace Halide { namespace Runtime { namespace Internal {
WEAK void *default_malloc(void *user_context, size_t x) {
void *orig = malloc(x+40);
if (orig == NULL) {
// Will result in a failed assertion and a call to halide_error
return NULL;
}
// Round up to next multiple of 32. Should add at least 8 bytes so we can fit the original pointer.
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
WEAK void default_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
WEAK void *(*custom_malloc)(void *, size_t) = default_malloc;
WEAK void (*custom_free)(void *, void *) = default_free;
}}}
WEAK void *(*halide_set_custom_malloc(void *(*user_malloc)(void *, size_t)))(void *, size_t) {
void *(*result)(void *, size_t) = custom_malloc;
custom_malloc = user_malloc;
return result;
}
WEAK void (*halide_set_custom_free(void (*user_free)(void *, void *)))(void *, void *) {
void (*result)(void *, void *) = custom_free;
custom_free = user_free;
return result;
}
WEAK void *halide_malloc(void *user_context, size_t x) {
return custom_malloc(user_context, x);
}
WEAK void halide_free(void *user_context, void *ptr) {
custom_free(user_context, ptr);
}
WEAK int halide_error_out_of_memory(void *user_context) {
// The error message builder uses malloc, so we can't use it here.
halide_error(user_context, "Out of memory (halide_malloc returned NULL)");
return halide_error_code_out_of_memory;
}
struct spawn_thread_task {
void (*f)(void *);
void *closure;
};
WEAK void *halide_spawn_thread_helper(void *arg) {
spawn_thread_task *t = (spawn_thread_task *)arg;
t->f(t->closure);
free(t);
return NULL;
}
WEAK void halide_spawn_thread(void *user_context, void (*f)(void *), void *closure) {
#if 0
// Note that we don't pass the user_context through to the
// thread. It may begin well after the user context is no longer a
// valid thing.
pthread_t thread;
// For the same reason we use malloc instead of
// halide_malloc. Custom malloc/free overrides may well not behave
// well if run at unexpected times (e.g. the matching free may
// occur at static destructor time if the thread never returns).
spawn_thread_task *t = (spawn_thread_task *)malloc(sizeof(spawn_thread_task));
t->f = f;
t->closure = closure;
pthread_create(&thread, NULL, halide_spawn_thread_helper, t);
#else
halide_error(user_context, "Halide spawn thread called");
#endif
}
typedef int32_t (*trace_fn)(void *, const halide_trace_event *);
namespace Halide { namespace Runtime { namespace Internal {
WEAK void halide_print_impl(void *user_context, const char * str) {
write(STDERR_FILENO, str, strlen(str));
}
WEAK int32_t default_trace(void *user_context, const halide_trace_event *e) {
stringstream ss(user_context);
// Round up bits to 8, 16, 32, or 64
int print_bits = 8;
while (print_bits < e->bits) print_bits <<= 1;
halide_assert(user_context, print_bits <= 64 && "Tracing bad type");
// Otherwise, use halide_printf and a plain-text format
const char *event_types[] = {"Load",
"Store",
"Begin realization",
"End realization",
"Produce",
"Update",
"Consume",
"End consume"};
// Only print out the value on stores and loads.
bool print_value = (e->event < 2);
ss << event_types[e->event] << " " << e->func << "." << e->value_index << "(";
if (e->vector_width > 1) {
ss << "<";
}
for (int i = 0; i < e->dimensions; i++) {
if (i > 0) {
if ((e->vector_width > 1) && (i % e->vector_width) == 0) {
ss << ">, <";
} else {
ss << ", ";
}
}
ss << e->coordinates[i];
}
if (e->vector_width > 1) {
ss << ">)";
} else {
ss << ")";
}
if (print_value) {
if (e->vector_width > 1) {
ss << " = <";
} else {
ss << " = ";
}
for (int i = 0; i < e->vector_width; i++) {
if (i > 0) {
ss << ", ";
}
if (e->type_code == 0) {
if (print_bits == 8) {
ss << ((int8_t *)(e->value))[i];
} else if (print_bits == 16) {
ss << ((int16_t *)(e->value))[i];
} else if (print_bits == 32) {
ss << ((int32_t *)(e->value))[i];
} else {
ss << ((int64_t *)(e->value))[i];
}
} else if (e->type_code == 1) {
if (print_bits == 8) {
ss << ((uint8_t *)(e->value))[i];
} else if (print_bits == 16) {
ss << ((uint16_t *)(e->value))[i];
} else if (print_bits == 32) {
ss << ((uint32_t *)(e->value))[i];
} else {
ss << ((uint64_t *)(e->value))[i];
}
} else if (e->type_code == 2) {
halide_assert(user_context, print_bits >= 32 && "Tracing a bad type");
if (print_bits == 32) {
ss << ((float *)(e->value))[i];
} else {
ss << ((double *)(e->value))[i];
}
} else if (e->type_code == 3) {
ss << ((void **)(e->value))[i];
}
}
if (e->vector_width > 1) {
ss << ">";
}
}
ss << "\n";
halide_print(user_context, ss.str());
return 0;
}
WEAK trace_fn halide_custom_trace = default_trace;
WEAK void (*halide_custom_print)(void *, const char *) = halide_print_impl;
}}} // namespace Halide::Runtime::Internal
WEAK trace_fn halide_set_custom_trace(trace_fn t) {
trace_fn result = halide_custom_trace;
halide_custom_trace = t;
return result;
}
WEAK int32_t halide_trace(void *user_context, const halide_trace_event *e) {
return (*halide_custom_trace)(user_context, e);
}
WEAK int halide_shutdown_trace() {
return 0;
}
WEAK void halide_print(void *user_context, const char *msg) {
(*halide_custom_print)(user_context, msg);
}
}
#endif
<|endoftext|> |
<commit_before>/*
* testSocket.cpp
*
* Created on: 25 May 2016
* Author: gnx91527
*/
#include <signal.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
namespace po = boost::program_options;
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
#include "zmq/zmq.hpp"
#include <JSONSubscriber.h>
#include "FileWriterController.h"
#include "SharedMemoryParser.h"
#include "SharedMemoryController.h"
using namespace filewriter;
void parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)
{
try
{
std::string config_file;
// Declare a group of options that will allowed only on the command line
po::options_description generic("Generic options");
generic.add_options()
("help,h",
"Print this help message")
("config,c", po::value<string>(&config_file),
"Specify program configuration file")
;
// Declare a group of options that will be allowed both on the command line
// and in the configuration file
po::options_description config("Configuration options");
config.add_options()
("logconfig,l", po::value<string>(),
"Set the log4cxx logging configuration file")
("ready", po::value<std::string>()->default_value("tcp://127.0.0.1:5001"),
"Ready ZMQ endpoint from frameReceiver")
("release", po::value<std::string>()->default_value("tcp://127.0.0.1:5002"),
"Release frame ZMQ endpoint from frameReceiver")
("frames,f", po::value<unsigned int>()->default_value(1),
"Set the number of frames to be notified about before terminating")
("sharedbuf", po::value<std::string>()->default_value("FrameReceiverBuffer"),
"Set the name of the shared memory frame buffer")
("output,o", po::value<std::string>(),
"Name of HDF5 file to write frames to (default: no file writing)")
("processes,p", po::value<unsigned int>()->default_value(1),
"Number of concurrent file writer processes" )
("rank,r", po::value<unsigned int>()->default_value(0),
"The rank (index number) of the current file writer process in relation to the other concurrent ones")
;
// Group the variables for parsing at the command line and/or from the configuration file
po::options_description cmdline_options;
cmdline_options.add(generic).add(config);
po::options_description config_file_options;
config_file_options.add(config);
// Parse the command line options
po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
po::notify(vm);
// If the command-line help option was given, print help and exit
if (vm.count("help"))
{
std::cout << "usage: fileWriter [options]" << std::endl << std::endl;
std::cout << cmdline_options << std::endl;
exit(1);
}
// If the command line config option was given, parse the specified configuration
// file for additional options. Note that boost::program_options gives precedence
// to the first instance occurring. In this case, that implies that command-line
// options have precedence over equivalent configuration file entries.
if (vm.count("config"))
{
std::ifstream config_ifs(config_file.c_str());
if (config_ifs)
{
LOG4CXX_DEBUG(logger, "Parsing configuration file " << config_file);
po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);
po::notify(vm);
}
else
{
LOG4CXX_ERROR(logger, "Unable to open configuration file " << config_file << " for parsing");
exit(1);
}
}
if (vm.count("logconfig"))
{
PropertyConfigurator::configure(vm["logconfig"].as<string>());
LOG4CXX_DEBUG(logger, "log4cxx config file is set to " << vm["logconfig"].as<string>());
}
if (vm.count("ready"))
{
LOG4CXX_DEBUG(logger, "Setting frame ready notification ZMQ address to " << vm["ready"].as<string>());
}
if (vm.count("release"))
{
LOG4CXX_DEBUG(logger, "Setting frame release notification ZMQ address to " << vm["release"].as<string>());
}
if (vm.count("frames"))
{
LOG4CXX_DEBUG(logger, "Setting number of frames to receive to " << vm["frames"].as<unsigned int>());
}
if (vm.count("output"))
{
LOG4CXX_DEBUG(logger, "Writing frames to file: " << vm["output"].as<string>());
}
if (vm.count("processes"))
{
LOG4CXX_DEBUG(logger, "Number of concurrent filewriter processes: " << vm["processes"].as<unsigned int>());
}
if (vm.count("rank"))
{
LOG4CXX_DEBUG(logger, "This process rank (index): " << vm["rank"].as<unsigned int>());
}
}
catch (po::unknown_option &e)
{
LOG4CXX_WARN(logger, "CLI parsing error: " << e.what() << ". Will carry on...");
}
catch (Exception &e)
{
LOG4CXX_FATAL(logger, "Got Log4CXX exception: " << e.what());
throw;
}
catch (exception &e)
{
LOG4CXX_ERROR(logger, "Got exception:" << e.what());
throw;
}
catch (...)
{
LOG4CXX_FATAL(logger, "Exception of unknown type!");
throw;
}
}
int main(int argc, char** argv)
{
// Create a default basic logger configuration, which can be overridden by command-line option later
BasicConfigurator::configure();
LoggerPtr logger(Logger::getLogger("socketApp"));
po::variables_map vm;
parse_arguments(argc, argv, vm, logger);
boost::shared_ptr<filewriter::FileWriterController> fwc;
fwc = boost::shared_ptr<filewriter::FileWriterController>(new filewriter::FileWriterController());
filewriter::JSONSubscriber sh("tcp://127.0.0.1:5003");
sh.registerCallback(fwc);
sh.subscribe();
// Configure the shared memory setup of the file writer controller
std::string cfgString = "{" +
std::string("\"fr_release_cnxn\":\"") + vm["release"].as<string>() + std::string("\",") +
"\"fr_ready_cnxn\":\"" + vm["ready"].as<string>() + "\"," +
"\"fr_shared_mem\":\"" + vm["sharedbuf"].as<string>() + "\"" +
"}";
cfgString = "{\"fr_setup\": " + cfgString + "}";
boost::shared_ptr<JSONMessage> cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Now wait for the shutdown
fwc->waitForShutdown();
return 0;
}
<commit_msg>Added configuration messages to the fileWriterApp test application to setup the system for Percival frames.<commit_after>/*
* testSocket.cpp
*
* Created on: 25 May 2016
* Author: gnx91527
*/
#include <signal.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
namespace po = boost::program_options;
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
#include "zmq/zmq.hpp"
#include <JSONSubscriber.h>
#include "FileWriterController.h"
#include "SharedMemoryParser.h"
#include "SharedMemoryController.h"
using namespace filewriter;
void parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)
{
try
{
std::string config_file;
// Declare a group of options that will allowed only on the command line
po::options_description generic("Generic options");
generic.add_options()
("help,h",
"Print this help message")
("config,c", po::value<string>(&config_file),
"Specify program configuration file")
;
// Declare a group of options that will be allowed both on the command line
// and in the configuration file
po::options_description config("Configuration options");
config.add_options()
("logconfig,l", po::value<string>(),
"Set the log4cxx logging configuration file")
("ready", po::value<std::string>()->default_value("tcp://127.0.0.1:5001"),
"Ready ZMQ endpoint from frameReceiver")
("release", po::value<std::string>()->default_value("tcp://127.0.0.1:5002"),
"Release frame ZMQ endpoint from frameReceiver")
("frames,f", po::value<unsigned int>()->default_value(1),
"Set the number of frames to be notified about before terminating")
("sharedbuf", po::value<std::string>()->default_value("FrameReceiverBuffer"),
"Set the name of the shared memory frame buffer")
("output,o", po::value<std::string>(),
"Name of HDF5 file to write frames to (default: no file writing)")
("processes,p", po::value<unsigned int>()->default_value(1),
"Number of concurrent file writer processes" )
("rank,r", po::value<unsigned int>()->default_value(0),
"The rank (index number) of the current file writer process in relation to the other concurrent ones")
;
// Group the variables for parsing at the command line and/or from the configuration file
po::options_description cmdline_options;
cmdline_options.add(generic).add(config);
po::options_description config_file_options;
config_file_options.add(config);
// Parse the command line options
po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
po::notify(vm);
// If the command-line help option was given, print help and exit
if (vm.count("help"))
{
std::cout << "usage: fileWriter [options]" << std::endl << std::endl;
std::cout << cmdline_options << std::endl;
exit(1);
}
// If the command line config option was given, parse the specified configuration
// file for additional options. Note that boost::program_options gives precedence
// to the first instance occurring. In this case, that implies that command-line
// options have precedence over equivalent configuration file entries.
if (vm.count("config"))
{
std::ifstream config_ifs(config_file.c_str());
if (config_ifs)
{
LOG4CXX_DEBUG(logger, "Parsing configuration file " << config_file);
po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);
po::notify(vm);
}
else
{
LOG4CXX_ERROR(logger, "Unable to open configuration file " << config_file << " for parsing");
exit(1);
}
}
if (vm.count("logconfig"))
{
PropertyConfigurator::configure(vm["logconfig"].as<string>());
LOG4CXX_DEBUG(logger, "log4cxx config file is set to " << vm["logconfig"].as<string>());
}
if (vm.count("ready"))
{
LOG4CXX_DEBUG(logger, "Setting frame ready notification ZMQ address to " << vm["ready"].as<string>());
}
if (vm.count("release"))
{
LOG4CXX_DEBUG(logger, "Setting frame release notification ZMQ address to " << vm["release"].as<string>());
}
if (vm.count("frames"))
{
LOG4CXX_DEBUG(logger, "Setting number of frames to receive to " << vm["frames"].as<unsigned int>());
}
if (vm.count("output"))
{
LOG4CXX_DEBUG(logger, "Writing frames to file: " << vm["output"].as<string>());
}
if (vm.count("processes"))
{
LOG4CXX_DEBUG(logger, "Number of concurrent filewriter processes: " << vm["processes"].as<unsigned int>());
}
if (vm.count("rank"))
{
LOG4CXX_DEBUG(logger, "This process rank (index): " << vm["rank"].as<unsigned int>());
}
}
catch (po::unknown_option &e)
{
LOG4CXX_WARN(logger, "CLI parsing error: " << e.what() << ". Will carry on...");
}
catch (Exception &e)
{
LOG4CXX_FATAL(logger, "Got Log4CXX exception: " << e.what());
throw;
}
catch (exception &e)
{
LOG4CXX_ERROR(logger, "Got exception:" << e.what());
throw;
}
catch (...)
{
LOG4CXX_FATAL(logger, "Exception of unknown type!");
throw;
}
}
int main(int argc, char** argv)
{
// Create a default basic logger configuration, which can be overridden by command-line option later
BasicConfigurator::configure();
LoggerPtr logger(Logger::getLogger("socketApp"));
po::variables_map vm;
parse_arguments(argc, argv, vm, logger);
//DataBlockPool::allocate(200, 1024);
boost::shared_ptr<filewriter::FileWriterController> fwc;
fwc = boost::shared_ptr<filewriter::FileWriterController>(new filewriter::FileWriterController());
filewriter::JSONSubscriber sh("tcp://127.0.0.1:5003");
sh.registerCallback(fwc);
sh.subscribe();
// Configure the shared memory setup of the file writer controller
std::string cfgString = "{" +
std::string("\"fr_release_cnxn\":\"") + vm["release"].as<string>() + std::string("\",") +
"\"fr_ready_cnxn\":\"" + vm["ready"].as<string>() + "\"," +
"\"fr_shared_mem\":\"" + vm["sharedbuf"].as<string>() + "\"" +
"}";
cfgString = "{\"fr_setup\": " + cfgString + "}";
boost::shared_ptr<JSONMessage> cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Now load the percival plugin
cfgString = "{" +
std::string("\"plugin_library\":\"./lib/libPercivalProcessPlugin.so\",") +
"\"plugin_index\":\"percival\"," +
"\"plugin_name\":\"PercivalProcessPlugin\"" +
"}";
cfgString = "{\"load_plugin\": " + cfgString + "}";
cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Connect the Percival plugin to the shared memory controller
cfgString = "{" +
std::string("\"plugin_index\":\"percival\",") +
"\"plugin_connect_to\":\"frame_receiver\"" +
"}";
cfgString = "{\"connect_plugin\": " + cfgString + "}";
cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Disconnect the HDF5 plugin from the shared memory controller
cfgString = "{" +
std::string("\"plugin_index\":\"hdf\",") +
"\"plugin_disconnect_from\":\"frame_receiver\"" +
"}";
cfgString = "{\"disconnect_plugin\": " + cfgString + "}";
cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Connect the HDF5 plugin to the Percival plugin
cfgString = "{" +
std::string("\"plugin_index\":\"hdf\",") +
"\"plugin_connect_to\":\"percival\"" +
"}";
cfgString = "{\"connect_plugin\": " + cfgString + "}";
cfg = boost::shared_ptr<JSONMessage>(new JSONMessage(cfgString));
fwc->configure(cfg);
// Now wait for the shutdown
fwc->waitForShutdown();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "core/Setup.h"
#if OUZEL_COMPILE_DIRECT3D11
#include "ShaderResourceD3D11.hpp"
#include "RenderDeviceD3D11.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT getVertexFormat(DataType dataType)
{
switch (dataType)
{
case DataType::BYTE: return DXGI_FORMAT_R8_SINT;
case DataType::BYTE_NORM: return DXGI_FORMAT_R8_SNORM;
case DataType::UNSIGNED_BYTE: return DXGI_FORMAT_R8_UINT;
case DataType::UNSIGNED_BYTE_NORM: return DXGI_FORMAT_R8_UNORM;
case DataType::BYTE_VECTOR2: return DXGI_FORMAT_R8G8_SINT;
case DataType::BYTE_VECTOR2_NORM: return DXGI_FORMAT_R8G8_SNORM;
case DataType::UNSIGNED_BYTE_VECTOR2: return DXGI_FORMAT_R8G8_UINT;
case DataType::UNSIGNED_BYTE_VECTOR2_NORM: return DXGI_FORMAT_R8G8_UNORM;
case DataType::BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::BYTE_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_BYTE_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::BYTE_VECTOR4: return DXGI_FORMAT_R8G8B8A8_SINT;
case DataType::BYTE_VECTOR4_NORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case DataType::UNSIGNED_BYTE_VECTOR4: return DXGI_FORMAT_R8G8B8A8_UINT;
case DataType::UNSIGNED_BYTE_VECTOR4_NORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DataType::SHORT: return DXGI_FORMAT_R16_SINT;
case DataType::SHORT_NORM: return DXGI_FORMAT_R16_SNORM;
case DataType::UNSIGNED_SHORT: return DXGI_FORMAT_R16_UINT;
case DataType::UNSIGNED_SHORT_NORM: return DXGI_FORMAT_R16_UNORM;
case DataType::SHORT_VECTOR2: return DXGI_FORMAT_R16G16_SINT;
case DataType::SHORT_VECTOR2_NORM: return DXGI_FORMAT_R16G16_SNORM;
case DataType::UNSIGNED_SHORT_VECTOR2: return DXGI_FORMAT_R16G16_UINT;
case DataType::UNSIGNED_SHORT_VECTOR2_NORM: return DXGI_FORMAT_R16G16_UNORM;
case DataType::SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::SHORT_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_SHORT_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::SHORT_VECTOR4: return DXGI_FORMAT_R16G16B16A16_SINT;
case DataType::SHORT_VECTOR4_NORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case DataType::UNSIGNED_SHORT_VECTOR4: return DXGI_FORMAT_R16G16B16A16_UINT;
case DataType::UNSIGNED_SHORT_VECTOR4_NORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case DataType::INTEGER: return DXGI_FORMAT_R32_SINT;
case DataType::UNSIGNED_INTEGER: return DXGI_FORMAT_R32_UINT;
case DataType::INTEGER_VECTOR2: return DXGI_FORMAT_R32G32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR2: return DXGI_FORMAT_R32G32_UINT;
case DataType::INTEGER_VECTOR3: return DXGI_FORMAT_R32G32B32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR3: return DXGI_FORMAT_R32G32B32_UINT;
case DataType::INTEGER_VECTOR4: return DXGI_FORMAT_R32G32B32A32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR4: return DXGI_FORMAT_R32G32B32A32_UINT;
case DataType::FLOAT: return DXGI_FORMAT_R32_FLOAT;
case DataType::FLOAT_VECTOR2: return DXGI_FORMAT_R32G32_FLOAT;
case DataType::FLOAT_VECTOR3: return DXGI_FORMAT_R32G32B32_FLOAT;
case DataType::FLOAT_VECTOR4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DataType::FLOAT_MATRIX3: return DXGI_FORMAT_UNKNOWN;
case DataType::FLOAT_MATRIX4: return DXGI_FORMAT_UNKNOWN;
case DataType::NONE: return DXGI_FORMAT_UNKNOWN;
}
return DXGI_FORMAT_UNKNOWN;
}
ShaderResourceD3D11::ShaderResourceD3D11(RenderDeviceD3D11& initRenderDeviceD3D11):
renderDeviceD3D11(initRenderDeviceD3D11)
{
}
ShaderResourceD3D11::~ShaderResourceD3D11()
{
if (fragmentShader)
fragmentShader->Release();
if (vertexShader)
vertexShader->Release();
if (inputLayout)
inputLayout->Release();
if (fragmentShaderConstantBuffer)
fragmentShaderConstantBuffer->Release();
if (vertexShaderConstantBuffer)
vertexShaderConstantBuffer->Release();
}
bool ShaderResourceD3D11::init(const std::vector<uint8_t>& newFragmentShader,
const std::vector<uint8_t>& newVertexShader,
const std::set<Vertex::Attribute::Usage>& newVertexAttributes,
const std::vector<Shader::ConstantInfo>& newFragmentShaderConstantInfo,
const std::vector<Shader::ConstantInfo>& newVertexShaderConstantInfo,
uint32_t newFragmentShaderDataAlignment,
uint32_t newVertexShaderDataAlignment,
const std::string& newFragmentShaderFunction,
const std::string& newVertexShaderFunction)
{
if (!ShaderResource::init(newFragmentShader,
newVertexShader,
newVertexAttributes,
newFragmentShaderConstantInfo,
newVertexShaderConstantInfo,
newFragmentShaderDataAlignment,
newVertexShaderDataAlignment,
newFragmentShaderFunction,
newVertexShaderFunction))
{
return false;
}
if (fragmentShader) fragmentShader->Release();
HRESULT hr = renderDeviceD3D11.getDevice()->CreateFragmentShader(fragmentShaderData.data(), fragmentShaderData.size(), nullptr, &fragmentShader);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create a Direct3D 11 pixel shader, error: " << hr;
return false;
}
if (vertexShader) vertexShader->Release();
hr = renderDeviceD3D11.getDevice()->CreateVertexShader(vertexShaderData.data(), vertexShaderData.size(), nullptr, &vertexShader);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create a Direct3D 11 vertex shader, error: " << hr;
return false;
}
std::vector<D3D11_INPUT_ELEMENT_DESC> vertexInputElements;
UINT offset = 0;
for (const Vertex::Attribute& vertexAttribute : Vertex::ATTRIBUTES)
{
if (vertexAttributes.find(vertexAttribute.usage) != vertexAttributes.end())
{
DXGI_FORMAT vertexFormat = getVertexFormat(vertexAttribute.dataType);
if (vertexFormat == DXGI_FORMAT_UNKNOWN)
{
Log(Log::Level::ERR) << "Invalid vertex format";
return false;
}
const char* semantic;
UINT index = 0;
switch (vertexAttribute.usage)
{
case Vertex::Attribute::Usage::BINORMAL:
semantic = "BINORMAL";
break;
case Vertex::Attribute::Usage::BLEND_INDICES:
semantic = "BLENDINDICES";
break;
case Vertex::Attribute::Usage::BLEND_WEIGHT:
semantic = "BLENDWEIGHT";
break;
case Vertex::Attribute::Usage::COLOR:
semantic = "COLOR";
break;
case Vertex::Attribute::Usage::NORMAL:
semantic = "NORMAL";
break;
case Vertex::Attribute::Usage::POSITION:
semantic = "POSITION";
break;
case Vertex::Attribute::Usage::POSITION_TRANSFORMED:
semantic = "POSITIONT";
break;
case Vertex::Attribute::Usage::POINT_SIZE:
semantic = "PSIZE";
break;
case Vertex::Attribute::Usage::TANGENT:
semantic = "TANGENT";
break;
case Vertex::Attribute::Usage::TEXTURE_COORDINATES0:
semantic = "TEXCOORD";
break;
case Vertex::Attribute::Usage::TEXTURE_COORDINATES1:
semantic = "TEXCOORD";
index = 1;
break;
default:
Log(Log::Level::ERR) << "Invalid vertex attribute usage";
return false;
}
vertexInputElements.push_back({
semantic, index,
vertexFormat,
0, offset, D3D11_INPUT_PER_VERTEX_DATA, 0
});
}
offset += getDataTypeSize(vertexAttribute.dataType);
}
if (inputLayout) inputLayout->Release();
hr = renderDeviceD3D11.getDevice()->CreateInputLayout(vertexInputElements.data(),
static_cast<UINT>(vertexInputElements.size()),
vertexShaderData.data(),
vertexShaderData.size(),
&inputLayout);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 input layout for vertex shader, error: " << hr;
return false;
}
if (!fragmentShaderConstantInfo.empty())
{
fragmentShaderConstantLocations.clear();
fragmentShaderConstantLocations.reserve(fragmentShaderConstantInfo.size());
fragmentShaderConstantSize = 0;
for (const Shader::ConstantInfo& info : fragmentShaderConstantInfo)
{
fragmentShaderConstantLocations.push_back({fragmentShaderConstantSize, info.size});
fragmentShaderConstantSize += info.size;
}
}
D3D11_BUFFER_DESC fragmentShaderConstantBufferDesc;
fragmentShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(fragmentShaderConstantSize);
fragmentShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
fragmentShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
fragmentShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
fragmentShaderConstantBufferDesc.MiscFlags = 0;
fragmentShaderConstantBufferDesc.StructureByteStride = 0;
if (fragmentShaderConstantBuffer) fragmentShaderConstantBuffer->Release();
hr = renderDeviceD3D11.getDevice()->CreateBuffer(&fragmentShaderConstantBufferDesc, nullptr, &fragmentShaderConstantBuffer);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr;
return false;
}
if (!vertexShaderConstantInfo.empty())
{
vertexShaderConstantLocations.clear();
vertexShaderConstantLocations.reserve(vertexShaderConstantInfo.size());
vertexShaderConstantSize = 0;
for (const Shader::ConstantInfo& info : vertexShaderConstantInfo)
{
vertexShaderConstantLocations.push_back({vertexShaderConstantSize, info.size});
vertexShaderConstantSize += info.size;
}
}
D3D11_BUFFER_DESC vertexShaderConstantBufferDesc;
vertexShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(vertexShaderConstantSize);
vertexShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
vertexShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexShaderConstantBufferDesc.MiscFlags = 0;
vertexShaderConstantBufferDesc.StructureByteStride = 0;
if (vertexShaderConstantBuffer) vertexShaderConstantBuffer->Release();
hr = renderDeviceD3D11.getDevice()->CreateBuffer(&vertexShaderConstantBufferDesc, nullptr, &vertexShaderConstantBuffer);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr;
return false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
#endif
<commit_msg>Fix the D3D11 pixel shader creation<commit_after>// Copyright (C) 2018 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "core/Setup.h"
#if OUZEL_COMPILE_DIRECT3D11
#include "ShaderResourceD3D11.hpp"
#include "RenderDeviceD3D11.hpp"
#include "utils/Log.hpp"
namespace ouzel
{
namespace graphics
{
static DXGI_FORMAT getVertexFormat(DataType dataType)
{
switch (dataType)
{
case DataType::BYTE: return DXGI_FORMAT_R8_SINT;
case DataType::BYTE_NORM: return DXGI_FORMAT_R8_SNORM;
case DataType::UNSIGNED_BYTE: return DXGI_FORMAT_R8_UINT;
case DataType::UNSIGNED_BYTE_NORM: return DXGI_FORMAT_R8_UNORM;
case DataType::BYTE_VECTOR2: return DXGI_FORMAT_R8G8_SINT;
case DataType::BYTE_VECTOR2_NORM: return DXGI_FORMAT_R8G8_SNORM;
case DataType::UNSIGNED_BYTE_VECTOR2: return DXGI_FORMAT_R8G8_UINT;
case DataType::UNSIGNED_BYTE_VECTOR2_NORM: return DXGI_FORMAT_R8G8_UNORM;
case DataType::BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::BYTE_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_BYTE_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_BYTE_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::BYTE_VECTOR4: return DXGI_FORMAT_R8G8B8A8_SINT;
case DataType::BYTE_VECTOR4_NORM: return DXGI_FORMAT_R8G8B8A8_SNORM;
case DataType::UNSIGNED_BYTE_VECTOR4: return DXGI_FORMAT_R8G8B8A8_UINT;
case DataType::UNSIGNED_BYTE_VECTOR4_NORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case DataType::SHORT: return DXGI_FORMAT_R16_SINT;
case DataType::SHORT_NORM: return DXGI_FORMAT_R16_SNORM;
case DataType::UNSIGNED_SHORT: return DXGI_FORMAT_R16_UINT;
case DataType::UNSIGNED_SHORT_NORM: return DXGI_FORMAT_R16_UNORM;
case DataType::SHORT_VECTOR2: return DXGI_FORMAT_R16G16_SINT;
case DataType::SHORT_VECTOR2_NORM: return DXGI_FORMAT_R16G16_SNORM;
case DataType::UNSIGNED_SHORT_VECTOR2: return DXGI_FORMAT_R16G16_UINT;
case DataType::UNSIGNED_SHORT_VECTOR2_NORM: return DXGI_FORMAT_R16G16_UNORM;
case DataType::SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::SHORT_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_SHORT_VECTOR3: return DXGI_FORMAT_UNKNOWN;
case DataType::UNSIGNED_SHORT_VECTOR3_NORM: return DXGI_FORMAT_UNKNOWN;
case DataType::SHORT_VECTOR4: return DXGI_FORMAT_R16G16B16A16_SINT;
case DataType::SHORT_VECTOR4_NORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case DataType::UNSIGNED_SHORT_VECTOR4: return DXGI_FORMAT_R16G16B16A16_UINT;
case DataType::UNSIGNED_SHORT_VECTOR4_NORM: return DXGI_FORMAT_R16G16B16A16_UNORM;
case DataType::INTEGER: return DXGI_FORMAT_R32_SINT;
case DataType::UNSIGNED_INTEGER: return DXGI_FORMAT_R32_UINT;
case DataType::INTEGER_VECTOR2: return DXGI_FORMAT_R32G32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR2: return DXGI_FORMAT_R32G32_UINT;
case DataType::INTEGER_VECTOR3: return DXGI_FORMAT_R32G32B32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR3: return DXGI_FORMAT_R32G32B32_UINT;
case DataType::INTEGER_VECTOR4: return DXGI_FORMAT_R32G32B32A32_SINT;
case DataType::UNSIGNED_INTEGER_VECTOR4: return DXGI_FORMAT_R32G32B32A32_UINT;
case DataType::FLOAT: return DXGI_FORMAT_R32_FLOAT;
case DataType::FLOAT_VECTOR2: return DXGI_FORMAT_R32G32_FLOAT;
case DataType::FLOAT_VECTOR3: return DXGI_FORMAT_R32G32B32_FLOAT;
case DataType::FLOAT_VECTOR4: return DXGI_FORMAT_R32G32B32A32_FLOAT;
case DataType::FLOAT_MATRIX3: return DXGI_FORMAT_UNKNOWN;
case DataType::FLOAT_MATRIX4: return DXGI_FORMAT_UNKNOWN;
case DataType::NONE: return DXGI_FORMAT_UNKNOWN;
}
return DXGI_FORMAT_UNKNOWN;
}
ShaderResourceD3D11::ShaderResourceD3D11(RenderDeviceD3D11& initRenderDeviceD3D11):
renderDeviceD3D11(initRenderDeviceD3D11)
{
}
ShaderResourceD3D11::~ShaderResourceD3D11()
{
if (fragmentShader)
fragmentShader->Release();
if (vertexShader)
vertexShader->Release();
if (inputLayout)
inputLayout->Release();
if (fragmentShaderConstantBuffer)
fragmentShaderConstantBuffer->Release();
if (vertexShaderConstantBuffer)
vertexShaderConstantBuffer->Release();
}
bool ShaderResourceD3D11::init(const std::vector<uint8_t>& newFragmentShader,
const std::vector<uint8_t>& newVertexShader,
const std::set<Vertex::Attribute::Usage>& newVertexAttributes,
const std::vector<Shader::ConstantInfo>& newFragmentShaderConstantInfo,
const std::vector<Shader::ConstantInfo>& newVertexShaderConstantInfo,
uint32_t newFragmentShaderDataAlignment,
uint32_t newVertexShaderDataAlignment,
const std::string& newFragmentShaderFunction,
const std::string& newVertexShaderFunction)
{
if (!ShaderResource::init(newFragmentShader,
newVertexShader,
newVertexAttributes,
newFragmentShaderConstantInfo,
newVertexShaderConstantInfo,
newFragmentShaderDataAlignment,
newVertexShaderDataAlignment,
newFragmentShaderFunction,
newVertexShaderFunction))
{
return false;
}
if (fragmentShader) fragmentShader->Release();
HRESULT hr = renderDeviceD3D11.getDevice()->CreatePixelShader(fragmentShaderData.data(), fragmentShaderData.size(), nullptr, &fragmentShader);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create a Direct3D 11 pixel shader, error: " << hr;
return false;
}
if (vertexShader) vertexShader->Release();
hr = renderDeviceD3D11.getDevice()->CreateVertexShader(vertexShaderData.data(), vertexShaderData.size(), nullptr, &vertexShader);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create a Direct3D 11 vertex shader, error: " << hr;
return false;
}
std::vector<D3D11_INPUT_ELEMENT_DESC> vertexInputElements;
UINT offset = 0;
for (const Vertex::Attribute& vertexAttribute : Vertex::ATTRIBUTES)
{
if (vertexAttributes.find(vertexAttribute.usage) != vertexAttributes.end())
{
DXGI_FORMAT vertexFormat = getVertexFormat(vertexAttribute.dataType);
if (vertexFormat == DXGI_FORMAT_UNKNOWN)
{
Log(Log::Level::ERR) << "Invalid vertex format";
return false;
}
const char* semantic;
UINT index = 0;
switch (vertexAttribute.usage)
{
case Vertex::Attribute::Usage::BINORMAL:
semantic = "BINORMAL";
break;
case Vertex::Attribute::Usage::BLEND_INDICES:
semantic = "BLENDINDICES";
break;
case Vertex::Attribute::Usage::BLEND_WEIGHT:
semantic = "BLENDWEIGHT";
break;
case Vertex::Attribute::Usage::COLOR:
semantic = "COLOR";
break;
case Vertex::Attribute::Usage::NORMAL:
semantic = "NORMAL";
break;
case Vertex::Attribute::Usage::POSITION:
semantic = "POSITION";
break;
case Vertex::Attribute::Usage::POSITION_TRANSFORMED:
semantic = "POSITIONT";
break;
case Vertex::Attribute::Usage::POINT_SIZE:
semantic = "PSIZE";
break;
case Vertex::Attribute::Usage::TANGENT:
semantic = "TANGENT";
break;
case Vertex::Attribute::Usage::TEXTURE_COORDINATES0:
semantic = "TEXCOORD";
break;
case Vertex::Attribute::Usage::TEXTURE_COORDINATES1:
semantic = "TEXCOORD";
index = 1;
break;
default:
Log(Log::Level::ERR) << "Invalid vertex attribute usage";
return false;
}
vertexInputElements.push_back({
semantic, index,
vertexFormat,
0, offset, D3D11_INPUT_PER_VERTEX_DATA, 0
});
}
offset += getDataTypeSize(vertexAttribute.dataType);
}
if (inputLayout) inputLayout->Release();
hr = renderDeviceD3D11.getDevice()->CreateInputLayout(vertexInputElements.data(),
static_cast<UINT>(vertexInputElements.size()),
vertexShaderData.data(),
vertexShaderData.size(),
&inputLayout);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 input layout for vertex shader, error: " << hr;
return false;
}
if (!fragmentShaderConstantInfo.empty())
{
fragmentShaderConstantLocations.clear();
fragmentShaderConstantLocations.reserve(fragmentShaderConstantInfo.size());
fragmentShaderConstantSize = 0;
for (const Shader::ConstantInfo& info : fragmentShaderConstantInfo)
{
fragmentShaderConstantLocations.push_back({fragmentShaderConstantSize, info.size});
fragmentShaderConstantSize += info.size;
}
}
D3D11_BUFFER_DESC fragmentShaderConstantBufferDesc;
fragmentShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(fragmentShaderConstantSize);
fragmentShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
fragmentShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
fragmentShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
fragmentShaderConstantBufferDesc.MiscFlags = 0;
fragmentShaderConstantBufferDesc.StructureByteStride = 0;
if (fragmentShaderConstantBuffer) fragmentShaderConstantBuffer->Release();
hr = renderDeviceD3D11.getDevice()->CreateBuffer(&fragmentShaderConstantBufferDesc, nullptr, &fragmentShaderConstantBuffer);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr;
return false;
}
if (!vertexShaderConstantInfo.empty())
{
vertexShaderConstantLocations.clear();
vertexShaderConstantLocations.reserve(vertexShaderConstantInfo.size());
vertexShaderConstantSize = 0;
for (const Shader::ConstantInfo& info : vertexShaderConstantInfo)
{
vertexShaderConstantLocations.push_back({vertexShaderConstantSize, info.size});
vertexShaderConstantSize += info.size;
}
}
D3D11_BUFFER_DESC vertexShaderConstantBufferDesc;
vertexShaderConstantBufferDesc.ByteWidth = static_cast<UINT>(vertexShaderConstantSize);
vertexShaderConstantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
vertexShaderConstantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
vertexShaderConstantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vertexShaderConstantBufferDesc.MiscFlags = 0;
vertexShaderConstantBufferDesc.StructureByteStride = 0;
if (vertexShaderConstantBuffer) vertexShaderConstantBuffer->Release();
hr = renderDeviceD3D11.getDevice()->CreateBuffer(&vertexShaderConstantBufferDesc, nullptr, &vertexShaderConstantBuffer);
if (FAILED(hr))
{
Log(Log::Level::ERR) << "Failed to create Direct3D 11 constant buffer, error: " << hr;
return false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
#endif
<|endoftext|> |
<commit_before>// Copyright 2012 Andrew C. Morrow
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef included_108FBB04_F426_414D_9EDD_B4D2AF941E96
#define included_108FBB04_F426_414D_9EDD_B4D2AF941E96
#include <cassert>
#include <initializer_list>
#include <memory>
#include <system_error>
#include <type_traits>
namespace acm {
namespace detail {
namespace adl_swap_ns {
using std::swap;
template <class T>
struct is_nothrow_swappable_test {
static bool constexpr value = noexcept(swap(std::declval<T&>(), std::declval<T&>()));
};
} // namespace adl_swap_ns
// This really should be part of C++
template <class T>
struct is_nothrow_swappable
: std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<T>::value>
{};
} // namespace detail
template<typename E, typename T>
class error_or {
public:
using error_type = E;
using value_type = T;
inline error_or() noexcept(std::is_nothrow_default_constructible<value_type>::value) {
new(&val_.value) value_type;
}
inline error_or(error_type error) noexcept(std::is_nothrow_move_constructible<error_type>::value)
: ok_(false) {
assert(error);
new(&val_.error) error_type(std::move(error));
}
inline error_or(value_type value) noexcept(std::is_nothrow_move_constructible<value_type>::value) {
new(&val_.value) value_type(std::move(value));
}
template<typename U = value_type>
inline error_or(std::initializer_list<typename U::value_type> values) noexcept(std::is_nothrow_constructible<U, std::initializer_list<typename U::value_type>>::value) {
new(&val_.value) value_type(values);
}
// template<typename... Args>
// inline error_or(Args&&... args) noexcept(std::is_nothrow_constructible<value_type, Args...>::value)
// {
// new(&val_.value) value_type(std::forward<Args>(args)...);
// }
inline error_or(const error_or& other) noexcept(std::is_nothrow_copy_constructible<error_type>::value and
std::is_nothrow_copy_constructible<value_type>::value) {
if (other.ok_)
new(&val_.value) value_type(other.val_.value);
else
new(&val_.error) error_type(other.val_.error);
ok_ = other.ok_;
}
inline error_or(error_or&& other) noexcept((std::is_nothrow_move_constructible<error_type>::value or
std::is_nothrow_copy_constructible<error_type>::value) and
(std::is_nothrow_move_constructible<value_type>::value or
std::is_nothrow_copy_constructible<value_type>::value)) {
if (other.ok_)
new(&val_.value) value_type(std::move_if_noexcept(other.val_.value));
else
new(&val_.error) error_type(std::move_if_noexcept(other.val_.error));
ok_ = other.ok_;
}
template<typename U>
inline error_or(const error_or<error_type, U>& other) noexcept(std::is_nothrow_copy_constructible<error_type>::value and
std::is_nothrow_copy_constructible<value_type>::value) {
if (other.ok_)
new(&val_.value) value_type(other.val_.value);
else
new(&val_.error) error_type(other.val_.error);
ok_ = other.ok_;
}
template<typename U>
inline error_or(error_or<error_type, U>&& other) noexcept((std::is_nothrow_move_constructible<error_type>::value or
std::is_nothrow_copy_constructible<error_type>::value) and
(std::is_nothrow_constructible<value_type, typename std::add_rvalue_reference<U>::type>::value or
std::is_nothrow_constructible<value_type, typename std::add_lvalue_reference<U>::type>::value)) {
if (other.ok_)
new(&val_.value) value_type(move_if_noexcept_from(other.val_.value));
else
new(&val_.error) error_type(std::move_if_noexcept(other.val_.error));
ok_ = other.ok_;
}
void swap(error_or& other) noexcept {
other.sfinae_swap(*this);
}
friend inline void swap(error_or& a, error_or& b) noexcept {
a.swap(b);
}
inline error_or& operator=(error_type error) noexcept(std::is_nothrow_constructible<error_or, typename std::add_rvalue_reference<error_type>::type>::value) {
error_or(std::move(error)).swap(*this);
return *this;
}
inline error_or& operator=(value_type value) noexcept(std::is_nothrow_constructible<error_or, typename std::add_rvalue_reference<value_type>::type>::value) {
error_or(std::move(value)).swap(*this);
return *this;
}
inline error_or& operator=(error_or other) noexcept(std::is_nothrow_move_constructible<error_or>::value) {
error_or(std::move(other)).swap(*this);
return *this;
}
template<typename U>
inline error_or& operator=(error_or<error_type, U> other) noexcept(std::is_nothrow_constructible<error_or, error_or<E, U>&&>::value) {
error_or(std::move(other)).swap(*this);
return *this;
}
inline ~error_or() noexcept(std::is_nothrow_destructible<error_type>::value and
std::is_nothrow_destructible<value_type>::value) {
if (ok_)
val_.value.~value_type();
else
val_.error.~error_type();
}
inline bool ok() const noexcept {
return ok_;
}
inline explicit operator bool() const noexcept {
return ok_;
}
inline const error_type& error() const noexcept {
assert(!ok_);
return val_.error;
}
inline value_type& value() noexcept {
assert(ok_);
return val_.value;
}
inline const value_type& value() const noexcept {
assert(ok_);
return val_.value;
}
inline error_type&& release_error() noexcept {
assert(!ok_);
return std::move(val_.error);
}
inline value_type&& release_value() noexcept {
assert(ok_);
return std::move(val_.value);
}
private:
union val {
// The lifecycle of members is handled by the enclosing class.
inline val() noexcept {}
inline ~val() noexcept {}
value_type value;
error_type error;
} val_;
bool ok_ = true;
static constexpr bool is_nothrow_swappable =
detail::is_nothrow_swappable<error_type>::value and
detail::is_nothrow_swappable<value_type>::value and
std::is_nothrow_move_constructible<error_type>::value and
std::is_nothrow_move_constructible<value_type>::value and
std::is_nothrow_destructible<error_type>::value and
std::is_nothrow_destructible<value_type>::value;
template<typename U = value_type>
typename std::enable_if<error_or<error_type, U>::is_nothrow_swappable>::type sfinae_swap(error_or& other) noexcept {
using std::swap;
if (ok_ == other.ok_) {
if (ok_)
swap(val_.value, other.val_.value);
else
swap(val_.error, other.val_.error);
} else {
if (ok_) {
new(&val_.error) error_type(std::move(other.val_.error));
new(&other.val_.value) value_type(std::move(val_.value));
val_.value.~value_type();
other.val_.error.~error_type();
} else {
new(&other.val_.error) error_type(std::move(val_.error));
new(&val_.value) value_type(std::move(other.val_.value));
other.val_.value.~value_type();
val_.error.~error_type();
}
swap(ok_, other.ok_);
}
}
template<typename U>
typename std::conditional
<
!std::is_nothrow_constructible<value_type, typename std::add_rvalue_reference<U>::type>::value and std::is_constructible<U, typename std::add_lvalue_reference<U>::type>::value,
const U&,
U&&
>::type
move_if_noexcept_from(U& u) {
return std::move(u);
}
};
template<typename E1, typename T1, typename E2, typename T2>
bool operator==(const error_or<E1, T1>& lhs, const error_or<E2, T2>& rhs) noexcept(noexcept(lhs.value() == rhs.value()) and
noexcept(lhs.error() == rhs.error())) {
if (lhs.ok() == rhs.ok()) {
if (lhs.ok()) {
return lhs.value() == rhs.value();
} else {
return lhs.error() == rhs.error();
}
}
return false;
}
template<typename E1, typename T1, typename E2, typename T2>
bool operator!=(const error_or<E1, T1>& lhs, const error_or<E2, T2>& rhs) noexcept(noexcept(lhs == rhs)) {
return not lhs == rhs;
}
template<typename T>
using error_code_or = error_or<std::error_code, T>;
template<typename T>
using error_condition_or = error_or<std::error_condition, T>;
template<typename T>
using error_code_or_unique = error_code_or<std::unique_ptr<T>>;
template<typename T>
using error_condition_or_unique = error_condition_or<std::unique_ptr<T>>;
} // namespace acm
#endif // included_108FBB04_F426_414D_9EDD_B4D2AF941E96
<commit_msg>Make error_or final, it is not intended for use as a base class<commit_after>// Copyright 2012 Andrew C. Morrow
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef included_108FBB04_F426_414D_9EDD_B4D2AF941E96
#define included_108FBB04_F426_414D_9EDD_B4D2AF941E96
#include <cassert>
#include <initializer_list>
#include <memory>
#include <system_error>
#include <type_traits>
namespace acm {
namespace detail {
namespace adl_swap_ns {
using std::swap;
template <class T>
struct is_nothrow_swappable_test {
static bool constexpr value = noexcept(swap(std::declval<T&>(), std::declval<T&>()));
};
} // namespace adl_swap_ns
// This really should be part of C++
template <class T>
struct is_nothrow_swappable
: std::integral_constant<bool, adl_swap_ns::is_nothrow_swappable_test<T>::value>
{};
} // namespace detail
template<typename E, typename T>
class error_or final {
public:
using error_type = E;
using value_type = T;
inline error_or() noexcept(std::is_nothrow_default_constructible<value_type>::value) {
new(&val_.value) value_type;
}
inline error_or(error_type error) noexcept(std::is_nothrow_move_constructible<error_type>::value)
: ok_(false) {
assert(error);
new(&val_.error) error_type(std::move(error));
}
inline error_or(value_type value) noexcept(std::is_nothrow_move_constructible<value_type>::value) {
new(&val_.value) value_type(std::move(value));
}
template<typename U = value_type>
inline error_or(std::initializer_list<typename U::value_type> values) noexcept(std::is_nothrow_constructible<U, std::initializer_list<typename U::value_type>>::value) {
new(&val_.value) value_type(values);
}
// template<typename... Args>
// inline error_or(Args&&... args) noexcept(std::is_nothrow_constructible<value_type, Args...>::value)
// {
// new(&val_.value) value_type(std::forward<Args>(args)...);
// }
inline error_or(const error_or& other) noexcept(std::is_nothrow_copy_constructible<error_type>::value and
std::is_nothrow_copy_constructible<value_type>::value) {
if (other.ok_)
new(&val_.value) value_type(other.val_.value);
else
new(&val_.error) error_type(other.val_.error);
ok_ = other.ok_;
}
inline error_or(error_or&& other) noexcept((std::is_nothrow_move_constructible<error_type>::value or
std::is_nothrow_copy_constructible<error_type>::value) and
(std::is_nothrow_move_constructible<value_type>::value or
std::is_nothrow_copy_constructible<value_type>::value)) {
if (other.ok_)
new(&val_.value) value_type(std::move_if_noexcept(other.val_.value));
else
new(&val_.error) error_type(std::move_if_noexcept(other.val_.error));
ok_ = other.ok_;
}
template<typename U>
inline error_or(const error_or<error_type, U>& other) noexcept(std::is_nothrow_copy_constructible<error_type>::value and
std::is_nothrow_copy_constructible<value_type>::value) {
if (other.ok_)
new(&val_.value) value_type(other.val_.value);
else
new(&val_.error) error_type(other.val_.error);
ok_ = other.ok_;
}
template<typename U>
inline error_or(error_or<error_type, U>&& other) noexcept((std::is_nothrow_move_constructible<error_type>::value or
std::is_nothrow_copy_constructible<error_type>::value) and
(std::is_nothrow_constructible<value_type, typename std::add_rvalue_reference<U>::type>::value or
std::is_nothrow_constructible<value_type, typename std::add_lvalue_reference<U>::type>::value)) {
if (other.ok_)
new(&val_.value) value_type(move_if_noexcept_from(other.val_.value));
else
new(&val_.error) error_type(std::move_if_noexcept(other.val_.error));
ok_ = other.ok_;
}
void swap(error_or& other) noexcept {
other.sfinae_swap(*this);
}
friend inline void swap(error_or& a, error_or& b) noexcept {
a.swap(b);
}
inline error_or& operator=(error_type error) noexcept(std::is_nothrow_constructible<error_or, typename std::add_rvalue_reference<error_type>::type>::value) {
error_or(std::move(error)).swap(*this);
return *this;
}
inline error_or& operator=(value_type value) noexcept(std::is_nothrow_constructible<error_or, typename std::add_rvalue_reference<value_type>::type>::value) {
error_or(std::move(value)).swap(*this);
return *this;
}
inline error_or& operator=(error_or other) noexcept(std::is_nothrow_move_constructible<error_or>::value) {
error_or(std::move(other)).swap(*this);
return *this;
}
template<typename U>
inline error_or& operator=(error_or<error_type, U> other) noexcept(std::is_nothrow_constructible<error_or, error_or<E, U>&&>::value) {
error_or(std::move(other)).swap(*this);
return *this;
}
inline ~error_or() noexcept(std::is_nothrow_destructible<error_type>::value and
std::is_nothrow_destructible<value_type>::value) {
if (ok_)
val_.value.~value_type();
else
val_.error.~error_type();
}
inline bool ok() const noexcept {
return ok_;
}
inline explicit operator bool() const noexcept {
return ok_;
}
inline const error_type& error() const noexcept {
assert(!ok_);
return val_.error;
}
inline value_type& value() noexcept {
assert(ok_);
return val_.value;
}
inline const value_type& value() const noexcept {
assert(ok_);
return val_.value;
}
inline error_type&& release_error() noexcept {
assert(!ok_);
return std::move(val_.error);
}
inline value_type&& release_value() noexcept {
assert(ok_);
return std::move(val_.value);
}
private:
union val {
// The lifecycle of members is handled by the enclosing class.
inline val() noexcept {}
inline ~val() noexcept {}
value_type value;
error_type error;
} val_;
bool ok_ = true;
static constexpr bool is_nothrow_swappable =
detail::is_nothrow_swappable<error_type>::value and
detail::is_nothrow_swappable<value_type>::value and
std::is_nothrow_move_constructible<error_type>::value and
std::is_nothrow_move_constructible<value_type>::value and
std::is_nothrow_destructible<error_type>::value and
std::is_nothrow_destructible<value_type>::value;
template<typename U = value_type>
typename std::enable_if<error_or<error_type, U>::is_nothrow_swappable>::type sfinae_swap(error_or& other) noexcept {
using std::swap;
if (ok_ == other.ok_) {
if (ok_)
swap(val_.value, other.val_.value);
else
swap(val_.error, other.val_.error);
} else {
if (ok_) {
new(&val_.error) error_type(std::move(other.val_.error));
new(&other.val_.value) value_type(std::move(val_.value));
val_.value.~value_type();
other.val_.error.~error_type();
} else {
new(&other.val_.error) error_type(std::move(val_.error));
new(&val_.value) value_type(std::move(other.val_.value));
other.val_.value.~value_type();
val_.error.~error_type();
}
swap(ok_, other.ok_);
}
}
template<typename U>
typename std::conditional
<
!std::is_nothrow_constructible<value_type, typename std::add_rvalue_reference<U>::type>::value and std::is_constructible<U, typename std::add_lvalue_reference<U>::type>::value,
const U&,
U&&
>::type
move_if_noexcept_from(U& u) {
return std::move(u);
}
};
template<typename E1, typename T1, typename E2, typename T2>
bool operator==(const error_or<E1, T1>& lhs, const error_or<E2, T2>& rhs) noexcept(noexcept(lhs.value() == rhs.value()) and
noexcept(lhs.error() == rhs.error())) {
if (lhs.ok() == rhs.ok()) {
if (lhs.ok()) {
return lhs.value() == rhs.value();
} else {
return lhs.error() == rhs.error();
}
}
return false;
}
template<typename E1, typename T1, typename E2, typename T2>
bool operator!=(const error_or<E1, T1>& lhs, const error_or<E2, T2>& rhs) noexcept(noexcept(lhs == rhs)) {
return not lhs == rhs;
}
template<typename T>
using error_code_or = error_or<std::error_code, T>;
template<typename T>
using error_condition_or = error_or<std::error_condition, T>;
template<typename T>
using error_code_or_unique = error_code_or<std::unique_ptr<T>>;
template<typename T>
using error_condition_or_unique = error_condition_or<std::unique_ptr<T>>;
} // namespace acm
#endif // included_108FBB04_F426_414D_9EDD_B4D2AF941E96
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.